:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(aio): discover summarization teams from the run's window (#114064)
posthog[bot]bbd2ff107fea
diff --git a/posthog/tasks/test/test_ai_observability_usage_report.py b/posthog/tasks/test/test_ai_observability_usage_report.pyindex d8200bd7ca50..8a97e8b97ac7 100644--- a/posthog/tasks/test/test_ai_observability_usage_report.py+++ b/posthog/tasks/test/test_ai_observability_usage_report.py@@ -1004,6 +1004,25 @@ class TestAIObservabilityUsageReport(APIBaseTest, ClickhouseTestMixin, Clickhousassert team_3.id not in team_idsassert len(team_ids) == 3+ @parameterized.expand(+ [+ ("inside", "$ai_generation", timedelta(minutes=30), True),+ ("at_start_is_included", "$ai_trace", timedelta(0), True),+ ("span_only", "$ai_span", timedelta(minutes=45), True),+ ("just_before_start", "$ai_generation", -timedelta(seconds=1), False),+ ("at_end_is_excluded", "$ai_generation", timedelta(hours=1), False),+ ]+ )+ def test_get_teams_with_ai_events_hour_window_boundaries(+ self, _name: str, event: str, offset: timedelta, expected: bool+ ) -> None:+ start = datetime(2022, 1, 9, 10, tzinfo=UTC)+ self._create_ai_events(self.team, str(uuid4()), event, 1, timestamp=start + offset)++ team_ids = get_teams_with_ai_events(start, start + timedelta(hours=1), LLM_ANALYTICS_DISCOVERY_TRIGGER_EVENTS)++ assert (self.team.id in team_ids) == expected+def test_get_llm_prompt_fetched_counts(self) -> None:"""Test that get_llm_prompt_fetched_counts returns per-team prompt fetch totals."""org_2 = Organization.objects.create(name="Org 2")diff --git a/posthog/temporal/ai_observability/team_discovery.py b/posthog/temporal/ai_observability/team_discovery.pyindex 17c1e1ff2c25..9128d4b1f2c7 100644--- a/posthog/temporal/ai_observability/team_discovery.py+++ b/posthog/temporal/ai_observability/team_discovery.py@@ -147,10 +147,12 @@ DISCOVERY_ACTIVITY_RETRY_POLICY = RetryPolicy(maximum_attempts=2)DISCOVERY_FAIL_CLOSED_PATCH_ID = "ai-observability-discovery-fail-closed-2026-09"[email protected](frozen=True)class TeamDiscoveryInput:- # Empty: discovery config is read from the flag payload inside the activity.- pass+ # A coordinator that processes one window sets it, so a team with no AI events in that window does not cost+ # a child workflow and its sampling query. Without a window, discovery uses the flag's lookback days.+ window_start: str | None = None+ window_end: str | None = None@retry(@@ -163,7 +165,6 @@ async def _consented_team_ids_with_retry(team_ids: list[int]) -> set[int]:return await database_sync_to_async_pool(consented_team_ids)(team_ids)-# TODO: drop `inputs`/TeamDiscoveryInput next release; kept so pre-rollout activity tasks still deserialize.@temporalio.activity.defn(name="get_team_ids_for_llm_analytics")async def get_team_ids_for_ai_observability(inputs: TeamDiscoveryInput | None = None) -> list[int]:"""@@ -187,8 +188,12 @@ async def get_team_ids_for_ai_observability(inputs: TeamDiscoveryInput | None =lookback_days = config.discovery_lookback_daystry:- end = datetime.now(UTC)- begin = end - timedelta(days=lookback_days)+ if inputs is not None and inputs.window_start and inputs.window_end:+ begin = datetime.fromisoformat(inputs.window_start)+ end = datetime.fromisoformat(inputs.window_end)+ else:+ end = datetime.now(UTC)+ begin = end - timedelta(days=lookback_days)from posthog.tasks.ai_observability_usage_report import (LLM_ANALYTICS_DISCOVERY_TRIGGER_EVENTS,@@ -213,6 +218,8 @@ async def get_team_ids_for_ai_observability(inputs: TeamDiscoveryInput | None =# order, so a run that stops early skips different teams each hour.discovered = sorted(guaranteed - skip) + sampleddiscovery_context = {+ "discovery_begin": begin.isoformat(),+ "discovery_end": end.isoformat(),"ai_event_teams_count": len(ai_event_teams),"remaining_count": len(remaining),"sampled_count": len(sampled),diff --git a/posthog/temporal/ai_observability/test_team_discovery.py b/posthog/temporal/ai_observability/test_team_discovery.pyindex a0e5221fd63f..1eef1e0933cc 100644--- a/posthog/temporal/ai_observability/test_team_discovery.py+++ b/posthog/temporal/ai_observability/test_team_discovery.py@@ -1,6 +1,7 @@import mathfrom collections.abc import Awaitable, Callable, Iteratorfrom contextlib import asynccontextmanager+from datetime import UTC, datetimefrom functools import partialimport pytest@@ -353,19 +354,30 @@ class TestGetTeamIdsForAIObservability:assert "$ai_generation" in passed_trigger_eventsassert set(passed_trigger_events) < set(AI_OBSERVABILITY_REPORT_TRIGGER_EVENTS)+ @pytest.mark.parametrize(+ "inputs,expected_window",+ [+ pytest.param(TeamDiscoveryInput(), None, id="flag_lookback_days"),+ pytest.param(+ TeamDiscoveryInput(window_start="2026-01-01T10:00:00Z", window_end="2026-01-01T11:00:00Z"),+ (datetime(2026, 1, 1, 10, tzinfo=UTC), datetime(2026, 1, 1, 11, tzinfo=UTC)),+ id="explicit_window_overrides_lookback",+ ),+ ],+ )@patch("posthog.tasks.ai_observability_usage_report.get_teams_with_ai_events")- async def test_lookback_uses_ff_payload_value(self, mock_get_teams, mock_ff):- """The discovery activity scopes its eligibility query to the- discovery_lookback_days from the feature flag payload.- """+ async def test_eligibility_query_window(self, mock_get_teams, mock_ff, inputs, expected_window):mock_ff.return_value = {"discovery_lookback_days": 3}mock_get_teams.return_value = []- await get_team_ids_for_ai_observability(TeamDiscoveryInput())+ await get_team_ids_for_ai_observability(inputs)begin, end = mock_get_teams.call_args.args[0], mock_get_teams.call_args.args[1]- delta_days = (end - begin).total_seconds() / 86400- assert 2.99 < delta_days < 3.01+ if expected_window is None:+ delta_days = (end - begin).total_seconds() / 86400+ assert 2.99 < delta_days < 3.01+ else:+ assert (begin, end) == expected_windowdef _create_team(name: str, approved: bool) -> int:@@ -469,6 +481,9 @@ class TestCoordinatorConsentGate:async def test_discovery_failure_does_not_start_team_workflows(self, run: Callable[[], Awaitable[object]]) -> None:with (patch("temporalio.workflow.patched", return_value=True),+ patch(+ "temporalio.workflow.info", return_value=MagicMock(workflow_start_time=datetime(2026, 1, 1, tzinfo=UTC))+ ),patch("temporalio.workflow.execute_activity", side_effect=RuntimeError("Discovery unavailable")),patch("temporalio.workflow.start_child_workflow") as start_child,):diff --git a/posthog/temporal/ai_observability/trace_summarization/README.md b/posthog/temporal/ai_observability/trace_summarization/README.mdindex 0e3c764cc633..f68f0058eee2 100644--- a/posthog/temporal/ai_observability/trace_summarization/README.md+++ b/posthog/temporal/ai_observability/trace_summarization/README.md@@ -144,6 +144,9 @@ The coordinator runs hourly via Temporal schedule (configured in `schedule.py`).### Team DiscoveryTeams are discovered dynamically via `team_discovery.py`: guaranteed teams (in `GUARANTEED_TEAM_IDS`) plus a configurable random sample of teams with AI events.+The coordinator passes its summarization window to discovery, so the sample only holds teams with AI events in that window.+A team with no AI events in the window has nothing to summarize, and it would still cost a child workflow and a sampling query.+The clustering coordinators pass no window, so their discovery uses `discovery_lookback_days` from the flag payload.Every discovered team must also pass the consent gate below, guaranteed teams included.### AI data processing consentdiff --git a/posthog/temporal/ai_observability/trace_summarization/coordinator.py b/posthog/temporal/ai_observability/trace_summarization/coordinator.pyindex 535f5e657580..a8b8e84f5a2c 100644--- a/posthog/temporal/ai_observability/trace_summarization/coordinator.py+++ b/posthog/temporal/ai_observability/trace_summarization/coordinator.py@@ -185,10 +185,17 @@ class BatchTraceSummarizationCoordinatorWorkflow(PostHogWorkflow):window_minutes=inputs.window_minutes,)+ # Discover only teams with AI events in the window the children summarize, because the+ # discovery lookback is days and most of those teams have nothing in this window.+ window = (+ inputs+ if inputs.window_start and inputs.window_end+ else _with_summarization_window(inputs, temporalio.workflow.info().workflow_start_time)+ )try:team_ids = await temporalio.workflow.execute_activity(get_team_ids_for_ai_observability,- TeamDiscoveryInput(),+ TeamDiscoveryInput(window_start=window.window_start, window_end=window.window_end),start_to_close_timeout=DISCOVERY_ACTIVITY_TIMEOUT,retry_policy=DISCOVERY_ACTIVITY_RETRY_POLICY,)diff --git a/posthog/temporal/ai_observability/trace_summarization/tests/test_coordinator.py b/posthog/temporal/ai_observability/trace_summarization/tests/test_coordinator.pyindex ba85a058aa49..57d75bbcc5d8 100644--- a/posthog/temporal/ai_observability/trace_summarization/tests/test_coordinator.py+++ b/posthog/temporal/ai_observability/trace_summarization/tests/test_coordinator.py@@ -45,6 +45,7 @@ SLOW_TEAM_ID = 1DISCOVERED_TEAM_IDS = [SLOW_TEAM_ID, 2, 3, 4, 5]child_runs: list[dict[str, Any]] = []+discovery_inputs: list[TeamDiscoveryInput | None] = []@workflow.defn(name=WORKFLOW_NAME)@@ -72,6 +73,7 @@ class FakeTeamSummarizationWorkflow:@activity.defn(name="get_team_ids_for_llm_analytics")async def fake_team_discovery(inputs: TeamDiscoveryInput | None = None) -> list[int]:+ discovery_inputs.append(inputs)return DISCOVERED_TEAM_IDS@@ -274,6 +276,7 @@ class TestBatchTraceSummarizationCoordinatorWorkflow:@pytest.mark.asyncioasync def test_sliding_window_does_not_hold_teams_behind_a_slow_team(self):child_runs.clear()+ discovery_inputs.clear()result = await _run_coordinator(BatchTraceSummarizationCoordinatorInputs(max_concurrent_teams=2))runs_by_team = {run["team_id"]: run for run in child_runs}@@ -285,6 +288,8 @@ class TestBatchTraceSummarizationCoordinatorWorkflow:windows = {run["window"] for run in child_runs}assert len(windows) == 1assert None not in next(iter(windows))+ window_start, window_end = next(iter(windows))+ assert discovery_inputs == [TeamDiscoveryInput(window_start=window_start, window_end=window_end)]@pytest.mark.asyncio@pytest.mark.parametrize(