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/test_run_session_evaluation.py
.py
import uuid from datetime import UTC, datetime, timedelta import pytest from freezegun import freeze_time from unittest.mock import Mock, patch from asgiref.sync import async_to_sync from temporalio.exceptions import ApplicationError from posthog.schema import LLMTrace, LLMTraceEvent from posthog.hogql.constants im...
469
22,594
posthog
posthog/temporal/ai_observability/test_metrics.py
.py
import pytest from unittest.mock import MagicMock, patch from posthog.temporal.ai_observability.metrics import ( EVAL_ACTIVITY_TYPES, EVAL_WORKFLOW_TYPES, EvalsMetricsInterceptor, ExecutionTimeRecorder, ) class TestExecutionTimeRecorder: def test_records_completed_status_on_success(self): ...
135
5,680
posthog
posthog/temporal/ai_observability/run_trace_evaluation.py
.py
"""Trace-level evaluation workflow. The evaluation scheduler starts this workflow when the first $ai_generation matching a trace-target evaluation arrives. The workflow id (`llma-trace-eval-{evaluation_id}-{trace_id}`) plus the USE_EXISTING conflict policy make every later matching event of the same trace a no-op whil...
792
32,073
posthog
posthog/temporal/ai_observability/test_team_capture.py
.py
import time from datetime import UTC, datetime from posthog.test.base import BaseTest from unittest.mock import MagicMock, patch from parameterized import parameterized from posthog.api.capture import CaptureInternalError from posthog.models.team import Team from posthog.temporal.ai_observability.team_capture import...
90
3,371
posthog
posthog/temporal/ai_observability/run_session_evaluation.py
.py
"""Session-level evaluation: fetch, payload caps, Hog globals and judge transcript. Sits beside `run_trace_evaluation` rather than inside it because the shared emit activity lives there, and this module already imports a constant from it; if `run_trace_evaluation` ever imported something back from here, the two would ...
632
27,896
posthog
posthog/temporal/ai_observability/llm_endpoint.py
.py
"""ChatOpenAI client for the labeling/report agents, routed through the internal Go ai-gateway when AI_GATEWAY_URL + AI_GATEWAY_API_KEY are set, else direct to OpenAI. The raw-SDK builders for summarization live in ``posthog.llm.gateway_client`` (importing from this package would pull in the temporal workflow graph an...
94
3,513
posthog
posthog/temporal/ai_observability/coordinator_metrics.py
.py
"""Shared Prometheus metrics for LLMA coordinator workflows. Used by both the summarization and clustering coordinators to track team discovery and per-team success/failure across pipeline runs. """ from posthog.temporal.ai_observability.metrics import get_metric_meter def record_teams_discovered(count: int, pipeli...
48
1,838
posthog
posthog/temporal/ai_observability/evaluation_types.py
.py
from typing import Any, Literal, NotRequired, Required, TypedDict class EvaluationActivityResult(TypedDict, total=False): """Result produced by evaluation execution activities. `total=False` is used as the default so individual fields opt in via `Required` / `NotRequired`, making the contract honest abou...
46
2,131
posthog
posthog/temporal/ai_observability/evaluation_errors.py
.py
"""Shared taxonomy for evaluation execution errors. The split between user-actionable and PostHog-owned errors is load-bearing: most user errors disable the evaluation without failing the Temporal activity, while PostHog-owned errors still raise so Temporal/Grafana stays useful. `hog_input_error` is the one user error...
253
9,384
posthog
posthog/temporal/ai_observability/team_discovery.py
.py
""" Team discovery activity for AI observability workflows. Provides dynamic team discovery that combines a guaranteed allowlist with a configurable random sample of teams that have AI events. Config is read from the `llm-analytics-clustering-workflows` feature flag payload so it can be changed from the PostHog UI wi...
214
8,785
posthog
posthog/temporal/ai_observability/test_team_discovery.py
.py
import math from contextlib import asynccontextmanager import pytest from unittest.mock import patch from parameterized import parameterized from posthog.temporal.ai_observability.team_discovery import ( DEFAULT_DISCOVERY_LOOKBACK_DAYS, DEFAULT_GUARANTEED_TEAM_IDS, DEFAULT_SAMPLE_PERCENTAGE, TeamDisc...
342
14,575
posthog
posthog/temporal/ai_observability/message_utils.py
.py
"""Utilities for extracting and formatting LLM messages from event properties.""" import json from typing import Any, Union def extract_text_from_messages(messages: Union[str, list, dict, None]) -> str: """ Extract readable text from LLM message structures. Handles common message formats from various LL...
333
14,120
posthog
posthog/temporal/ai_observability/__init__.py
.py
from posthog.temporal.ai_observability.eval_reports.activities import ( check_count_triggered_eval_report_activity, check_count_triggered_eval_reports_activity, deliver_report_activity, fetch_count_triggered_eval_report_candidates_activity, fetch_due_eval_reports_activity, prepare_report_context...
194
7,283
posthog
posthog/temporal/ai_observability/shared_activities.py
.py
"""Shared Temporal activities used by multiple llm_analytics workflows.""" import asyncio from dataclasses import dataclass from typing import Any, Literal, cast from temporalio import activity AnalysisLevel = Literal["trace", "generation", "evaluation"] @dataclass class FetchAllClusteringFiltersInput: team_id...
98
3,073
posthog
posthog/temporal/ai_observability/team_capture.py
.py
"""Emitting AI observability events on behalf of a team, without a Postgres read per event. Every emitted `$ai_evaluation` / `$ai_tag` event needs the team's `api_token` to call `capture_internal`. Those emit closures run under `database_sync_to_async(thread_sensitive=False)`, so each one lands on a fresh executor thr...
101
3,781
posthog
posthog/temporal/ai_observability/model_resolution.py
.py
"""Resolves which provider, model and key an eval or tagger run should use. `model_configuration` is optional on both `Evaluation` and `Tagger`. A null value is not "unconfigured" — it means "defer to the team's active key". `model_spec()` turns the (possibly null) serialized config into a `ModelSpec` whose `resolve()...
130
4,750
posthog
posthog/temporal/ai_observability/test_run_evaluation.py
.py
import json import uuid from datetime import UTC, datetime from typing import Any import pytest from unittest.mock import MagicMock, patch from asgiref.sync import sync_to_async from parameterized import parameterized from temporalio import activity from temporalio.api.enums.v1 import EventType from temporalio.except...
2,325
95,338
posthog
posthog/temporal/ai_observability/evaluation_event_io.py
.py
from typing import Any from posthog.dataclasses import frozen @frozen class EventIO: input_raw: Any output_raw: Any def extract_event_io(event_type: str, properties: dict[str, Any]) -> EventIO: """Extract raw input and output values from event properties. Returns an `EventIO` for use in Hog eval g...
52
2,215
posthog
posthog/temporal/ai_observability/test_message_utils.py
.py
"""Tests for message extraction utilities.""" import json import pytest from posthog.temporal.ai_observability.message_utils import extract_text_from_messages, format_tool_definitions class TestExtractTextFromMessages: def test_simple_string(self): """Test extraction from simple string""" resul...
695
28,972
posthog
posthog/temporal/ai_observability/run_aggregate_evaluation.py
.py
"""Aggregate evaluation workflow: a settling phase in front of the shared trace-evaluation body. Successor to `run-trace-evaluation`. The scheduler starts this workflow once per (evaluation, trace) pair on the first condition-matching generation. Under the fixed_window strategy the workflow just sleeps for the configu...
590
27,852
posthog
posthog/temporal/ai_observability/evaluation_sentiment.py
.py
import json import asyncio from typing import Any from temporalio import activity from temporalio.exceptions import ApplicationError from posthog.temporal.ai_observability.evaluation_event_io import extract_event_io from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult from posthog.t...
108
4,137
posthog
posthog/temporal/ai_observability/run_evaluation.py
.py
import json from datetime import timedelta from typing import Any, NotRequired, Required, TypedDict from django.conf import settings import temporalio from temporalio.common import RetryPolicy, WorkflowIDReusePolicy from temporalio.exceptions import ApplicationError from posthog.temporal.ai_observability.evaluation_...
401
16,566
posthog
posthog/temporal/ai_observability/test_evaluation_payload.py
.py
import pytest from posthog.temporal.ai_observability.evaluation_payload import ( PAYLOAD_BYTES_EXPR, payload_budget_bytes, should_skip_for_payload, ) class TestPayloadBudget: def test_budget_tracks_the_targets_judge_budget(self): assert payload_budget_bytes(500_000) > payload_budget_bytes(150...
38
1,677
posthog
posthog/temporal/ai_observability/evaluation_workflow_activities.py
.py
import json from dataclasses import dataclass from datetime import UTC, datetime from typing import Any from django.conf import settings from django.db import transaction import structlog import temporalio from structlog.contextvars import bind_contextvars from posthog.api.capture import CaptureInternalError from po...
376
15,323
posthog
posthog/temporal/ai_observability/metrics.py
.py
import typing import datetime as dt from django.conf import settings from temporalio import activity, workflow from temporalio.worker import ( ActivityInboundInterceptor, ExecuteActivityInput, ExecuteWorkflowInput, Interceptor, WorkflowInboundInterceptor, WorkflowInterceptorClassInput, ) from...
259
10,512
posthog
posthog/temporal/ai_observability/test_evaluation_hog.py
.py
import json import pytest from parameterized import parameterized from temporalio.exceptions import ApplicationError from posthog.temporal.ai_observability.evaluation_errors import is_terminal_user_error_result from posthog.temporal.ai_observability.evaluation_hog import execute_hog_eval_bytecode, finalize_hog_eval_...
128
5,220
posthog
posthog/temporal/ai_observability/test_model_resolution.py
.py
import uuid import pytest from temporalio.exceptions import ApplicationError from posthog.models import Organization, Team from posthog.temporal.ai_observability.model_resolution import DefaultModelSpec, ExplicitModelSpec, model_spec from products.ai_observability.backend.llm import DEFAULT_MODEL_BY_PROVIDER from p...
140
5,861
posthog
posthog/temporal/ai_observability/test_run_tagger.py
.py
import json import uuid from datetime import datetime from typing import Any import pytest from unittest.mock import MagicMock, patch from temporalio.exceptions import ApplicationError from posthog.api.capture import CaptureInternalError from posthog.models import Organization, Team from products.ai_observability.b...
778
29,674
posthog
posthog/temporal/ai_observability/evaluation_payload.py
.py
"""Payload-size budget shared by the trace and session evaluation fetches. The event-count caps (`MAX_TRACE_EVAL_EVENTS`, `MAX_SESSION_EVAL_EVENTS`) bound how many rows an evaluation pulls, which is a poor proxy for what actually costs memory: 2,500 near-limit events and 2,500 one-line events are the same number and w...
67
3,313
posthog
posthog/temporal/ai_observability/test_run_aggregate_evaluation.py
.py
import uuid from datetime import UTC, datetime, timedelta from typing import Any import pytest from freezegun import freeze_time from temporalio import activity from temporalio.exceptions import ApplicationError from temporalio.testing import WorkflowEnvironment from temporalio.worker import UnsandboxedWorkflowRunner...
712
32,294
posthog
posthog/temporal/ai_observability/test_run_trace_evaluation.py
.py
import json import uuid from datetime import UTC, datetime, timedelta from typing import Any import pytest from freezegun import freeze_time from unittest.mock import MagicMock, patch from asgiref.sync import async_to_sync from posthog.schema import LLMTrace, LLMTraceEvent from posthog.hogql import ast from postho...
752
30,666
posthog
posthog/temporal/ai_observability/evaluation_llm_judge.py
.py
import json from dataclasses import dataclass from datetime import timedelta from typing import Any import structlog import temporalio import posthoganalytics from pydantic import BaseModel, model_validator from structlog.contextvars import bind_contextvars from temporalio.common import RetryPolicy from temporalio.exc...
470
17,275
posthog
posthog/temporal/ai_observability/conftest.py
.py
import pytest from posthog.temporal.ai_observability.team_capture import clear_team_api_token_cache @pytest.fixture(autouse=True) def _clear_team_api_token_cache(): # The token cache is per worker process, so it would otherwise leak across tests that # reuse team ids from a rolled-back transaction. clear...
13
387
posthog
posthog/temporal/ai_observability/clustering_agent/__init__.py
.py
"""Shared machinery for LangGraph cluster-labeling agents across analysis levels. The trace/generation labeling agent (``trace_clustering/labeling_agent``) and the evaluation labeling agent (``evaluation_clustering/labeling_agent``) are structurally parallel — same ReAct loop, same ChatOpenAI guardrails, same default-...
79
3,042
posthog
posthog/temporal/ai_observability/eval_reports/types.py
.py
"""Dataclass inputs/outputs for evaluation reports activities.""" import dataclasses from typing import Any @dataclasses.dataclass class ScheduleAllEvalReportsWorkflowInputs: buffer_minutes: int = 15 @dataclasses.dataclass class CheckCountTriggeredReportsWorkflowInputs: pass @dataclasses.dataclass class ...
137
3,053
posthog
posthog/temporal/ai_observability/eval_reports/output_types.py
.py
"""Trusted query definitions for evaluation report outcomes.""" from collections.abc import Mapping from dataclasses import dataclass @dataclass(frozen=True) class EvaluationReportOutcomeDefinition: outcomes: tuple[str, ...] outcome_predicates: Mapping[str, str] event_predicate: str result_expression...
58
2,714
posthog
posthog/temporal/ai_observability/eval_reports/workflow.py
.py
"""Temporal workflows for evaluation reports.""" import json import asyncio from datetime import timedelta from django.conf import settings import temporalio.workflow from structlog import get_logger from temporalio.common import WorkflowIDReusePolicy from temporalio.exceptions import WorkflowAlreadyStartedError fr...
438
19,161
posthog
posthog/temporal/ai_observability/eval_reports/emit_signal.py
.py
"""Emit a signal per evaluation report run. This is the only path from AI observability evaluations into Signals. Emitting one signal per individual `$ai_evaluation` result flooded inboxes and said little; a report already aggregates the underlying results into an analytical narrative (trend, patterns, citations), so ...
242
10,965
posthog
posthog/temporal/ai_observability/eval_reports/constants.py
.py
"""Configuration constants for evaluation reports workflow.""" from datetime import timedelta from temporalio.common import RetryPolicy # Agent configuration EVAL_REPORT_AGENT_MODEL = "gpt-5.2" EVAL_REPORT_AGENT_RECURSION_LIMIT = 100 EVAL_REPORT_AGENT_TIMEOUT = 600.0 # 10 minutes # Workflow names — all eval-report...
96
4,213
posthog
posthog/temporal/ai_observability/eval_reports/schedule.py
.py
"""Temporal schedule registration for evaluation reports.""" from dataclasses import asdict from datetime import timedelta from django.conf import settings from temporalio.client import Client, Schedule, ScheduleActionStartWorkflow, ScheduleIntervalSpec, ScheduleSpec from posthog.temporal.ai_observability.eval_repo...
57
2,255
posthog
posthog/temporal/ai_observability/eval_reports/metrics.py
.py
"""Prometheus metrics for the LLMA evaluation reports temporal workflows. Follows the same pattern as trace_clustering/metrics.py. Metrics are emitted via Temporal's built-in metric meter (activity/workflow context) and scraped by the Prometheus endpoint on the worker pod. """ import typing import datetime as dt fro...
210
7,830
posthog
posthog/temporal/ai_observability/eval_reports/delivery.py
.py
"""Delivery logic for evaluation reports (email and Slack). Content shape: `EvalReportContent` has a `title`, 1-6 titled `sections`, a list of structured `citations`, and a `metrics` block. The renderers below build the email HTML body and Slack Block Kit payloads from that shape. """ import re from dataclasses impor...
523
21,894
posthog
posthog/temporal/ai_observability/eval_reports/activities.py
.py
"""Activities for evaluation reports workflow.""" import time import datetime as dt from collections import defaultdict from typing import TYPE_CHECKING, NamedTuple from zoneinfo import ZoneInfo from django.db.models import Q import temporalio.activity from dateutil.rrule import rrulestr from structlog import get_lo...
855
36,336
posthog
posthog/temporal/ai_observability/eval_reports/targets.py
.py
"""Evaluation-target descriptors shared by report queries, tools, and prompts. One entry per target, so adding a target is adding a row here rather than another `if target == ...` branch in every consumer. """ from dataclasses import dataclass GENERATION_TARGET = "generation" TRACE_TARGET = "trace" SESSION_TARGET = ...
80
2,670
posthog
posthog/temporal/ai_observability/eval_reports/report_agent/state.py
.py
"""State definitions for the evaluation report agent.""" from typing import Annotated, TypedDict from langgraph.graph.message import add_messages from langgraph.managed import RemainingSteps from posthog.temporal.ai_observability.eval_reports.report_agent.schema import EvalReportContent class EvalReportAgentState(...
45
1,542
posthog
posthog/temporal/ai_observability/eval_reports/report_agent/__init__.py
.py
from posthog.temporal.ai_observability.eval_reports.report_agent.graph import run_eval_report_agent __all__ = ["run_eval_report_agent"]
4
137
posthog
posthog/temporal/ai_observability/eval_reports/report_agent/schema.py
.py
"""Dataclasses for evaluation report content, metrics, and citations. The v2 schema splits the report into: - `evaluation_target`: the evaluated unit (`generation`, `trace`, or `session`) - `metrics`: structured numeric data computed mechanically from ClickHouse, the agent cannot fabricate these - `title`: the agent...
361
14,538
posthog
posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
.py
"""Tool definitions for the evaluation report agent. Uses LangGraph's InjectedState pattern so tools can access graph state directly. All query tools hit ClickHouse live via HogQL since the dataset is too large/variable to pre-load. Output tools mutate `state["report"]` (an EvalReportContent instance) via list append ...
1,642
62,954
posthog
posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py
.py
"""System prompt construction for the evaluation report agent.""" from posthog.temporal.ai_observability.eval_reports.output_types import get_outcome_definition from posthog.temporal.ai_observability.eval_reports.report_agent.schema import MAX_REPORT_SECTIONS from posthog.temporal.ai_observability.eval_reports.targets...
251
15,451
posthog
posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
.py
"""LangGraph agent for evaluation report generation using create_react_agent.""" import uuid from typing import Any import structlog from langchain_core.messages import HumanMessage from langchain_core.runnables import RunnableConfig from langgraph.prebuilt import create_react_agent from posthog.llm.gateway_client i...
397
15,142
posthog
posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py
.py
"""Tests for the v2 graph helpers: _fallback_content and _validate_agent_output.""" from unittest.mock import MagicMock, patch from django.test import SimpleTestCase from parameterized import parameterized from posthog.exceptions import ClickHouseAtCapacity from posthog.temporal.ai_observability.eval_reports.report...
535
22,478
posthog
posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools_ai_events_routing.py
.py
"""Tests for the eval-report agent's heavy-prop tools. `sample_generation_details`, `get_generation_detail`, and `get_generation_text_repr` are the three tools that read heavy columns. They route through `_execute_hogql_via_ai_events` which wraps the resolver. The other query sites in `tools.py` deliberately stay on `...
355
15,329
posthog
posthog/temporal/ai_observability/eval_reports/report_agent/test/test_schema.py
.py
"""Tests for the v2 eval report schema.""" from django.test import SimpleTestCase from parameterized import parameterized from posthog.temporal.ai_observability.eval_reports.output_types import SUPPORTED_EVAL_REPORT_OUTPUT_TYPES from posthog.temporal.ai_observability.eval_reports.report_agent.schema import ( MAX...
285
11,883
posthog
posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py
.py
"""Tests for the v2 eval report agent output tools (set_title, add_section, add_citation).""" import json import datetime as dt from typing import NotRequired, TypedDict from posthog.test.base import BaseTest from unittest.mock import ( MagicMock, call as mock_call, patch, ) from django.test import Simpl...
1,152
50,880
posthog
posthog/temporal/ai_observability/eval_reports/test/test_delivery.py
.py
from unittest.mock import MagicMock, patch from django.test import SimpleTestCase from parameterized import parameterized from posthog.temporal.ai_observability.eval_reports.delivery import ( CitationMap, _build_citation_map, _format_period_for_display, _inline_email_styles, _linkify_citations, ...
607
27,018
posthog
posthog/temporal/ai_observability/eval_reports/test/test_activities.py
.py
import datetime as dt from contextlib import asynccontextmanager import pytest from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event from unittest.mock import MagicMock, Mock, patch from django.test import SimpleTestCase from django.utils import timezone from parameterized import parameterized ...
1,013
45,616
posthog
posthog/temporal/ai_observability/eval_reports/test/test_emit_signal.py
.py
import random import pytest from unittest.mock import AsyncMock, patch import pytest_asyncio from asgiref.sync import sync_to_async from posthog.models import Organization, Team from posthog.temporal.ai_observability.eval_reports.emit_signal import ( EmitEvalReportSignalInputs, EvalReportSignalSummary, _...
269
10,990
posthog
posthog/temporal/ai_observability/eval_reports/test/test_workflow.py
.py
import asyncio from uuid import UUID import pytest from unittest.mock import patch from posthog.temporal.ai_observability.eval_reports.activities import ( deliver_report_activity, update_next_delivery_date_activity, ) from posthog.temporal.ai_observability.eval_reports.types import ( CheckCountTriggeredEv...
449
17,810
posthog
posthog/temporal/ai_observability/trace_summarization/workflow.py
.py
""" Batch trace summarization workflow for LLMA. This workflow runs on a schedule (e.g., hourly) to: 1. Query recent traces from a time window 2. Generate text representations and summaries for each trace 3. Store summaries as $ai_trace_summary events in ClickHouse 4. Queue embeddings for summaries via Kafka for async...
287
11,685
posthog
posthog/temporal/ai_observability/trace_summarization/state.py
.py
"""Redis intermediate storage for passing text_repr between activities. Stores gzip-compressed text representations in Redis so that only small references (~100 bytes) flow through Temporal workflow history while the large payloads (up to 2 MB) go through Redis. """ import gzip import structlog from redis import asy...
46
1,379
posthog
posthog/temporal/ai_observability/trace_summarization/utils.py
.py
"""Utility functions for trace summarization.""" from datetime import datetime def format_datetime_for_clickhouse(iso_string: str) -> str: """Convert ISO format datetime string to ClickHouse-compatible format.""" dt = datetime.fromisoformat(iso_string) return dt.strftime("%Y-%m-%d %H:%M:%S")
10
308
posthog
posthog/temporal/ai_observability/trace_summarization/models.py
.py
"""Data models for batch trace summarization.""" from dataclasses import dataclass, field from typing import Any, Literal from pydantic import BaseModel from posthog.temporal.ai_observability.trace_summarization.constants import ( DEFAULT_BATCH_SIZE, DEFAULT_MAX_ITEMS_PER_WINDOW, DEFAULT_MODE, DEFAUL...
180
5,485
posthog
posthog/temporal/ai_observability/trace_summarization/sampling.py
.py
"""Activity for sampling traces/generations from a time window. Uses lightweight HogQL queries to sample trace IDs and timestamps. The full trace data is fetched later by the summarization activity using TraceQueryRunner per-item, so sampling only needs IDs and timestamps. """ from typing import Any import structlog...
280
12,153
posthog
posthog/temporal/ai_observability/trace_summarization/summarize_and_save.py
.py
"""Activity for generating LLM summary and saving the result.""" import time from dataclasses import dataclass from uuid import uuid4 import structlog import temporalio from posthog.models.event.util import create_event from posthog.models.team import Team from posthog.redis import get_async_client from posthog.sync...
294
10,952
posthog
posthog/temporal/ai_observability/trace_summarization/__init__.py
.py
"""Trace summarization workflows and activities for batch processing.""" from posthog.temporal.ai_observability.trace_summarization.constants import ( COORDINATOR_WORKFLOW_NAME, DEFAULT_BATCH_SIZE, DEFAULT_MAX_ITEMS_PER_WINDOW, DEFAULT_MODE, DEFAULT_WINDOW_MINUTES, EVENT_NAME_TRACE_SUMMARY, ...
46
1,812
posthog
posthog/temporal/ai_observability/trace_summarization/constants.py
.py
"""Constants for batch trace summarization workflows.""" from datetime import timedelta from temporalio.common import RetryPolicy from products.ai_observability.backend.summarization.models import OpenAIModel, SummarizationMode # Window processing configuration DEFAULT_MAX_ITEMS_PER_WINDOW = ( 15 # Max items t...
156
7,701
posthog
posthog/temporal/ai_observability/trace_summarization/queries.py
.py
"""ClickHouse queries for trace summarization. Routes through `TraceQueryRunner` so reads land on the dedicated `ai_events` table (falling back to the shared `events` table for data beyond the retention window). The runner re-merges the heavy columns into `event.properties`, so downstream formatters keep working. """ ...
38
1,521
posthog
posthog/temporal/ai_observability/trace_summarization/schedule.py
.py
"""Schedule configuration for batch trace summarization.""" from datetime import timedelta from django.conf import settings from temporalio.client import ( Client, Schedule, ScheduleActionStartWorkflow, ScheduleIntervalSpec, ScheduleOverlapPolicy, SchedulePolicy, ScheduleSpec, ) from pos...
109
4,241
posthog
posthog/temporal/ai_observability/trace_summarization/coordinator.py
.py
""" Coordinator workflow for batch trace summarization. This workflow discovers teams dynamically via the team discovery activity and spawns child workflows to process traces for each team. Uses continue_as_new after each batch to keep the workflow history bounded (Temporal has a 50K event limit per execution). Per-...
315
14,479
posthog
posthog/temporal/ai_observability/trace_summarization/metrics.py
.py
"""Prometheus metrics for the LLMA trace summarization temporal workflows. Follows the same pattern as posthog.temporal.ai_observability.metrics (evals). Metrics are emitted via Temporal's built-in metric meter (activity/workflow context) and scraped by the Prometheus endpoint on the worker pod. """ import typing imp...
163
5,947
posthog
posthog/temporal/ai_observability/trace_summarization/fetch_and_format.py
.py
"""Activity for fetching trace/generation data and storing formatted text in Redis.""" import time import structlog import temporalio from posthog.hogql import ast from posthog.hogql.parser import parse_select from posthog.clickhouse.query_tagging import Feature, Product, tags_context from posthog.hogql_queries.ai....
320
11,400
posthog
posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format_heavy_columns.py
.py
"""Unit tests for the `_fetch_and_format_generation` query. Verifies the by-uuid generation lookup routes through `query_ai_events` and reads the heavy `input` / `output` from `posthog.ai_events` native columns. """ from typing import cast import pytest from unittest.mock import MagicMock, patch from posthog.hogql ...
126
5,071
posthog
posthog/temporal/ai_observability/trace_summarization/tests/test_metrics.py
.py
from unittest.mock import MagicMock, patch from parameterized import parameterized from posthog.temporal.ai_observability.trace_summarization.metrics import ( SUMMARIZATION_ACTIVITY_TYPES, SUMMARIZATION_WORKFLOW_TYPES, SummarizationMetricsInterceptor, increment_embedding_result, increment_errors, ...
117
4,571
posthog
posthog/temporal/ai_observability/trace_summarization/tests/test_coordinator.py
.py
"""Tests for batch trace summarization coordinator workflow.""" import pytest from posthog.temporal.ai_observability.shared_activities import JobConfig, resolve_level_jobs_for_team from posthog.temporal.ai_observability.trace_summarization.constants import ( DEFAULT_BATCH_SIZE, DEFAULT_MAX_ITEMS_PER_WINDOW, ...
168
6,237
posthog
posthog/temporal/ai_observability/trace_summarization/tests/test_summarize_and_save.py
.py
"""Tests for unified summarize_and_save activity.""" import uuid from contextlib import asynccontextmanager from datetime import UTC, datetime import pytest from unittest.mock import patch from posthog.temporal.ai_observability.trace_summarization.models import SummarizeAndSaveInput, TextReprExpiredError from postho...
203
9,050
posthog
posthog/temporal/ai_observability/trace_summarization/tests/test_workflow.py
.py
"""Tests for batch trace summarization workflow and sampling.""" from contextlib import asynccontextmanager import pytest from unittest.mock import patch from posthog.hogql.context import HogQLContext from posthog.hogql.placeholders import replace_placeholders from posthog.hogql.printer.utils import prepare_and_prin...
390
15,751
posthog
posthog/temporal/ai_observability/trace_summarization/tests/test_queries.py
.py
"""Tests for `fetch_trace` in the trace-summarization Temporal pipeline. Heavy columns must come back populated on the dedicated `ai_events` path (they live only there), and the function must hand back a fully-formed LLMTrace, not raise. """ import pytest from unittest.mock import MagicMock, patch from posthog.schem...
88
3,901
posthog
posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format.py
.py
"""Tests for unified fetch_and_format activity.""" import uuid from contextlib import asynccontextmanager from datetime import UTC, datetime import pytest from unittest.mock import MagicMock, patch from posthog.temporal.ai_observability.trace_summarization.fetch_and_format import ( _fetch_and_format_trace, _...
282
11,272
posthog
posthog/temporal/ai_observability/trace_summarization/tests/test_state.py
.py
"""Tests for Redis intermediate storage helpers.""" import gzip import pytest from unittest.mock import AsyncMock from posthog.temporal.ai_observability.trace_summarization.state import ( REDIS_KEY_PREFIX, REDIS_TTL_SECONDS, delete_text_repr, generate_redis_key, load_text_repr, store_text_rep...
92
2,814
posthog
posthog/temporal/ai_observability/trace_clustering/clustering.py
.py
"""Clustering utilities: HDBSCAN and k-means implementations.""" import os import sys # Configure Numba threading layer BEFORE importing UMAP (which uses Numba internally). # The default "workqueue" threading layer is not thread-safe and crashes when multiple # Python threads call Numba functions concurrently - which...
367
13,120
posthog
posthog/temporal/ai_observability/trace_clustering/workflow.py
.py
"""Daily trace clustering workflow.""" import json from datetime import timedelta import temporalio.exceptions from temporalio import workflow from posthog.temporal.ai_observability.trace_clustering.activities import ( emit_cluster_events_activity, generate_cluster_labels_activity, perform_clustering_com...
314
13,095
posthog
posthog/temporal/ai_observability/trace_clustering/models.py
.py
"""Data models for trace clustering workflow.""" from dataclasses import dataclass, field from typing import Any, TypedDict from posthog.temporal.ai_observability.shared_activities import AnalysisLevel # noqa: F401 from posthog.temporal.ai_observability.trace_clustering.constants import ( DEFAULT_LOOKBACK_DAYS, ...
352
13,333
posthog
posthog/temporal/ai_observability/trace_clustering/__init__.py
.py
"""Trace clustering workflow exports.""" from posthog.temporal.ai_observability.trace_clustering.activities import ( emit_cluster_events_activity, generate_cluster_labels_activity, perform_clustering_compute_activity, ) from posthog.temporal.ai_observability.trace_clustering.aggregates import compute_clust...
22
842
posthog
posthog/temporal/ai_observability/trace_clustering/constants.py
.py
"""Configuration constants for trace clustering workflow.""" from datetime import timedelta from temporalio.common import RetryPolicy # Clustering parameters DEFAULT_LOOKBACK_DAYS = 7 DEFAULT_MAX_SAMPLES = 1500 DEFAULT_MIN_K = 2 DEFAULT_MAX_K = 10 # Minimum items required for clustering, checked per analysis level ...
136
6,716
posthog
posthog/temporal/ai_observability/trace_clustering/data.py
.py
"""Data access layer for trace clustering. This module consolidates all HogQL queries used by the clustering workflow, providing a single source of truth for data fetching operations. All queries are team-scoped through HogQL's automatic team filtering. """ from dataclasses import dataclass from datetime import datet...
412
17,020
posthog
posthog/temporal/ai_observability/trace_clustering/schedule.py
.py
"""Schedule configuration for daily trace clustering coordinator.""" from datetime import timedelta from django.conf import settings from temporalio.client import ( Client, Schedule, ScheduleActionStartWorkflow, ScheduleIntervalSpec, ScheduleOverlapPolicy, SchedulePolicy, ScheduleSpec, ) ...
121
4,425
posthog
posthog/temporal/ai_observability/trace_clustering/coordinator.py
.py
""" Coordinator workflow for daily trace clustering. This workflow discovers teams dynamically via the team discovery activity and spawns child workflows to cluster traces for each team. Uses continue_as_new after each batch to keep the workflow history bounded (Temporal has a 50K event limit per execution). Per-tea...
305
14,146
posthog
posthog/temporal/ai_observability/trace_clustering/metrics.py
.py
"""Prometheus metrics for the LLMA trace clustering temporal workflows. Follows the same pattern as trace_summarization/metrics.py. Metrics are emitted via Temporal's built-in metric meter (activity/workflow context) and scraped by the Prometheus endpoint on the worker pod. """ import typing import datetime as dt fr...
210
7,888
posthog
posthog/temporal/ai_observability/trace_clustering/activities.py
.py
"""Temporal activities for trace clustering workflow. This module contains the 3 activities that make up the clustering pipeline: 1. perform_clustering_compute_activity - fetch embeddings, cluster, compute distances 2. generate_cluster_labels_activity - LLM labeling for clusters 3. emit_cluster_events_activity - emit ...
411
16,265
posthog
posthog/temporal/ai_observability/trace_clustering/aggregates.py
.py
"""Compute aggregate metrics (cost, latency, tokens, errors) for clusters. This activity is best-effort: it returns whatever metrics it managed to compute. """ import time import asyncio from django.utils.dateparse import parse_datetime import structlog from temporalio import activity from posthog.models.team impo...
129
4,477
posthog
posthog/temporal/ai_observability/trace_clustering/event_emission.py
.py
"""Event emission for clustering results. This module contains functions for emitting clustering results to ClickHouse: - Build cluster data structures with centroids and distances - Emit $ai_trace_clusters event with all clustering metadata - Handle noise/outlier cluster from HDBSCAN (cluster_id = -1) """ import uui...
327
12,766
posthog
posthog/temporal/ai_observability/trace_clustering/labeling.py
.py
"""LLM-based cluster labeling for trace clustering workflow. This module provides cluster labeling using a LangGraph agent that can iteratively explore cluster structure and generate high-quality labels. """ from datetime import datetime import numpy as np from posthog.models.team import Team from posthog.temporal....
169
6,660
posthog
posthog/temporal/ai_observability/trace_clustering/tests/test_event_emission.py
.py
"""Tests for event emission in trace clustering.""" import pytest from unittest.mock import patch import numpy as np from parameterized import parameterized from posthog.temporal.ai_observability.trace_clustering.constants import NOISE_CLUSTER_ID from posthog.temporal.ai_observability.trace_clustering.event_emission...
378
14,645
posthog
posthog/temporal/ai_observability/trace_clustering/tests/test_metrics.py
.py
from unittest.mock import MagicMock, patch from parameterized import parameterized from posthog.temporal.ai_observability.trace_clustering.metrics import ( CLUSTERING_ACTIVITY_TYPES, CLUSTERING_WORKFLOW_TYPES, ClusteringMetricsInterceptor, increment_errors, increment_workflow_finished, increme...
137
5,723
posthog
posthog/temporal/ai_observability/trace_clustering/tests/test_coordinator.py
.py
"""Tests for trace clustering coordinator workflow.""" import pytest from posthog.temporal.ai_observability.shared_activities import JobConfig, resolve_level_jobs_for_team from posthog.temporal.ai_observability.trace_clustering import constants from posthog.temporal.ai_observability.trace_clustering.coordinator impor...
142
5,199
posthog
posthog/temporal/ai_observability/trace_clustering/tests/test_workflow.py
.py
"""Tests for trace clustering workflow.""" import uuid from datetime import UTC, datetime import pytest from unittest.mock import patch import numpy as np from temporalio import activity from temporalio.testing import WorkflowEnvironment from temporalio.worker import UnsandboxedWorkflowRunner, Worker from posthog.t...
464
18,369
posthog
posthog/temporal/ai_observability/trace_clustering/tests/test_clustering.py
.py
"""Tests for clustering utilities: HDBSCAN, k-means, and dimensionality reduction.""" import pytest import numpy as np from parameterized import parameterized # Check if UMAP threading backend is available (required for UMAP tests) def _umap_threading_available() -> bool: """Check if UMAP can run without thread...
244
9,148
posthog
posthog/temporal/ai_observability/trace_clustering/tests/test_labeling_agent.py
.py
"""Tests for the cluster labeling agent.""" import json from unittest.mock import ANY, MagicMock, patch from langchain_core.messages import HumanMessage from posthog.temporal.ai_observability.trace_clustering.labeling_agent.graph import ( _apply_fallbacks as _fill_missing_labels, run_labeling_agent, ) from ...
473
16,414
posthog
posthog/temporal/ai_observability/trace_clustering/tests/test_data.py
.py
"""Tests for data access layer in trace clustering.""" from datetime import UTC, datetime import pytest from unittest.mock import MagicMock, patch from posthog.temporal.ai_observability.trace_clustering.data import ( fetch_item_embeddings_for_clustering, fetch_item_summaries, ) @pytest.fixture def mock_tea...
333
13,351
posthog
posthog/temporal/ai_observability/trace_clustering/labeling_agent/state.py
.py
"""State definitions for the 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, TraceSummary class TraceMetadata(TypedDic...
97
2,482