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/temporal/ai_observability/trace_clustering/labeling_agent/__init__.py
.py
"""Cluster labeling agent using LangGraph. This module contains a fully agent-driven LangGraph agent that handles all cluster labeling work. The agent has rich tools to explore cluster structure and generate high-quality, distinctive labels. """ from posthog.temporal.ai_observability.trace_clustering.labeling_agent.g...
11
385
posthog
posthog/temporal/ai_observability/trace_clustering/labeling_agent/tools.py
.py
"""Tool definitions for the cluster labeling agent. Uses LangGraph's InjectedState pattern so tools can access graph state directly. This eliminates the need for separate execution functions and manual tool dispatch. """ import json from typing import Annotated from langchain_core.tools import tool from langgraph.pr...
236
8,053
posthog
posthog/temporal/ai_observability/trace_clustering/labeling_agent/prompts.py
.py
"""System prompts for the cluster labeling agent.""" CLUSTER_LABELING_SYSTEM_PROMPT = """You are a cluster labeling agent. Your job is to create distinctive, informative labels for clusters of LLM traces. ## Context You are analyzing clusters of AI/LLM traces from a PostHog project. Each cluster contains traces that...
116
6,732
posthog
posthog/temporal/ai_observability/trace_clustering/labeling_agent/graph.py
.py
"""LangGraph agent for cluster labeling using create_react_agent.""" import uuid from typing import Any import structlog from langchain_core.messages import HumanMessage from langgraph.prebuilt import create_react_agent from posthog.llm.gateway_client import team_distinct_id from posthog.temporal.ai_observability.cl...
137
4,930
posthog
posthog/temporal/ai_observability/tests/test_llm_endpoint.py
.py
"""Tests for clustering labeling client construction (ai-gateway vs direct OpenAI).""" import json import pytest from unittest.mock import patch from django.test import override_settings from posthog.temporal.ai_observability.llm_endpoint import build_langchain_callbacks, build_langchain_chat_client GATEWAY_URL = ...
146
6,293
posthog
posthog/temporal/ai_observability/tests/test_coordinator_metrics.py
.py
from unittest.mock import MagicMock, patch from parameterized import parameterized from posthog.temporal.ai_observability.coordinator_metrics import ( increment_team_failed, increment_team_succeeded, record_teams_discovered, ) class TestCoordinatorMetrics: @parameterized.expand( [ ...
35
1,366
posthog
posthog/temporal/ai_observability/sentiment/utils.py
.py
"""Utility helpers for sentiment classification.""" from typing import Any from posthog.hogql_queries.ai.sentiment_labeling import select_sentiment_label from posthog.temporal.ai_observability.sentiment.schema import PendingClassification def average_score_dicts(score_dicts: list[dict[str, float]]) -> dict[str, flo...
62
1,972
posthog
posthog/temporal/ai_observability/sentiment/extraction.py
.py
"""Extract user messages from $ai_input for sentiment classification.""" from posthog.temporal.ai_observability.message_utils import _extract_content_text from posthog.temporal.ai_observability.sentiment.constants import ( MAX_MESSAGE_CHARS, MAX_USER_MESSAGES, SENTIMENT_EVAL_MAX_MESSAGE_CHARS, SENTIMEN...
110
3,935
posthog
posthog/temporal/ai_observability/sentiment/model.py
.py
"""Sentiment classification using cardiffnlp/twitter-roberta-base-sentiment-latest. Uses ONNX Runtime for inference (~60MB) instead of PyTorch (~2GB). Loads the pre-baked ONNX model once per worker process (singleton) and provides a classify function that returns three-class sentiment scores. The ONNX model is baked ...
116
4,074
posthog
posthog/temporal/ai_observability/sentiment/constants.py
.py
"""Constants for sentiment classification.""" import os from pathlib import Path def _positive_int_env(name: str, default: int) -> int: try: value = int(os.environ.get(name, default)) except ValueError: return default return max(1, value) # Model MODEL_NAME = "cardiffnlp/twitter-roberta...
32
1,021
posthog
posthog/temporal/ai_observability/sentiment/schema.py
.py
"""Dataclasses for sentiment evaluations.""" from dataclasses import dataclass @dataclass class SentimentResult: label: str score: float scores: dict[str, float] @classmethod def neutral(cls) -> "SentimentResult": return cls(label="neutral", score=0.0, scores={"positive": 0.0, "neutral":...
23
455
posthog
posthog/temporal/ai_observability/sentiment/tests/test_extraction.py
.py
from parameterized import parameterized from posthog.temporal.ai_observability.sentiment.constants import ( MAX_MESSAGE_CHARS, MAX_USER_MESSAGES, SENTIMENT_EVAL_MAX_MESSAGE_CHARS, SENTIMENT_EVAL_MESSAGE_HEAD_CHARS, ) from posthog.temporal.ai_observability.sentiment.extraction import ( HEAD_TAIL_SEP...
184
7,494
posthog
posthog/temporal/ai_observability/sentiment/tests/test_model.py
.py
from unittest.mock import MagicMock, patch from parameterized import parameterized from posthog.temporal.ai_observability.sentiment.model import classify from posthog.temporal.ai_observability.sentiment.schema import SentimentResult def _make_pipeline_output(label: str, score: float) -> list[dict[str, object]]: ...
103
3,798
posthog
posthog/temporal/ai_observability/sentiment/tests/test_utils.py
.py
from parameterized import parameterized from posthog.hogql_queries.ai.sentiment_labeling import select_sentiment_label from posthog.temporal.ai_observability.sentiment.schema import PendingClassification, SentimentResult from posthog.temporal.ai_observability.sentiment.utils import build_generation_result class Test...
45
2,337
posthog
posthog/temporal/ai_observability/evaluation_clustering/workflow.py
.py
"""Per-job workflows for evaluation clustering (Stage A sampler + Stage B clustering stub).""" from datetime import timedelta import temporalio.exceptions from temporalio import workflow from posthog.temporal.ai_observability.evaluation_clustering.constants import ( CLUSTERING_WORKFLOW_NAME, SAMPLER_ACTIVITY...
300
13,053
posthog
posthog/temporal/ai_observability/evaluation_clustering/models.py
.py
"""Data models for evaluation clustering workflows.""" from dataclasses import dataclass, field from typing import Any @dataclass class SamplerActivityInputs: """Inputs for the per-job sample_and_embed activity. Stage A runs one of these per (team, active evaluation ClusteringJob) per hour. The window i...
75
1,970
posthog
posthog/temporal/ai_observability/evaluation_clustering/sampling.py
.py
"""Stage A — per-job sample $ai_evaluation events, compose text, enqueue embeddings.""" from datetime import datetime from typing import Any from uuid import uuid4 import structlog from temporalio import activity from posthog.hogql import ast from posthog.hogql.constants import LimitContext from posthog.hogql.parser...
271
11,814
posthog
posthog/temporal/ai_observability/evaluation_clustering/__init__.py
.py
"""Evaluation-level clustering for AI observability. Two-stage pipeline: Stage A (hourly): sample $ai_evaluation events per ClusteringJob, compose a short text representation, and enqueue embeddings via the shared document_embeddings Kafka topic. Stage B (daily): per ClusteringJob, fetch accumulated embeddings,...
43
1,846
posthog
posthog/temporal/ai_observability/evaluation_clustering/constants.py
.py
"""Constants for evaluation-level clustering.""" from datetime import timedelta from temporalio.common import RetryPolicy # Stage A (sampler): window + offset + caps SAMPLER_WINDOW_MINUTES = 60 SAMPLER_WINDOW_OFFSET_MINUTES = 30 # skew the window into the past so evals have time to land SAMPLER_MAX_SAMPLES_PER_JOB ...
88
4,519
posthog
posthog/temporal/ai_observability/evaluation_clustering/data.py
.py
"""HogQL data access for Stage B evaluation clustering. Two queries: - ``fetch_evaluation_embeddings`` — pulls accumulated eval embeddings for a job via ``JSONExtractString(metadata, 'job_id')``, matching the Stage A metadata convention ``{"job_id": ...}`` (with a transitional suffix match on legacy ``rendering...
519
21,284
posthog
posthog/temporal/ai_observability/evaluation_clustering/schedule.py
.py
"""Schedules for evaluation clustering (Stage A hourly sampler + Stage B daily clustering).""" from datetime import timedelta from django.conf import settings from temporalio.client import ( Client, Schedule, ScheduleActionStartWorkflow, ScheduleIntervalSpec, ScheduleOverlapPolicy, SchedulePo...
81
3,221
posthog
posthog/temporal/ai_observability/evaluation_clustering/coordinator.py
.py
"""Coordinators for evaluation clustering (Stage A sampler + Stage B clustering).""" import dataclasses from datetime import timedelta from typing import Any import structlog import temporalio from temporalio import workflow from temporalio.workflow import ChildWorkflowHandle from posthog.temporal.ai_observability.e...
316
14,019
posthog
posthog/temporal/ai_observability/evaluation_clustering/activities.py
.py
"""Temporal activities for Stage B evaluation clustering. Pipeline: 1. ``perform_evaluation_clustering_compute_activity`` — fetch accumulated eval embeddings for the job, HDBSCAN, distances, 2D coords. Returns lightweight metadata; the 3072-dim embeddings stay inside this activity. 2. ``fetch_evaluation_metadat...
512
19,638
posthog
posthog/temporal/ai_observability/evaluation_clustering/aggregates.py
.py
"""Per-cluster metric aggregation for Stage B evaluation clustering. Fills in both operational metrics (cost/latency/tokens/errors — sourced from the linked $ai_generation event) and eval-specific metrics (pass_rate, na_rate, dominant_evaluation_name, dominant_runtime, avg_judge_cost) on :class:`ClusterAggregateMetric...
131
5,360
posthog
posthog/temporal/ai_observability/evaluation_clustering/event_emission.py
.py
"""Emit $ai_evaluation_clusters events after Stage B clustering. Parallel to ``trace_clustering.event_emission.emit_cluster_events`` — reuses the shared ``_build_cluster_data`` helper for the actual cluster-data assembly — but with two eval-specific differences: 1. Event name: ``$ai_evaluation_clusters``. 2. No trace...
93
3,061
posthog
posthog/temporal/ai_observability/evaluation_clustering/labeling.py
.py
"""High-level labeling entry point for evaluation clustering. Converts the compute-activity outputs (items, labels, per-item metadata, centroid 2D coords) and the eval metadata map into the shapes the LangGraph labeling agent expects, then invokes it. """ import numpy as np from posthog.temporal.ai_observability.eva...
171
6,762
posthog
posthog/temporal/ai_observability/evaluation_clustering/tests/test_event_emission.py
.py
"""Tests for $ai_evaluation_clusters event emission.""" import pytest from unittest.mock import patch import numpy as np from posthog.temporal.ai_observability.evaluation_clustering.constants import EVENT_NAME_EVALUATION_CLUSTERS from posthog.temporal.ai_observability.evaluation_clustering.event_emission import emit...
124
5,172
posthog
posthog/temporal/ai_observability/evaluation_clustering/tests/test_workflow.py
.py
"""Tests for the evaluation sampler workflow window math and coordinator job filtering.""" import uuid from datetime import UTC, datetime, timedelta import pytest from unittest.mock import patch from temporalio import activity from temporalio.testing import WorkflowEnvironment from temporalio.worker import Unsandbox...
262
10,910
posthog
posthog/temporal/ai_observability/evaluation_clustering/tests/test_aggregates.py
.py
"""Unit tests for Stage B per-cluster aggregate computation.""" import pytest from parameterized import parameterized from posthog.temporal.ai_observability.evaluation_clustering.aggregates import aggregate_evaluation_metrics from posthog.temporal.ai_observability.evaluation_clustering.data import EvaluationMetadata...
167
6,370
posthog
posthog/temporal/ai_observability/evaluation_clustering/tests/test_labeling_agent.py
.py
"""Tests for the evaluation labeling agent tools and graph.""" import json from unittest.mock import ANY, MagicMock, patch from langchain_core.messages import HumanMessage from posthog.temporal.ai_observability.evaluation_clustering.labeling_agent.graph import ( _apply_fallbacks, run_eval_labeling_agent, ) ...
282
11,330
posthog
posthog/temporal/ai_observability/evaluation_clustering/tests/test_sampling.py
.py
"""Tests for the Stage A evaluation sampler activity.""" from contextlib import asynccontextmanager import pytest from unittest.mock import MagicMock, patch from parameterized import parameterized from posthog.temporal.ai_observability.evaluation_clustering.constants import ( AI_OBSERVABILITY_EVALUATION_DOCUMEN...
230
9,601
posthog
posthog/temporal/ai_observability/evaluation_clustering/tests/test_labeling.py
.py
"""Tests for the high-level eval labeling entry point (building agent inputs).""" from typing import Any import numpy as np from posthog.temporal.ai_observability.evaluation_clustering.data import EvaluationMetadata from posthog.temporal.ai_observability.evaluation_clustering.labeling import ( _build_eval_cluste...
135
5,417
posthog
posthog/temporal/ai_observability/evaluation_clustering/tests/test_data.py
.py
"""Tests for Stage B data access — embeddings fetch + eval→generation metadata join.""" from datetime import UTC from types import SimpleNamespace import pytest from unittest.mock import patch from posthog.temporal.ai_observability.evaluation_clustering.constants import ( AI_OBSERVABILITY_EVALUATION_DOCUMENT_TYP...
231
9,301
posthog
posthog/temporal/ai_observability/evaluation_clustering/tests/test_fetch_generation_contents.py
.py
"""Tests for the eval clustering data layer. `fetch_generation_contents` is the only at-risk reader in `evaluation_clustering/data.py` (it reads heavy `input` / `output_choices`). It uses a two-query pattern: resolves uuid → trace_id off `events` first, then runs the heavy fetch on `ai_events` with `trace_id IN (...)`...
176
8,750
posthog
posthog/temporal/ai_observability/evaluation_clustering/labeling_agent/state.py
.py
"""State TypedDicts for the evaluation cluster-labeling agent.""" from typing import Annotated, TypedDict from langgraph.graph.message import add_messages from langgraph.managed import RemainingSteps from posthog.temporal.ai_observability.trace_clustering.models import ClusterLabel class EvalContent(TypedDict): ...
82
3,228
posthog
posthog/temporal/ai_observability/evaluation_clustering/labeling_agent/__init__.py
.py
"""LangGraph cluster-labeling agent for evaluation-level clustering. Structurally parallel to ``trace_clustering.labeling_agent``: ReAct agent with tools over an injected state. The level-specific pieces (state shape, tool domain, prompt) live here; the shared ChatOpenAI setup and fallback filler come from ``posthog.t...
12
522
posthog
posthog/temporal/ai_observability/evaluation_clustering/labeling_agent/tools.py
.py
"""Tool definitions for the evaluation cluster-labeling agent. Parallel to ``trace_clustering.labeling_agent.tools`` — same InjectedState pattern, same label-setting semantics — but the content-rendering tools surface evaluation-specific fields (verdict, reasoning, evaluator name) instead of trace summaries. """ impo...
378
14,236
posthog
posthog/temporal/ai_observability/evaluation_clustering/labeling_agent/prompts.py
.py
"""System prompt for the evaluation cluster-labeling agent.""" EVAL_CLUSTER_LABELING_SYSTEM_PROMPT = """You are a cluster labeling agent. Your job is to create distinctive, informative labels for clusters of LLM **evaluations**. ## Context Each cluster contains `$ai_evaluation` events — judgments produced by LLM-as-...
104
7,617
posthog
posthog/temporal/ai_observability/evaluation_clustering/labeling_agent/graph.py
.py
"""LangGraph agent entry point for evaluation cluster labeling.""" import uuid from typing import Any import structlog from langchain_core.messages import HumanMessage from langgraph.prebuilt import create_react_agent from posthog.llm.gateway_client import team_distinct_id from posthog.temporal.ai_observability.clus...
131
4,836
posthog
posthog/temporal/warehouse_sources_queue_partition_management/types.py
.py
from pydantic import BaseModel class PartitionManagementInput(BaseModel): pass
6
85
posthog
posthog/temporal/warehouse_sources_queue_partition_management/workflows.py
.py
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.warehouse_sources_queue_partition_management.activities import ( man...
28
1,165
posthog
posthog/temporal/warehouse_sources_queue_partition_management/__init__.py
.py
from posthog.temporal.warehouse_sources_queue_partition_management.activities import ( manage_warehouse_sources_queue_partitions, ) from posthog.temporal.warehouse_sources_queue_partition_management.workflows import ( WarehouseSourcesQueuePartitionManagementWorkflow, ) WORKFLOWS = [WarehouseSourcesQueuePartiti...
15
449
posthog
posthog/temporal/warehouse_sources_queue_partition_management/schedule.py
.py
import uuid from django.conf import settings from temporalio import common from temporalio.client import ( Client, Schedule, ScheduleActionStartWorkflow, ScheduleCalendarSpec, ScheduleRange, ScheduleSpec, ) from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_u...
45
1,440
posthog
posthog/temporal/warehouse_sources_queue_partition_management/activities.py
.py
from __future__ import annotations from dataclasses import dataclass, field from datetime import UTC, date, datetime, timedelta from typing import Any from django.conf import settings import psycopg import requests import structlog import temporalio.activity from asgiref.sync import sync_to_async logger = structlog...
294
11,346
posthog
posthog/temporal/exports/types.py
.py
import dataclasses from typing import Optional from posthog.temporal.common.errors import resolve_error_trace, unwrap_temporal_cause @dataclasses.dataclass class ExportAssetActivityInputs: exported_asset_id: int source: Optional[str] = None @dataclasses.dataclass class ExportError: exception_class: str...
31
741
posthog
posthog/temporal/exports/workflows.py
.py
import json import dataclasses from datetime import timedelta import temporalio.workflow as wf from posthog.event_usage import EventSource from posthog.slo.types import SloConfig, SloOutcome from posthog.temporal.common.base import PostHogWorkflow from posthog.temporal.common.errors import resolve_exception_class fro...
53
1,900
posthog
posthog/temporal/exports/__init__.py
.py
from posthog.temporal.exports.activities import export_asset_activity from posthog.temporal.exports.retry_policy import EXPORT_RETRY_POLICY from posthog.temporal.exports.types import ExportAssetActivityInputs, ExportAssetResult from posthog.temporal.exports.workflows import ExportAssetWorkflow __all__ = [ "export_...
17
524
posthog
posthog/temporal/exports/activities.py
.py
import traceback import structlog import temporalio.activity from temporalio.exceptions import ApplicationError from posthog.event_usage import EventSource from posthog.sync import database_sync_to_async from posthog.tasks import exporter from posthog.temporal.common.errors import MAX_ERROR_MESSAGE_CHARS, MAX_ERROR_T...
75
3,303
posthog
posthog/temporal/exports/retry_policy.py
.py
from datetime import timedelta from temporalio.common import RetryPolicy from products.exports.backend.tasks.failure_handler import USER_QUERY_ERROR_NAMES EXPORT_RETRY_POLICY = RetryPolicy( initial_interval=timedelta(seconds=30), backoff_coefficient=2.0, maximum_interval=timedelta(minutes=15), maximu...
16
415
posthog
posthog/temporal/health_checks/workflows.py
.py
import json import asyncio import dataclasses 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.health_checks.activities impor...
103
3,810
posthog
posthog/temporal/health_checks/alerts.py
.py
from typing import Literal import structlog from posthog.cdp.internal_events import InternalEventEvent, produce_internal_event from posthog.exceptions_capture import capture_exception from posthog.models.health_issue import HealthIssue from posthog.temporal.health_checks.framework import ( AlertContent, Healt...
80
2,978
posthog
posthog/temporal/health_checks/models.py
.py
from __future__ import annotations import dataclasses from collections.abc import Callable from dataclasses import dataclass from typing import TYPE_CHECKING, Any from posthog.models.health_issue import HealthIssue if TYPE_CHECKING: from posthog.temporal.health_checks.framework import HealthCheckRegistration @...
93
2,816
posthog
posthog/temporal/health_checks/__init__.py
.py
from posthog.temporal.health_checks.activities import ( get_team_id_batches, push_health_check_metrics_activity, run_health_check_batch, ) from posthog.temporal.health_checks.workflows import HealthCheckWorkflow WORKFLOWS = [HealthCheckWorkflow] ACTIVITIES = [get_team_id_batches, run_health_check_batch, pu...
19
530
posthog
posthog/temporal/health_checks/registry.py
.py
import importlib import threading from typing import TYPE_CHECKING from posthog.temporal.health_checks.models import BatchDetectFn if TYPE_CHECKING: from posthog.clickhouse.query_tagging import Product from posthog.temporal.health_checks.framework import HealthCheckRegistration HEALTH_CHECKS: dict[str, "Heal...
62
2,279
posthog
posthog/temporal/health_checks/detectors.py
.py
from dataclasses import dataclass @dataclass(frozen=True) class HealthExecutionPolicy: batch_size: int max_concurrent: int def __post_init__(self) -> None: if self.batch_size <= 0: raise ValueError(f"batch_size must be > 0, got {self.batch_size}") if self.max_concurrent <= 0: ...
18
585
posthog
posthog/temporal/health_checks/schedule.py
.py
import dataclasses from django.conf import settings import structlog 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.health_checks.models import HealthC...
53
1,995
posthog
posthog/temporal/health_checks/observability.py
.py
import time from django.conf import settings import structlog from prometheus_client import Gauge from posthog.exceptions_capture import capture_exception from posthog.metrics import pushed_metrics_registry from posthog.temporal.health_checks.models import BatchResult logger = structlog.get_logger(__name__) def p...
93
3,490
posthog
posthog/temporal/health_checks/processing.py
.py
import time import structlog from posthog.temporal.health_checks.alerts import emit_health_check_alert from posthog.temporal.health_checks.db import resolve_stale_issues_with_deltas, upsert_issues_with_deltas from posthog.temporal.health_checks.models import BatchDetectFn, BatchResult from posthog.temporal.health_che...
63
2,179
posthog
posthog/temporal/health_checks/query.py
.py
from collections.abc import Mapping from dataclasses import dataclass from typing import Any import structlog from posthog.clickhouse.client import sync_execute logger = structlog.get_logger(__name__) @dataclass(frozen=True) class HealthQuerySettings: max_execution_time: int = 30 max_threads: int = 2 ...
63
1,828
posthog
posthog/temporal/health_checks/db.py
.py
from posthog.models.health_issue import HealthIssue, _filter_existing_team_ids from posthog.temporal.health_checks.models import HealthCheckResult def upsert_issues_with_deltas( kind: str, issues_by_team: dict[int, list[HealthCheckResult]], ) -> list[HealthIssue]: """Upsert health issues from a batch dete...
51
1,966
posthog
posthog/temporal/health_checks/activities.py
.py
import dataclasses from datetime import timedelta from itertools import batched from django.db import close_old_connections from django.db.models import Exists, OuterRef from django.utils import timezone import structlog import temporalio.activity from posthog.clickhouse.client.execute import KillSwitchLevel, get_ki...
119
4,114
posthog
posthog/temporal/health_checks/signal_emitter.py
.py
import asyncio from dataclasses import dataclass import structlog from asgiref.sync import async_to_sync from posthog.exceptions_capture import capture_exception from posthog.models import Team from posthog.models.health_issue import HealthIssue from posthog.temporal.health_checks.alerts import _check_class_for_kind ...
128
4,770
posthog
posthog/temporal/health_checks/validation.py
.py
import structlog from posthog.exceptions_capture import capture_exception from posthog.temporal.health_checks.models import HealthCheckResult logger = structlog.get_logger(__name__) def _validate_batch_output( issues_by_team: dict[int, list[HealthCheckResult]], valid_team_ids: set[int], kind: str, ) -> ...
40
1,599
posthog
posthog/temporal/health_checks/framework.py
.py
from __future__ import annotations import inspect from dataclasses import dataclass from typing import Any from django.conf import settings from posthog.clickhouse.query_tagging import Product from posthog.dags.common.owners import JobOwners from posthog.models.health_issue import HealthIssue from posthog.temporal.h...
285
11,153
posthog
posthog/temporal/health_checks/tests/test_alert_emission.py
.py
from unittest.mock import patch from django.test import SimpleTestCase from parameterized import parameterized from posthog.models.health_issue import HealthIssue from posthog.temporal.health_checks.alerts import EVENT_FIRING, EVENT_RESOLVED, emit_health_check_alert from posthog.temporal.health_checks.framework impo...
92
4,151
posthog
posthog/temporal/health_checks/tests/test_db.py
.py
from posthog.test.base import BaseTest from posthog.models.health_issue import HealthIssue from posthog.temporal.health_checks.db import resolve_stale_issues_with_deltas, upsert_issues_with_deltas from posthog.temporal.health_checks.models import HealthCheckResult class TestResolveStaleIssuesWithDeltas(BaseTest): ...
56
2,520
posthog
posthog/temporal/health_checks/tests/test_signal_emitter.py
.py
from unittest.mock import AsyncMock, MagicMock, patch from django.test import SimpleTestCase from parameterized import parameterized from posthog.models import Team from posthog.models.health_issue import HealthIssue from posthog.temporal.health_checks.framework import ( AlertContent, HealthCheck, Remedi...
203
8,897
posthog
posthog/temporal/alerts/types.py
.py
import dataclasses from enum import StrEnum from posthog.schema import AlertState from posthog.slo.types import SloConfig class PrepareAction(StrEnum): EVALUATE = "evaluate" SKIP = "skip" AUTO_DISABLE = "auto_disable" class SkipReason(StrEnum): NOT_FOUND = "not_found" DISABLED = "disabled" ...
98
2,728
posthog
posthog/temporal/alerts/workflows.py
.py
import json import asyncio import datetime as dt from uuid import UUID import temporalio.common import temporalio.workflow from temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedError from posthog.schema import AlertState from posthog.slo.context import JsonValue from posthog.slo.types import SloA...
314
13,718
posthog
posthog/temporal/alerts/investigation.py
.py
"""Investigation-agent trigger helpers used by the Temporal evaluate_alert activity. The trigger and notification-gating decisions both run inside `evaluate_alert` in the same DB transaction as the AlertCheck insert, so the read-then-write that claims the cooldown lease stays consistent. This module exposes the primit...
66
2,429
posthog
posthog/temporal/alerts/__init__.py
.py
from posthog.temporal.alerts.activities import ( cleanup_alert_checks, evaluate_alert, notify_alert, prepare_alert, record_failed_evaluation, retrieve_due_alerts, run_investigation_safety_net, ) from posthog.temporal.alerts.workflows import ( CheckAlertWorkflow, CleanupAlertChecksWor...
33
742
posthog
posthog/temporal/alerts/schedule.py
.py
import datetime as dt from django.conf import settings from temporalio.client import ( Client, Schedule, ScheduleActionStartWorkflow, ScheduleOverlapPolicy, SchedulePolicy, ScheduleSpec, ) from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule SC...
80
3,181
posthog
posthog/temporal/alerts/activities.py
.py
import traceback from concurrent.futures import ThreadPoolExecutor from datetime import UTC, datetime from django.db import transaction from django.db.models import Case, F, IntegerField, Q, Value, When import structlog import temporalio.activity from temporalio.exceptions import ApplicationError from posthog.schema...
590
27,015
posthog
posthog/temporal/alerts/retry_policy.py
.py
import datetime as dt import dataclasses from temporalio.common import RetryPolicy from posthog.schema_enums import AlertCalculationInterval from products.exports.backend.tasks.failure_handler import USER_QUERY_ERROR_NAMES # A user's query error won't clear on retry, so evaluate_alert fails fast on it. Temporal mat...
81
2,902
posthog
posthog/temporal/delete_teams/types.py
.py
import typing import dataclasses @dataclasses.dataclass class TeamDataActivityInputs: """Inputs shared by the per-domain team-data deletion activities.""" team_ids: list[int] user_id: int @property def properties_to_log(self) -> dict[str, typing.Any]: return {"team_ids": self.team_ids, "...
96
2,391
posthog
posthog/temporal/delete_teams/workflows.py
.py
import datetime as dt import temporalio.common import temporalio.workflow import temporalio.exceptions from posthog.temporal.common.base import PostHogWorkflow from posthog.temporal.delete_teams.activities import ( delete_batch_exports_activity, delete_cohort_members_activity, delete_data_modeling_schedul...
271
12,298
posthog
posthog/temporal/delete_teams/__init__.py
.py
from posthog.temporal.delete_teams.activities import ( delete_batch_exports_activity, delete_cohort_members_activity, delete_data_modeling_schedules_activity, delete_groups_activity, delete_loop_trigger_schedules_activity, delete_misc_small_tables_activity, delete_organization_record_activit...
49
1,592
posthog
posthog/temporal/delete_teams/activities.py
.py
import temporalio.activity from temporalio.exceptions import ApplicationError from posthog.sync import database_sync_to_async_pool from posthog.temporal.common.heartbeat import Heartbeater from posthog.temporal.delete_teams.types import ( OrganizationEmailInputs, OrganizationRecordInputs, ProjectEmailInput...
222
9,355
posthog
posthog/temporal/delete_teams/dispatch.py
.py
import asyncio from django.conf import settings from posthog.temporal.common.client import async_connect from posthog.temporal.delete_teams.types import DeleteOrganizationWorkflowInputs, DeleteProjectDataWorkflowInputs def start_delete_project_data_workflow( *, team_ids: list[int], project_id: int | None, user_...
50
1,620
posthog
posthog/schema_migrations/0004_entity_node_kind.py
.py
from posthog.schema_migrations.base import SchemaMigration # Data warehouse series nodes use a different kind per insight type; exclusions have no # data warehouse member, so table_name-shaped exclusion items fall through to EventsNode. SERIES_DATA_WAREHOUSE_KIND = { "TrendsQuery": "DataWarehouseNode", "Sticki...
71
3,063
posthog
posthog/schema_migrations/upgrade.py
.py
from copy import deepcopy from typing import Any from posthog.schema_migrations import LATEST_VERSIONS, MIGRATIONS, _discover_migrations def upgrade(query: dict) -> dict: _discover_migrations() # Lazy load migrations on first use return upgrade_node(query) def upgrade_node(node: Any) -> Any: if isinst...
32
1,028
posthog
posthog/schema_migrations/0002_stickiness_hidden_legend_indexes.py
.py
from posthog.schema_migrations.base import SchemaMigration KIND_TO_FILTER_KEY = { "TrendsQuery": "trendsFilter", "StickinessQuery": "stickinessFilter", } class Migration(SchemaMigration): """Convert 'hiddenLegendIndexes' to a new 'hidden' field of 'resultCustomizations'.""" targets = {"TrendsQuery":...
94
4,060
posthog
posthog/schema_migrations/0003_trends_result_customizations_compare.py
.py
import json from typing import Any, Optional from posthog.schema_migrations.base import SchemaMigration KIND_TO_FILTER_KEY = { "TrendsQuery": "trendsFilter", "StickinessQuery": "stickinessFilter", } class Migration(SchemaMigration): """Merge per-compare-period result customizations into a single base-se...
146
5,771
posthog
posthog/schema_migrations/__init__.py
.py
import os import re import importlib import threading import structlog from posthog.schema_migrations.base import SchemaMigration logger = structlog.get_logger(__name__) LATEST_VERSIONS: dict[str, int] = {} MIGRATIONS: dict[str, dict[int, SchemaMigration]] = {} _migrations_discovered: bool = False _discovery_lock =...
67
2,531
posthog
posthog/schema_migrations/0001_retention_query_show_mean.py
.py
from posthog.schema_migrations.base import SchemaMigration class Migration(SchemaMigration): """Convert boolean 'showMean' field to a 'meanRetentionCalculation' field with 'simple'/'weighted' values.""" targets = {"RetentionQuery": 1} def transform(self, query: dict) -> dict: if query["kind"] !=...
26
884
posthog
posthog/schema_migrations/validate.py
.py
import structlog from posthog.schema_migrations import MIGRATIONS, _discover_migrations logger = structlog.get_logger(__name__) def validate_migrations(): """Validate that all migrations are linear and in strictly increasing order.""" _discover_migrations() # Lazy load migrations on first use for kind,...
19
827
posthog
posthog/schema_migrations/upgrade_manager.py
.py
from collections.abc import Iterator from contextlib import contextmanager from typing import TYPE_CHECKING from posthog.hogql_queries.legacy_compatibility.flagged_conversion_manager import conversion_to_query_based from posthog.schema_migrations.upgrade import upgrade if TYPE_CHECKING: from products.product_anal...
25
873
posthog
posthog/schema_migrations/migrate_mock_insights.py
.py
import sys import glob import json import subprocess from pathlib import Path from typing import Any # Ensure repo root is importable sys.path.insert(0, str(Path(__file__).resolve().parents[2])) from posthog.schema_migrations.upgrade import upgrade MOCKS_DIR = Path(__file__).resolve().parents[2] / "frontend/src/mock...
44
1,130
posthog
posthog/schema_migrations/base.py
.py
from abc import ABC, abstractmethod class SchemaMigration(ABC): """ Base class for schema migrations. Bumps the schema of one or more query types by one version. Subclasses must define: * `targets`: A mapping of node kinds to the version before running the migration. * `transform`: A method that ...
30
1,027
posthog
posthog/schema_migrations/test/test_upgrade_manager.py
.py
from typing import Any, Optional import pytest from unittest.mock import Mock from posthog.schema import NodeKind import posthog.schema_migrations as schema_migrations_module from posthog.schema_migrations import LATEST_VERSIONS, MIGRATIONS, SchemaMigration from posthog.schema_migrations.upgrade_manager import upgra...
56
1,771
posthog
posthog/schema_migrations/test/test_0001_retention_query_show_mean.py
.py
import importlib def test_retention_query_show_mean_migration(): migration_module = importlib.import_module("posthog.schema_migrations.0001_retention_query_show_mean") migration = migration_module.Migration() # Test non-retention query is unchanged other_query = {"kind": "NotRetentionQuery"} asse...
39
1,569
posthog
posthog/schema_migrations/test/test_discovery.py
.py
import json from pathlib import Path import pytest from unittest.mock import MagicMock, patch from posthog.schema import NodeKind import posthog.schema_migrations as schema_migrations_module from posthog.schema_migrations import LATEST_VERSIONS, MIGRATIONS, _discover_migrations from posthog.utils import to_json de...
92
3,446
posthog
posthog/schema_migrations/test/test_upgrade.py
.py
import pytest from posthog.schema import NodeKind import posthog.schema_migrations as schema_migrations_module from posthog.schema_migrations import LATEST_VERSIONS, MIGRATIONS, SchemaMigration from posthog.schema_migrations.upgrade import upgrade class SampleMigration(SchemaMigration): targets = {NodeKind.TREN...
84
2,548
posthog
posthog/schema_migrations/test/test_0002_stickiness_hidden_legend_indexes.py
.py
import importlib def _get_migration(): migration_module = importlib.import_module("posthog.schema_migrations.0002_stickiness_hidden_legend_indexes") return migration_module.Migration() def test_non_trends_query_is_unchanged(): migration = _get_migration() other_query = {"kind": "NotTrendsQuery"} ...
319
11,151
posthog
posthog/schema_migrations/test/test_base.py
.py
from posthog.schema import NodeKind from posthog.schema_migrations.base import SchemaMigration class TestMigration(SchemaMigration): targets = {NodeKind.EVENTS_QUERY: 1} def transform(self, query: dict) -> dict: query["some_key"] = "some_value" return query def test_should_run_returns_true...
57
1,651
posthog
posthog/schema_migrations/test/test_validate.py
.py
import pytest from unittest.mock import MagicMock from posthog.schema import NodeKind import posthog.schema_migrations as schema_migrations_module from posthog.schema_migrations import LATEST_VERSIONS, MIGRATIONS from posthog.schema_migrations.validate import validate_migrations @pytest.fixture(autouse=True) def _r...
43
1,299
posthog
posthog/schema_migrations/test/test_0004_entity_node_kind.py
.py
import importlib from parameterized import parameterized from posthog.schema import FunnelsQuery, LifecycleQuery, TrendsQuery from posthog.schema_migrations.upgrade import upgrade def _get_migration(): migration_module = importlib.import_module("posthog.schema_migrations.0004_entity_node_kind") return migr...
158
6,456
posthog
posthog/schema_migrations/test/test_0003_trends_result_customizations_compare.py
.py
import importlib import pytest COMPARE_ON = {"compareFilter": {"compare": True}} BASE_KEY = '{"series":0}' CURRENT_KEY = '{"series":0,"compare_label":"current"}' PREVIOUS_KEY = '{"series":0,"compare_label":"previous"}' BASE_ENTRY = {"assignmentBy": "value", "color": "preset-1"} CURRENT_ENTRY = {"assignmentBy": "val...
184
7,468
posthog
posthog/heatmaps/sql.py
.py
from django.conf import settings from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE from posthog.clickhouse.kafka_engine import ( CONSUMER_GROUP_HEATMAPS, CONSUMER_GROUP_HEATMAPS_WS, kafka_engine, ttl_period, ) from posthog.clickhouse.table_engines import Distributed, MergeTreeEngine, Replication...
207
7,044
posthog
posthog/clickhouse/custom_metrics.py
.py
from collections.abc import Mapping from concurrent.futures import Future from dataclasses import dataclass from posthog import settings from posthog.clickhouse.cluster import ClickhouseCluster, Query from posthog.clickhouse.table_engines import MergeTreeEngine, ReplicationScheme # This view is accesed through an en...
181
6,306