repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
posthog | posthog/dags/common/overrides_manager.py | .py | import time
import uuid
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import TYPE_CHECKING, Generic, TypeVar
from clickhouse_driver import Client
from posthog import settings
from posthog.clickhouse.cluster import AlterTableMutationRunner, LightweightDeleteMutationRunner
if TYPE_C... | 158 | 5,227 |
posthog | posthog/dags/common/__init__.py | .py | from .common import (
check_for_concurrent_runs,
chunk_ranges,
dagster_tags,
settings_with_log_comment,
skip_if_already_running,
)
from .owners import JobOwners
__all__ = [
"JobOwners",
"check_for_concurrent_runs",
"chunk_ranges",
"dagster_tags",
"settings_with_log_comment",
... | 18 | 350 |
posthog | posthog/dags/common/owners.py | .py | from enum import Enum
class JobOwners(str, Enum):
TEAM_ANALYTICS_PLATFORM = "team-analytics-platform"
TEAM_BILLING = "team-billing"
TEAM_CLICKHOUSE = "team-clickhouse"
TEAM_DATA_MODELING = "team-data-modeling"
TEAM_DATA_STACK = "team-data-stack"
TEAM_DATA_TOOLS = "team-data-tools"
TEAM_ERR... | 24 | 835 |
posthog | posthog/dags/common/ops.py | .py | import math
import hashlib
import dagster
def _team_rollout_rank(team_id: int) -> int:
digest = hashlib.sha256(str(team_id).encode()).digest()
return int.from_bytes(digest[:8], byteorder="big")
def _filter_team_ids_for_rollout(team_ids: list[int], rollout_percentage: float) -> list[int]:
if rollout_per... | 96 | 3,615 |
posthog | posthog/dags/common/common.py | .py | from collections.abc import Callable
from contextlib import suppress
from datetime import datetime, timedelta
from functools import wraps
from typing import Optional
import dagster
from posthog.clickhouse import query_tagging
from posthog.clickhouse.query_tagging import DagsterTags
def dagster_tags(
context: da... | 120 | 4,080 |
posthog | posthog/dags/common/loggers.py | .py | """Dagster logger that routes op/asset logs through PostHog's structlog pipeline.
Dagster's default `colored_console_logger` writes plain colored text to the
process stdout. The PostHog Logs product is fed by the OTel collector scraping
each container's stdout and parsing structlog's JSON lines (see
`posthog/settings/... | 67 | 3,381 |
posthog | posthog/dags/common/resources.py | .py | import json
import socket
import asyncio
from collections.abc import Generator
from dataclasses import dataclass
from typing import Any
from urllib.parse import urlparse
import dagster
import psycopg2
import requests
import tenacity
import psycopg2.extras
import posthoganalytics
from clickhouse_driver.errors import Er... | 458 | 18,129 |
posthog | posthog/user_scripts/aggregate_funnel_test.py | .py | #!/usr/bin/python3
import sys
import json
import traceback
if __name__ == "__main__":
for line in sys.stdin:
try:
print(json.dumps({"result": line})) # noqa: T201
except Exception as e:
print(json.dumps({"result": json.dumps(str(e) + traceback.format_exc())}), end="\n") # ... | 13 | 358 |
posthog | posthog/user_scripts/aggregate_funnel_array_trends_test.py | .py | #!/usr/bin/python3
import sys
import json
if __name__ == "__main__":
for line in sys.stdin:
try:
print(json.dumps({"result": line})) # noqa: T201
except Exception as e:
print(json.dumps({"result": json.dumps(str(e))}), end="\n") # noqa: T201
sys.stdout.flush()
| 13 | 317 |
posthog | posthog/user_scripts/v6/aggregate_funnel_test.py | .py | #!/usr/bin/python3
import sys
import json
import traceback
if __name__ == "__main__":
for line in sys.stdin:
try:
# calculate_funnel_from_user_events(*parse_args(line))
print(json.dumps({"result": line})) # noqa: T201
except Exception as e:
print(json.dumps({"re... | 14 | 425 |
posthog | posthog/user_scripts/v6/aggregate_funnel_array_trends_test.py | .py | #!/usr/bin/python3
import sys
import json
if __name__ == "__main__":
for line in sys.stdin:
try:
print(json.dumps({"result": line})) # noqa: T201
# calculate_funnel_trends_from_user_events(*parse_args(line))
except Exception as e:
print(json.dumps({"result": js... | 14 | 391 |
posthog | posthog/temporal/utils.py | .py | import uuid
import typing
import dataclasses
from typing import Optional
# Dataclass living here to avoid circular reference
@dataclasses.dataclass
class ExternalDataWorkflowInputs:
team_id: int
external_data_source_id: uuid.UUID
external_data_schema_id: uuid.UUID | None = None
billable: bool = True
... | 40 | 1,049 |
posthog | posthog/temporal/schedule.py | .py | import asyncio
from dataclasses import asdict
from datetime import timedelta
from django.conf import settings
import structlog
from asgiref.sync import async_to_sync
from temporalio import common
from temporalio.client import (
Client,
Schedule,
ScheduleActionStartWorkflow,
ScheduleAlreadyRunningError... | 940 | 39,735 |
posthog | posthog/temporal/oauth.py | .py | from datetime import timedelta
from typing import Literal
from uuid import UUID
from django.conf import settings
from django.utils import timezone
from posthog.models import OAuthAccessToken, OAuthApplication
from posthog.models.utils import generate_random_oauth_access_token
from posthog.scopes import (
API_SCOP... | 287 | 12,661 |
posthog | posthog/temporal/codec_server.py | .py | import os
import hmac
from django.conf import settings
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
import structlog
from asgiref.sync import async_to_sync
from google.protobuf import json_format
f... | 100 | 3,413 |
posthog | posthog/temporal/experiments/workflows.py | .py | import asyncio
from datetime import timedelta
import temporalio.workflow
from temporalio.common import RetryPolicy
from posthog.temporal.common.base import PostHogWorkflow
with temporalio.workflow.unsafe.imports_passed_through():
from posthog.temporal.experiments.activities import (
backfill_experiment_m... | 186 | 6,910 |
posthog | posthog/temporal/experiments/utils.py | .py | from datetime import datetime
from typing import Union
import structlog
from posthog.schema import ExperimentFunnelMetric, ExperimentMeanMetric, ExperimentRatioMetric
from posthog.cdp.internal_events import InternalEventEvent, produce_internal_event
from products.experiments.backend.models.experiment import (
E... | 191 | 7,584 |
posthog | posthog/temporal/experiments/test_cache_warming.py | .py | from datetime import datetime
from uuid import uuid4
from freezegun import freeze_time
from posthog.test.base import _create_event, _create_person, flush_persons_and_events
from unittest.mock import patch
from django.core.cache import cache
from django.test import override_settings
from posthog.schema import CachedE... | 272 | 12,013 |
posthog | posthog/temporal/experiments/models.py | .py | import dataclasses
# Temporal retry ceiling for the per-metric calc activities. Shared with the activity code, which emits the
# terminal `experiment metric error` analytics event only on the final attempt — keep the RetryPolicy in
# workflows.py and this constant in lockstep or terminal failures get emitted early / n... | 68 | 1,759 |
posthog | posthog/temporal/experiments/__init__.py | .py | from posthog.temporal.experiments.activities import (
backfill_experiment_metric,
calculate_experiment_regular_metric,
calculate_experiment_saved_metric,
get_experiment_regular_metrics_for_hour,
get_experiment_saved_metrics_for_hour,
)
from posthog.temporal.experiments.workflows import (
Experim... | 39 | 1,174 |
posthog | posthog/temporal/experiments/test_recalculation_time_filter.py | .py | import datetime
from datetime import time
from zoneinfo import ZoneInfo
import pytest
from unittest.mock import patch
from posthog.models import Organization, Team, User
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.temporal.experiments.activities import _get_experiment_regular_... | 96 | 4,104 |
posthog | posthog/temporal/experiments/schedule.py | .py | from django.conf import settings
from temporalio.client import Client, Schedule, ScheduleActionStartWorkflow, ScheduleSpec
from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule
from posthog.temporal.experiments.models import (
ExperimentRegularMetricsWorkflowInputs,
... | 93 | 3,535 |
posthog | posthog/temporal/experiments/test_significance_transition.py | .py | from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
import pytest
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from parameterized import parameterized
from posthog.temporal.experiments.utils import check_significance_transition
from products.experiments.backen... | 251 | 10,036 |
posthog | posthog/temporal/experiments/activities.py | .py | from datetime import datetime, timedelta
from typing import Any, Union
from zoneinfo import ZoneInfo
from django.db import close_old_connections
from django.db.models import Q
import structlog
import temporalio.activity
from posthog.schema import ExperimentFunnelMetric, ExperimentMeanMetric, ExperimentQuery, Experim... | 650 | 24,085 |
posthog | posthog/temporal/logs_alerting/schedule.py | .py | """Schedule registration for the logs alert check workflow."""
from dataclasses import asdict
from django.conf import settings
from temporalio.client import (
Client,
Schedule,
ScheduleActionStartWorkflow,
ScheduleOverlapPolicy,
SchedulePolicy,
ScheduleSpec,
)
from posthog.temporal.common.sc... | 38 | 1,213 |
posthog | posthog/temporal/sync_person_distinct_ids/workflow.py | .py | import json
import typing
import datetime as dt
import dataclasses
import temporalio.common
import temporalio.workflow
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.sync_person_distinct_ids.activities import (
FindOrphanedPersonsInputs,
LookupPgDistinctIdsInputs,
MarkChOnl... | 212 | 9,022 |
posthog | posthog/temporal/sync_person_distinct_ids/__init__.py | .py | from posthog.temporal.sync_person_distinct_ids.activities import (
find_orphaned_persons,
lookup_pg_distinct_ids,
mark_ch_only_orphans_deleted,
sync_distinct_ids_to_ch,
)
from posthog.temporal.sync_person_distinct_ids.workflow import SyncPersonDistinctIdsWorkflow
WORKFLOWS = [
SyncPersonDistinctIds... | 19 | 468 |
posthog | posthog/temporal/sync_person_distinct_ids/activities.py | .py | import json
import dataclasses
import temporalio.activity
from psycopg import sql
from structlog import get_logger
from posthog.models.person.util import create_person, create_person_distinct_id
from posthog.persons_db import persons_db_aconnection
from posthog.temporal.common.clickhouse import get_client
from postho... | 378 | 14,319 |
posthog | posthog/temporal/sync_events_retention/types.py | .py | from dataclasses import dataclass
from typing import Optional
from posthog.slo.types import SloConfig
@dataclass(frozen=True)
class SyncEventsRetentionInput:
dry_run: bool
batch_size: int = 1000
slo: Optional[SloConfig] = None
@dataclass(frozen=True)
class SyncEventsRetentionResult:
total_processed... | 18 | 349 |
posthog | posthog/temporal/sync_events_retention/workflow.py | .py | from datetime import timedelta
from temporalio import common, workflow
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.sync_events_retention.activities import sync_events_retention
from posthog.temporal.sync_events_retention.types import SyncEventsRetentionInput, SyncEventsRetentionResu... | 30 | 1,151 |
posthog | posthog/temporal/sync_events_retention/__init__.py | .py | from posthog.temporal.sync_events_retention.activities import sync_events_retention
from posthog.temporal.sync_events_retention.workflow import SyncEventsRetentionWorkflow
SYNC_EVENTS_RETENTION_WORKFLOWS = [SyncEventsRetentionWorkflow]
SYNC_EVENTS_RETENTION_ACTIVITIES = [sync_events_retention]
| 6 | 296 |
posthog | posthog/temporal/sync_events_retention/activities.py | .py | import asyncio
from django.conf import settings
from temporalio import activity
from posthog.constants import AvailableFeature
from posthog.models.team import Team
from posthog.models.team.event_retention import parse_events_feature_to_months
from posthog.ph_client import ph_scoped_capture
from posthog.temporal.comm... | 96 | 4,218 |
posthog | posthog/temporal/salesforce_enrichment/stripe_workflow.py | .py | """Salesforce stripe/billing enrichment workflow.
Pushes Stripe customer data (customer id + billing address) and internal
``billing_customer.name`` onto Salesforce Account records. Runs daily with a
Redis-backed high-water mark so only rows that changed in the duckgres DWH since
the last successful run are touched. T... | 395 | 15,857 |
posthog | posthog/temporal/salesforce_enrichment/workflow.py | .py | import json
import math
import time
import typing
import asyncio
import datetime as dt
import dataclasses
from django.db import close_old_connections
from temporalio import activity, workflow
from temporalio.common import RetryPolicy
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.comm... | 239 | 8,993 |
posthog | posthog/temporal/salesforce_enrichment/__init__.py | .py | from posthog.temporal.salesforce_enrichment.conversations_slack_workflow import (
SalesforceConversationsSlackEnrichmentWorkflow,
aggregate_conversations_slack_signals_activity,
enrich_conversations_slack_page_activity,
)
from posthog.temporal.salesforce_enrichment.stripe_workflow import (
SalesforceStr... | 43 | 1,394 |
posthog | posthog/temporal/salesforce_enrichment/conversations_slack_workflow.py | .py | """Salesforce Conversations Slack enrichment workflow."""
import json
import time
import asyncio
import datetime as dt
import dataclasses
from itertools import batched
from typing import Any
from django.db import close_old_connections
from temporalio import activity, workflow
from temporalio.common import RetryPolic... | 341 | 13,250 |
posthog | posthog/temporal/salesforce_enrichment/usage_workflow.py | .py | """Salesforce usage enrichment workflow - enriches accounts with PostHog usage signals."""
import json
import time
import asyncio
import datetime as dt
import dataclasses
from itertools import batched
from typing import Any
from django.db import close_old_connections
from temporalio import activity, workflow
from te... | 394 | 15,747 |
posthog | posthog/temporal/ai/research_agent.py | .py | import json
import asyncio
from dataclasses import dataclass
from datetime import timedelta
from typing import Any, Optional
from uuid import UUID
import structlog
from temporalio import activity, workflow
from temporalio.common import RetryPolicy
from posthog.schema import HumanMessage, MaxBillingContext
from posth... | 112 | 3,968 |
posthog | posthog/temporal/ai/__init__.py | .py | from posthog.temporal.ai.anomaly_investigation import AnomalyInvestigationWorkflow, investigate_anomaly_activity
from posthog.temporal.ai.chat_agent import (
AssistantConversationRunnerWorkflow,
ChatAgentWorkflow,
process_chat_agent_activity,
process_conversation_activity,
)
from posthog.temporal.ai.che... | 76 | 2,749 |
posthog | posthog/temporal/ai/sync_vectors.py | .py | import json
import asyncio
from collections.abc import Coroutine
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Any, cast
from django.db.models import F, Q
import structlog
import posthoganalytics
import temporalio.common
import temporalio.activity
import temporalio.work... | 443 | 17,333 |
posthog | posthog/temporal/ai/chat_agent.py | .py | import json
import asyncio
from collections.abc import AsyncGenerator
from dataclasses import dataclass
from datetime import timedelta
from typing import Any, Optional, cast
from uuid import UUID, uuid4
from django.conf import settings
import pydantic
import structlog
from temporalio import activity, workflow
from te... | 335 | 13,174 |
posthog | posthog/temporal/ai/base.py | .py | from typing import Any
from posthog.temporal.common.base import PostHogWorkflow
class AgentBaseWorkflow(PostHogWorkflow):
"""Base temporal workflow for processing agents asynchronously."""
async def run(self, inputs: Any) -> None:
"""Execute the agent workflow."""
raise NotImplementedError
| 12 | 319 |
posthog | posthog/temporal/ai/slack_app/types.py | .py | """Shared dataclasses for PostHog Slack App Temporal workflows.
Living here (and not in the workflow modules) so activities split into this
package can take the inputs dataclass as their typed signature without
creating an import cycle with the workflow modules.
"""
from dataclasses import dataclass, field, fields
fr... | 203 | 8,324 |
posthog | posthog/temporal/ai/slack_app/posthog_code_slack_mention.py | .py | # Workflows in this module run on the max-ai temporal task queue.
import json
from datetime import timedelta
from typing import Any
from temporalio import workflow
from temporalio.common import RetryPolicy
from posthog.temporal.ai.slack_app import (
POSTHOG_CODE_SLACK_MENTION_PICKER_GUIDANCE,
PostHogCodeSlack... | 325 | 14,477 |
posthog | posthog/temporal/ai/slack_app/slack_app_mention.py | .py | # Workflows in this module run on the max-ai temporal task queue.
import json
from datetime import timedelta
from typing import Any
from temporalio import exceptions, workflow
from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
from posthog.temporal.ai.slack_app import (
derive_mention_workflow_id,
... | 257 | 13,170 |
posthog | posthog/temporal/ai/slack_app/__init__.py | .py | """Temporal activities for the PostHog Slack App.
Activities living here run on ``settings.TASKS_TASK_QUEUE`` and are imported by
``posthog_code_slack_mention.py`` and ``posthog_code_slack_mention_command.py``
in this package at module load time.
"""
from posthog.temporal.ai.slack_app.activities import (
CLASSIFI... | 121 | 5,072 |
posthog | posthog/temporal/ai/slack_app/helpers.py | .py | """Shared helpers used across PostHog Slack App Temporal activities.
These helpers exist outside the activity modules so that any activity in
``slack_app.activities.*`` can use them without forcing a cross-module import
between activity files.
"""
from typing import Any
from slack_sdk.errors import SlackApiError
d... | 74 | 2,416 |
posthog | posthog/temporal/ai/slack_app/eval_slack_repo_selection.py | .py | """Local eval for the Slack repo-selection flow — the canonical "how to test locally" tool.
Replicates the production cascade → Haiku gate → discovery agent path against a real
team with a real GitHub integration, without needing a Slack Integration row or any
actual Slack traffic. Each case declares its expected term... | 543 | 23,652 |
posthog | posthog/temporal/ai/slack_app/posthog_slack_inbox_onboarding.py | .py | import json
from datetime import timedelta
import structlog
from temporalio import workflow
from temporalio.common import RetryPolicy
from posthog.temporal.ai.slack_app.activities.onboarding import run_posthog_slack_inbox_onboarding_activity
from posthog.temporal.ai.slack_app.types import PostHogSlackInboxOnboardingI... | 33 | 1,389 |
posthog | posthog/temporal/ai/slack_app/posthog_code_slack_mention_command.py | .py | import json
from datetime import timedelta
from temporalio import workflow
from temporalio.common import RetryPolicy
from posthog.temporal.ai.slack_app import (
POSTHOG_CODE_SLACK_RULES_ADD_PICKER_GUIDANCE,
PostHogCodeSlackMentionCommandWorkflowInputs,
PostHogCodeSlackMentionWorkflowInputs,
block_post... | 156 | 6,779 |
posthog | posthog/temporal/ai/slack_app/attachments.py | .py | import os
import uuid
from dataclasses import dataclass
from typing import Any
from urllib.parse import urljoin, urlparse
import requests
import structlog
logger = structlog.get_logger(__name__)
MAX_SLACK_ATTACHMENTS_PER_MESSAGE = 5
MAX_SLACK_ATTACHMENT_BYTES = 10 * 1024 * 1024
SLACK_DOWNLOAD_TIMEOUT_SECONDS = 15
MA... | 342 | 11,917 |
posthog | posthog/temporal/ai/slack_app/posthog_code_slack_interactivity.py | .py | import json
from dataclasses import dataclass
from datetime import timedelta
from typing import Any
import structlog
from temporalio import activity, workflow
from temporalio.common import RetryPolicy
from posthog.temporal.common.base import PostHogWorkflow
POSTHOG_CODE_SLACK_INTERACTIVITY_TIMEOUT_SECONDS = 5 * 60
l... | 179 | 6,899 |
posthog | posthog/temporal/ai/slack_app/activities/repo_selection.py | .py | import asyncio
from typing import Any
import structlog
from temporalio import activity
from posthog.temporal.ai.slack_app.helpers import safe_react
from posthog.temporal.ai.slack_app.types import (
PostHogCodeRepoCascadeOutcome,
PostHogCodeSlackMentionWorkflowInputs,
SlackRepoSelectionOutcome,
)
from post... | 195 | 7,836 |
posthog | posthog/temporal/ai/slack_app/activities/rules.py | .py | import structlog
from temporalio import activity
from posthog.temporal.ai.slack_app.types import (
PostHogCodeRulesCommandResult,
PostHogCodeSlackMentionCommandResult,
PostHogCodeSlackMentionCommandWorkflowInputs,
PostHogCodeSlackMentionWorkflowInputs,
)
from posthog.temporal.common.utils import close_... | 197 | 7,159 |
posthog | posthog/temporal/ai/slack_app/activities/classifiers.py | .py | import re
import structlog
from openai.types.shared_params import ResponseFormatJSONSchema
from pydantic import ValidationError
from temporalio import activity
from posthog.llm.gateway_client import get_llm_client
from posthog.llm.semantic_enrichment import extract_json_object
from posthog.models.integration import I... | 548 | 26,066 |
posthog | posthog/temporal/ai/slack_app/activities/__init__.py | .py | from posthog.temporal.ai.slack_app.activities.billing import enforce_posthog_code_billing_quota_activity
from posthog.temporal.ai.slack_app.activities.classifiers import (
CLASSIFIER_THREAD_HISTORY_MESSAGES,
classify_message_is_agent_directed,
classify_posthog_code_task_needs_repo_activity,
classify_sla... | 78 | 3,441 |
posthog | posthog/temporal/ai/slack_app/activities/thread.py | .py | from temporalio import activity
from posthog.temporal.ai.slack_app.types import PostHogCodeSlackMentionWorkflowInputs
from posthog.temporal.common.utils import close_db_connections
@activity.defn
@close_db_connections
def collect_posthog_code_thread_messages_activity(
inputs: PostHogCodeSlackMentionWorkflowInput... | 30 | 1,203 |
posthog | posthog/temporal/ai/slack_app/activities/onboarding.py | .py | import structlog
from temporalio import activity
from posthog.temporal.ai.slack_app.types import PostHogSlackInboxOnboardingInputs
logger = structlog.get_logger(__name__)
@activity.defn
def run_posthog_slack_inbox_onboarding_activity(inputs: PostHogSlackInboxOnboardingInputs) -> None:
run_posthog_slack_inbox_on... | 29 | 1,099 |
posthog | posthog/temporal/ai/slack_app/activities/messaging.py | .py | from typing import Any
import structlog
from temporalio import activity
from posthog.models.integration import Integration, SlackIntegration
from posthog.temporal.ai.slack_app.helpers import safe_react, swap_reaction
from posthog.temporal.ai.slack_app.types import (
SLACK_APP_PROCESSING_REACTION,
SLACK_APP_QU... | 345 | 12,473 |
posthog | posthog/temporal/ai/slack_app/activities/billing.py | .py | from temporalio import activity
from posthog.temporal.ai.slack_app.helpers import block_if_team_over_quota
from posthog.temporal.ai.slack_app.types import PostHogCodeSlackMentionWorkflowInputs
from posthog.temporal.common.utils import close_db_connections
@activity.defn
@close_db_connections
def enforce_posthog_code... | 39 | 1,334 |
posthog | posthog/temporal/ai/slack_app/activities/task_creation.py | .py | import re
import uuid
import textwrap
from typing import Any
from django.db import models
import structlog
from temporalio import activity
from posthog.models.integration import Integration, SlackIntegration
from posthog.temporal.ai.slack_app.attachments import (
PreparedSlackAttachments,
build_slack_attachm... | 1,282 | 53,893 |
posthog | posthog/temporal/ai/slack_app/activities/user_resolution.py | .py | from temporalio import activity
from posthog.temporal.ai.slack_app.types import (
PostHogCodeSlackMentionCommandWorkflowInputs,
PostHogCodeSlackMentionWorkflowInputs,
)
from posthog.temporal.common.utils import close_db_connections
@activity.defn
@close_db_connections
def resolve_posthog_code_slack_user_acti... | 77 | 2,590 |
posthog | posthog/temporal/ai/llm_traces_summaries/summarize_traces.py | .py | import json
import uuid
import dataclasses
from datetime import timedelta
from django.conf import settings
import structlog
import temporalio
from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
from posthog.schema import DateRange
from posthog.models.team.team import Team
from posthog.settings.temporal... | 83 | 3,015 |
posthog | posthog/temporal/ai/anomaly_investigation/workflow.py | .py | """Temporal workflow that kicks off the anomaly investigation agent and persists
its findings as a Notebook linked to the AlertCheck.
Triggered from posthog/temporal/alerts/workflows.py when an alert transitions to FIRING.
"""
from __future__ import annotations
import re
import json
import asyncio
from dataclasses i... | 559 | 22,711 |
posthog | posthog/temporal/ai/anomaly_investigation/metric_definition.py | .py | """Plain-English rendering of the alerted insight's query definition.
Without this the investigation agent only sees the insight's *name* plus the
numbers, so a series called "Error tracking active users" reads as a count of
people hitting errors even when it is a `$pageview` DAU series filtered to a set
of app URLs —... | 311 | 11,794 |
posthog | posthog/temporal/ai/anomaly_investigation/runner.py | .py | """Single-pass anomaly investigation agent loop.
Kept small on purpose: we don't need LangGraph's conditional routing or the
streaming machinery from Max — just a tool-calling loop that terminates with a
structured report.
Budget: at most MAX_TOOL_CALLS tool invocations. After that the agent is told
to finalize with ... | 455 | 20,281 |
posthog | posthog/temporal/ai/anomaly_investigation/__init__.py | .py | from posthog.temporal.ai.anomaly_investigation.workflow import (
AnomalyInvestigationWorkflow,
AnomalyInvestigationWorkflowInputs,
investigate_anomaly_activity,
)
__all__ = [
"AnomalyInvestigationWorkflow",
"AnomalyInvestigationWorkflowInputs",
"investigate_anomaly_activity",
]
| 12 | 304 |
posthog | posthog/temporal/ai/anomaly_investigation/charts.py | .py | """Matplotlib chart rendering for the anomaly investigation agent.
Renders a compact PNG of the alert's metric over time, with the detector's
anomaly points highlighted. The PNG is base64-encoded and attached to the
first HumanMessage so the multimodal model can reason visually about the
shape of the anomaly (spike, c... | 114 | 4,234 |
posthog | posthog/temporal/ai/anomaly_investigation/notebook.py | .py | import json
import uuid
from dataclasses import dataclass
from typing import Any
from posthog.temporal.ai.anomaly_investigation.report import InvestigationReport
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
from products.notebooks.backend.facade.content import (
TipTapContent,
... | 123 | 4,708 |
posthog | posthog/temporal/ai/anomaly_investigation/tools.py | .py | """Agent tools for the anomaly investigation workflow.
Each tool is a narrow, read-only wrapper around existing PostHog query machinery.
All tools are bound to a team and enforce team isolation via the Team instance
they hold — they do NOT accept arbitrary team IDs from the LLM.
Tools return compact strings suitable ... | 269 | 10,806 |
posthog | posthog/temporal/ai/anomaly_investigation/prompts.py | .py | SYSTEM_PROMPT = """\
You are PostHog's anomaly investigation agent. An anomaly detection alert has just
transitioned to FIRING. Your job is to quickly validate the anomaly and explain it.
You have read-only access to the team's event data via HogQL, plus metric-specific
tools that return the alert's own time series an... | 161 | 8,638 |
posthog | posthog/temporal/ai/anomaly_investigation/report.py | .py | import re
import json
from typing import Any, Literal
from pydantic import BaseModel, Field, ValidationError, model_validator
_LEADING_PARAMETER_TAG_RE = re.compile(r'^\s*<parameter\s+name="([^"]*)">\s*')
def _close_truncated_json(fragment: str) -> str | None:
"""Append the closing brackets a truncated JSON arr... | 215 | 9,109 |
posthog | posthog/temporal/ai/checkpoint_compaction/types.py | .py | from pydantic import BaseModel
MAX_COMPACTION_BATCH_SIZE = 200
class CompactionProgress(BaseModel):
"""Accumulated state carried across continue-as-new executions."""
cursor: str | None = None
conversations_compacted: int = 0
conversations_failed: int = 0
checkpoints_deleted: int = 0
blobs_d... | 39 | 1,009 |
posthog | posthog/temporal/ai/checkpoint_compaction/workflow.py | .py | from datetime import timedelta
from temporalio import common, workflow
from posthog.temporal.ai.checkpoint_compaction.activities import (
compact_checkpoint_conversations,
select_checkpoint_compaction_batch,
)
from posthog.temporal.ai.checkpoint_compaction.types import (
CompactBatchResult,
Compaction... | 69 | 2,790 |
posthog | posthog/temporal/ai/checkpoint_compaction/__init__.py | .py | from posthog.temporal.ai.checkpoint_compaction.activities import (
compact_checkpoint_conversations,
select_checkpoint_compaction_batch,
)
from posthog.temporal.ai.checkpoint_compaction.workflow import CheckpointCompactionWorkflow
CHECKPOINT_COMPACTION_WORKFLOWS = [CheckpointCompactionWorkflow]
CHECKPOINT_COMP... | 9 | 411 |
posthog | posthog/temporal/ai/checkpoint_compaction/schedule.py | .py | from datetime import timedelta
from django.conf import settings
from temporalio.client import (
Client,
Schedule,
ScheduleActionStartWorkflow,
ScheduleIntervalSpec,
ScheduleOverlapPolicy,
SchedulePolicy,
ScheduleSpec,
)
from posthog.temporal.ai.checkpoint_compaction.types import Compactio... | 43 | 1,628 |
posthog | posthog/temporal/ai/checkpoint_compaction/activities.py | .py | from temporalio import activity
from posthog.sync import database_sync_to_async
from posthog.temporal.ai.checkpoint_compaction.types import (
MAX_COMPACTION_BATCH_SIZE,
CompactBatchResult,
CompactionBatch,
SelectBatchInput,
)
from posthog.temporal.common.logger import get_write_only_logger
from ee.hog... | 64 | 2,702 |
posthog | posthog/temporal/ingestion_acceptance_test/types.py | .py | """Types for ingestion acceptance test workflow."""
from pydantic import BaseModel
class IngestionAcceptanceTestInput(BaseModel):
"""Input for the ingestion acceptance test workflow.
The lane selects which ingestion routing the run targets (e.g. "main",
"turbo"). Each lane resolves its own api_host, tea... | 16 | 530 |
posthog | posthog/temporal/ingestion_acceptance_test/workflows.py | .py | """Workflow for ingestion acceptance tests."""
from datetime import timedelta
import temporalio.workflow
from temporalio.common import RetryPolicy
from posthog.temporal.common.base import PostHogWorkflow
with temporalio.workflow.unsafe.imports_passed_through():
from posthog.temporal.ingestion_acceptance_test.ac... | 44 | 1,544 |
posthog | posthog/temporal/ingestion_acceptance_test/slack.py | .py | """Slack notifications for test results using incoming webhooks."""
from typing import Any
import requests
import structlog
from .config import Config
from .results import TestSuiteResult
from .runner import RunningTestSnapshot
logger = structlog.get_logger(__name__)
def send_slack_notification(config: Config, re... | 216 | 6,870 |
posthog | posthog/temporal/ingestion_acceptance_test/runner.py | .py | """Test runner for acceptance tests without pytest dependency."""
import time
import threading
import traceback
from concurrent.futures import Executor, as_completed
from dataclasses import dataclass
from typing import Literal
import structlog
from .client import CapturedEvent, PostHogClient
from .config import Conf... | 194 | 6,185 |
posthog | posthog/temporal/ingestion_acceptance_test/__main__.py | .py | """Command-line entry point for running acceptance tests."""
import sys
import logging
from concurrent.futures import ThreadPoolExecutor
import posthoganalytics
from posthog.temporal.ingestion_acceptance_test.client import PostHogClient
from posthog.temporal.ingestion_acceptance_test.config import Config
from postho... | 33 | 1,180 |
posthog | posthog/temporal/ingestion_acceptance_test/__init__.py | .py | """Ingestion acceptance test Temporal workflow.
This workflow runs acceptance tests against the PostHog ingestion pipeline
to verify that events can be captured and queried successfully.
"""
from posthog.temporal.ingestion_acceptance_test.activities import run_ingestion_acceptance_tests
from posthog.temporal.ingestio... | 17 | 530 |
posthog | posthog/temporal/ingestion_acceptance_test/test_cases_discovery.py | .py | """Test discovery for acceptance tests."""
import inspect
import importlib
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .runner import AcceptanceTest
@dataclass
class TestCase:
"""A discovered test case."""
module_name: str
test_... | 61 | 1,743 |
posthog | posthog/temporal/ingestion_acceptance_test/schedule.py | .py | """Schedule for ingestion acceptance test workflow."""
import uuid
from datetime import timedelta
from django.conf import settings
from temporalio import common
from temporalio.client import Client, Schedule, ScheduleActionStartWorkflow, ScheduleIntervalSpec, ScheduleSpec
from posthog.temporal.common.schedule impor... | 68 | 2,776 |
posthog | posthog/temporal/ingestion_acceptance_test/client.py | .py | """PostHog client for acceptance tests using the official SDK and direct ClickHouse queries."""
import json
import time
import uuid
import threading
from collections.abc import Callable
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING, Any, TypeVar
impor... | 488 | 18,418 |
posthog | posthog/temporal/ingestion_acceptance_test/terminal_report.py | .py | """Terminal report formatting for test results."""
from .results import TestSuiteResult
def format_terminal_report(result: TestSuiteResult) -> str:
"""Format a detailed report suitable for console output."""
sections = [
_format_header(result),
_format_environment(result),
_format_sum... | 79 | 3,049 |
posthog | posthog/temporal/ingestion_acceptance_test/activities.py | .py | """Activities for ingestion acceptance test workflow."""
import asyncio
from concurrent.futures import ThreadPoolExecutor
import structlog
import posthoganalytics
import temporalio.activity
from posthog.temporal.ingestion_acceptance_test.client import PostHogClient
from posthog.temporal.ingestion_acceptance_test.con... | 86 | 3,208 |
posthog | posthog/temporal/ingestion_acceptance_test/config.py | .py | """Configuration loading from environment variables using pydantic-settings."""
import os
from pydantic import Field, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
ENV_PREFIX = "INGESTION_ACCEPTANCE_TEST_"
DEFAULT_LANE = "main"
class Config(BaseSettings):
"""Configuration for a... | 103 | 3,514 |
posthog | posthog/temporal/ingestion_acceptance_test/results.py | .py | """Test result types and reporters for alerting integration."""
from dataclasses import asdict, dataclass, field
from datetime import UTC, datetime
from typing import Any, Literal
@dataclass
class TestResult:
"""Result of a single test execution."""
test_name: str
test_file: str
status: Literal["pas... | 64 | 1,886 |
posthog | posthog/temporal/ingestion_acceptance_test/tests/acceptance_test_merge.py | .py | """Merge test - verifies that $merge_dangerously merges two persons into one."""
import uuid
import structlog
from ..runner import AcceptanceTest
logger = structlog.get_logger(__name__)
class TestMergeDangerously(AcceptanceTest):
"""Test $merge_dangerously functionality."""
def test_merge_combines_two_pe... | 86 | 4,661 |
posthog | posthog/temporal/ingestion_acceptance_test/tests/acceptance_test_basic_capture.py | .py | """Basic event capture test - sends an event and verifies it appears in queries."""
import uuid
import structlog
from ..runner import AcceptanceTest
logger = structlog.get_logger(__name__)
class TestBasicCapture(AcceptanceTest):
"""Test basic event capture and retrieval flow."""
def test_capture_event(se... | 46 | 1,841 |
posthog | posthog/temporal/ingestion_acceptance_test/tests/acceptance_test_event_person_properties_capture.py | .py | """Event properties capture test - verifies $set, $set_once, and $unset person properties."""
import uuid
import structlog
from ..runner import AcceptanceTest
logger = structlog.get_logger(__name__)
class TestPersonPropertiesCapture(AcceptanceTest):
"""Test event capture with person properties."""
def te... | 170 | 9,215 |
posthog | posthog/temporal/ingestion_acceptance_test/tests/acceptance_test_alias.py | .py | """Alias test - verifies that alias links two distinct IDs to the same person."""
import uuid
import structlog
from ..runner import AcceptanceTest
logger = structlog.get_logger(__name__)
class TestAlias(AcceptanceTest):
"""Test alias functionality."""
def test_alias_merges_events_from_different_distinct_... | 57 | 2,799 |
posthog | posthog/temporal/backfill_group_type_created_at/types.py | .py | from dataclasses import dataclass
from typing import TypedDict
from pydantic import BaseModel
class GroupTypeUpdate(TypedDict):
"""A single created_at correction, produced by the plan activity and applied by the apply activity."""
group_type: str
group_type_index: int
current_created_at: str # ISO-... | 57 | 1,640 |
posthog | posthog/temporal/backfill_group_type_created_at/workflows.py | .py | import json
from datetime import timedelta
from typing import Any
from temporalio import common, workflow
from posthog.temporal.backfill_group_type_created_at.activities import (
apply_group_type_created_at_backfill,
plan_group_type_created_at_backfill,
)
from posthog.temporal.backfill_group_type_created_at.t... | 81 | 3,232 |
posthog | posthog/temporal/backfill_group_type_created_at/__init__.py | .py | from posthog.temporal.backfill_group_type_created_at.activities import (
apply_group_type_created_at_backfill,
plan_group_type_created_at_backfill,
)
from posthog.temporal.backfill_group_type_created_at.workflows import BackfillGroupTypeCreatedAtWorkflow
WORKFLOWS = [
BackfillGroupTypeCreatedAtWorkflow,
]
... | 15 | 421 |
posthog | posthog/temporal/backfill_group_type_created_at/activities.py | .py | from datetime import UTC, datetime
from uuid import uuid4
from structlog.contextvars import bind_contextvars
from temporalio import activity
from posthog.models import Team
from posthog.models.group_type_mapping import invalidate_group_types_cache
from posthog.persons_db import persons_db_connection
from posthog.sync... | 211 | 8,316 |
posthog | posthog/temporal/cleanup_property_definitions/types.py | .py | import re
from dataclasses import dataclass
from typing import Literal
from pydantic import BaseModel, Field, field_validator
from products.event_definitions.backend.models.property_definition import PropertyDefinition
# String type names for the workflow input (user-friendly)
PropertyTypeName = Literal["event", "pe... | 99 | 3,015 |
posthog | posthog/temporal/cleanup_property_definitions/workflows.py | .py | import json
from datetime import timedelta
from typing import Any
from temporalio import common, workflow
from posthog.temporal.cleanup_property_definitions.activities import (
delete_property_definitions_from_clickhouse,
delete_property_definitions_from_postgres,
preview_property_definitions,
)
from post... | 131 | 5,415 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.