: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): gate scheduled summarization and clustering on consent (#105028)
posthog[bot]492e887631f9
diff --git a/posthog/temporal/ai_observability/__init__.py b/posthog/temporal/ai_observability/__init__.pyindex 713b879d738e..b0498bf25972 100644--- a/posthog/temporal/ai_observability/__init__.py+++ b/posthog/temporal/ai_observability/__init__.py@@ -76,6 +76,7 @@ from posthog.temporal.ai_observability.run_trace_evaluation import (execute_trace_llm_judge_activity,)from posthog.temporal.ai_observability.shared_activities import (+ check_ai_data_processing_consent_activity,fetch_all_clustering_filters_activity,fetch_all_clustering_jobs_activity,)@@ -167,6 +168,7 @@ ACTIVITIES = [fetch_and_format_activity,summarize_and_save_activity,# Shared activities+ check_ai_data_processing_consent_activity,fetch_all_clustering_filters_activity,fetch_all_clustering_jobs_activity,# Clustering activitiesdiff --git a/posthog/temporal/ai_observability/coordinator_metrics.py b/posthog/temporal/ai_observability/coordinator_metrics.pyindex d38d9f78ce43..115431814eb4 100644--- a/posthog/temporal/ai_observability/coordinator_metrics.py+++ b/posthog/temporal/ai_observability/coordinator_metrics.py@@ -7,6 +7,13 @@ team discovery and per-team success/failure across pipeline runs.from posthog.temporal.ai_observability.metrics import get_metric_meter+def increment_consent_query_failed() -> None:+ get_metric_meter().create_counter(+ "llma_coordinator_consent_query_failed",+ "Discovery activities that returned no teams because the consent query failed",+ ).add(1)++def record_teams_discovered(count: int, pipeline: str, analysis_level: str) -> None:meter = get_metric_meter({"pipeline": pipeline, "analysis_level": analysis_level})meter.create_counter(diff --git a/posthog/temporal/ai_observability/evaluation_clustering/coordinator.py b/posthog/temporal/ai_observability/evaluation_clustering/coordinator.pyindex a6a98fc29f3c..e9a4c431e795 100644--- a/posthog/temporal/ai_observability/evaluation_clustering/coordinator.py+++ b/posthog/temporal/ai_observability/evaluation_clustering/coordinator.py@@ -46,6 +46,7 @@ with temporalio.workflow.unsafe.imports_passed_through():from posthog.temporal.ai_observability.team_discovery import (DISCOVERY_ACTIVITY_RETRY_POLICY,DISCOVERY_ACTIVITY_TIMEOUT,+ DISCOVERY_FAIL_CLOSED_PATCH_ID,GUARANTEED_TEAM_IDS,TeamDiscoveryInput,get_team_ids_for_ai_observability,@@ -99,6 +100,8 @@ async def _discover_teams_and_jobs() -> tuple[list[int], dict[int, list[JobConfiretry_policy=DISCOVERY_ACTIVITY_RETRY_POLICY,)except Exception:+ if workflow.patched(DISCOVERY_FAIL_CLOSED_PATCH_ID):+ raiselogger.warning("Team discovery failed, falling back to guaranteed teams", exc_info=True)team_ids = sorted(GUARANTEED_TEAM_IDS)diff --git a/posthog/temporal/ai_observability/shared_activities.py b/posthog/temporal/ai_observability/shared_activities.pyindex 15b4ade1d897..afce83a907d6 100644--- a/posthog/temporal/ai_observability/shared_activities.py+++ b/posthog/temporal/ai_observability/shared_activities.py@@ -6,6 +6,9 @@ from typing import Any, Literal, castfrom temporalio import activity+from posthog.dataclasses import frozen+from posthog.sync import database_sync_to_async_pool+AnalysisLevel = Literal["trace", "generation", "evaluation"]@@ -33,6 +36,33 @@ async def fetch_all_clustering_filters_activity(return await asyncio.to_thread(_fetch_filters)+def consented_team_ids(team_ids: list[int]) -> set[int]:+ """Of the given teams, the ones whose organization approved third-party AI data processing.++ The flag is nullable, and every reader treats an unset flag as not approved. A team that+ no longer exists is absent from the result, so a caller fails closed on both.+ """+ from posthog.models import Team # noqa: PLC0415 - keeps Django models off the workflow import path++ return set(+ Team.objects.filter(id__in=team_ids, organization__is_ai_data_processing_approved=True).values_list(+ "id", flat=True+ )+ )+++@frozen+class TeamAIConsentInput:+ team_id: int+++async def check_ai_data_processing_consent_activity(inputs: TeamAIConsentInput) -> bool:+ """Report whether the team's organization approved third-party AI data processing."""+ consented = await database_sync_to_async_pool(consented_team_ids)([inputs.team_id])+ return inputs.team_id in consented++@dataclassclass JobConfig:"""One clustering job's configuration, serializable over Temporal."""diff --git a/posthog/temporal/ai_observability/team_discovery.py b/posthog/temporal/ai_observability/team_discovery.pyindex a905366f494f..ddeac4e1c27c 100644--- a/posthog/temporal/ai_observability/team_discovery.py+++ b/posthog/temporal/ai_observability/team_discovery.py@@ -15,11 +15,17 @@ import asyncioimport dataclassesfrom datetime import UTC, datetime, timedelta+from django.db import InterfaceError, OperationalError+import structlogimport posthoganalyticsimport temporalio.activityfrom temporalio.common import RetryPolicy+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed+from posthog.sync import database_sync_to_async_pool+from posthog.temporal.ai_observability.coordinator_metrics import increment_consent_query_failed+from posthog.temporal.ai_observability.shared_activities import consented_team_idsfrom posthog.temporal.common.heartbeat import Heartbeaterlogger = structlog.get_logger(__name__)@@ -138,6 +144,7 @@ def get_min_traces_override(team_id: int) -> int | None:# overhead so the activity doesn't get killed before the fallback path runs.DISCOVERY_ACTIVITY_TIMEOUT = timedelta(minutes=5)DISCOVERY_ACTIVITY_RETRY_POLICY = RetryPolicy(maximum_attempts=2)+DISCOVERY_FAIL_CLOSED_PATCH_ID = "ai-observability-discovery-fail-closed-2026-09"@dataclasses.dataclass@@ -146,6 +153,16 @@ class TeamDiscoveryInput:pass+@retry(+ retry=retry_if_exception_type((InterfaceError, OperationalError)),+ stop=stop_after_attempt(3),+ wait=wait_fixed(0.1),+ reraise=True,+)+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]:@@ -153,8 +170,13 @@ async def get_team_ids_for_ai_observability(inputs: TeamDiscoveryInput | None =Discover teams for AI observability workflows.Config (guaranteed/skip/sample/lookback) is read from the feature flag payload.- Returns guaranteed allowlist teams + a random sample of other teams with AI events.- On failure, falls back to guaranteed teams only.+ Candidates are the guaranteed allowlist teams + a random sample of other teams with AI+ events. If that sampling query fails, the candidates are the guaranteed teams only.++ Every candidate then passes the third-party AI data processing consent filter, guaranteed+ teams included, so a team whose organization did not approve is never returned. The filter+ fails closed: if the consent query itself fails, this returns no teams at all rather than a+ possibly non-consenting set."""async with Heartbeater():config = await asyncio.to_thread(_get_ai_observability_workflow_config)@@ -188,20 +210,12 @@ async def get_team_ids_for_ai_observability(inputs: TeamDiscoveryInput | None =# Guaranteed teams first: the coordinator processes teams in this order and# may exhaust its run budget before reaching the tail, so allowlisted teams# must never sit behind the sampled set.- result = sorted(guaranteed - skip) + sorted(sampled)-- logger.info(- "Team discovery completed",- guaranteed_count=len(guaranteed),- skip_count=len(skip),- ai_event_teams_count=len(ai_event_teams),- remaining_count=len(remaining),- sampled_count=len(sampled),- total_count=len(result),- sample_percentage=sample_percentage,- )-- return result+ discovered = sorted(guaranteed - skip) + sorted(sampled)+ discovery_context = {+ "ai_event_teams_count": len(ai_event_teams),+ "remaining_count": len(remaining),+ "sampled_count": len(sampled),+ }except Exception:logger.warning(@@ -210,4 +224,28 @@ async def get_team_ids_for_ai_observability(inputs: TeamDiscoveryInput | None =guaranteed_count=len(guaranteed),skip_count=len(skip),)- return sorted(guaranteed - skip)+ discovered = sorted(guaranteed - skip)+ discovery_context = {}++ try:+ consented = await _consented_team_ids_with_retry(discovered)+ except Exception:+ # Fail closed: an unreadable consent flag must not let trace content reach a+ # third-party model.+ logger.exception("AI data processing consent filter failed, discovering no teams")+ increment_consent_query_failed()+ return []++ result = [team_id for team_id in discovered if team_id in consented]++ logger.info(+ "Team discovery completed",+ guaranteed_count=len(guaranteed),+ skip_count=len(skip),+ discovered_count=len(discovered),+ total_count=len(result),+ sample_percentage=sample_percentage,+ **discovery_context,+ )++ return resultdiff --git a/posthog/temporal/ai_observability/test_team_discovery.py b/posthog/temporal/ai_observability/test_team_discovery.pyindex da9a2f3f0fbe..06a8ac570fa9 100644--- a/posthog/temporal/ai_observability/test_team_discovery.py+++ b/posthog/temporal/ai_observability/test_team_discovery.py@@ -1,11 +1,22 @@import math+from collections.abc import Awaitable, Callable, Iteratorfrom contextlib import asynccontextmanager+from functools import partialimport pytest-from unittest.mock import patch+from unittest.mock import AsyncMock, MagicMock, call, patch++from django.db import InterfaceError, OperationalErrorfrom parameterized import parameterized+from posthog.sync import database_sync_to_async+from posthog.temporal.ai_observability.evaluation_clustering.coordinator import (+ AIObservabilityEvaluationClusteringCoordinatorWorkflow,+ AIObservabilityEvaluationSamplerCoordinatorWorkflow,+ ClusteringCoordinatorInputs,+ SamplerCoordinatorInputs,+)from posthog.temporal.ai_observability.team_discovery import (DEFAULT_DISCOVERY_LOOKBACK_DAYS,DEFAULT_GUARANTEED_TEAM_IDS,@@ -15,6 +26,14 @@ from posthog.temporal.ai_observability.team_discovery import (get_min_traces_override,get_team_ids_for_ai_observability,)+from posthog.temporal.ai_observability.trace_clustering.coordinator import (+ TraceClusteringCoordinatorInputs,+ TraceClusteringCoordinatorWorkflow,+)+from posthog.temporal.ai_observability.trace_summarization.coordinator import (+ BatchTraceSummarizationCoordinatorInputs,+ BatchTraceSummarizationCoordinatorWorkflow,+)@asynccontextmanager@@ -23,6 +42,7 @@ async def _noop_heartbeater(*args, **kwargs):FF_PAYLOAD_PATH = "posthog.temporal.ai_observability.team_discovery.posthoganalytics.get_feature_flag_payload"+CONSENT_QUERY_PATH = "posthog.temporal.ai_observability.team_discovery.consented_team_ids"class TestGetLlmaWorkflowConfig:@@ -157,6 +177,11 @@ class TestGetMinTracesOverride:@patch("posthog.temporal.ai_observability.team_discovery.Heartbeater", _noop_heartbeater)@pytest.mark.asyncioclass TestGetTeamIdsForAIObservability:+ @pytest.fixture(autouse=True)+ def _consent_needs_no_database(self) -> Iterator[None]:+ with patch(CONSENT_QUERY_PATH, side_effect=set):+ yield+@patch("posthog.tasks.ai_observability_usage_report.get_teams_with_ai_events")async def test_guaranteed_teams_always_included(self, mock_get_teams, _mock_ff):mock_get_teams.return_value = [9999, 8888]@@ -339,3 +364,113 @@ class TestGetTeamIdsForAIObservability:begin, end = mock_get_teams.call_args.args[0], mock_get_teams.call_args.args[1]delta_days = (end - begin).total_seconds() / 86400assert 2.99 < delta_days < 3.01+++def _create_team(name: str, approved: bool) -> int:+ from posthog.models.organization import Organization+ from posthog.models.team import Team++ organization = Organization.objects.create(name=name, is_ai_data_processing_approved=approved)+ return Team.objects.create(organization=organization, name=name).id+++@patch("posthog.temporal.ai_observability.team_discovery.Heartbeater", _noop_heartbeater)+class TestAIDataProcessingConsentGate:+ @pytest.mark.django_db(transaction=True)+ @patch("posthog.tasks.ai_observability_usage_report.get_teams_with_ai_events")+ @patch(FF_PAYLOAD_PATH)+ async def test_allowlisted_team_without_consent_is_not_discovered(+ self, mock_ff: MagicMock, mock_get_teams: MagicMock+ ) -> None:+ approved_id = await database_sync_to_async(_create_team)("Approved", True)+ unapproved_id = await database_sync_to_async(_create_team)("Unapproved", False)+ mock_ff.return_value = {+ "guaranteed_team_ids": [approved_id, unapproved_id],+ "sample_percentage": 1.0,+ }+ mock_get_teams.return_value = [unapproved_id]++ result = await get_team_ids_for_ai_observability(TeamDiscoveryInput())++ assert result == [approved_id]++ @pytest.mark.parametrize(+ "query_results,expected,attempts,failed",+ [+ pytest.param([OperationalError("Postgres unavailable"), {1}], [1], 2, False, id="reconnects"),+ pytest.param([InterfaceError("Connection closed"), {1}], [1], 2, False, id="closed_connection"),+ pytest.param([OperationalError("Postgres unavailable")] * 3, [], 3, True, id="exhausted"),+ pytest.param([RuntimeError("Unexpected query failure")], [], 1, True, id="non_retryable"),+ pytest.param([set()], [], 1, False, id="no_consent"),+ ],+ )+ @patch(CONSENT_QUERY_PATH)+ @patch("posthog.tasks.ai_observability_usage_report.get_teams_with_ai_events")+ @patch(FF_PAYLOAD_PATH, return_value=None)+ async def test_consent_query_retries_fail_closed(+ self,+ _mock_ff: MagicMock,+ mock_get_teams: MagicMock,+ mock_query: MagicMock,+ query_results: list[Exception | set[int]],+ expected: list[int],+ attempts: int,+ failed: bool,+ ) -> None:+ mock_get_teams.return_value = [9999]+ mock_query.side_effect = query_results++ with (+ patch("asyncio.sleep", new_callable=AsyncMock) as sleep,+ patch("posthog.temporal.ai_observability.coordinator_metrics.get_metric_meter") as metric_meter,+ ):+ assert await get_team_ids_for_ai_observability(TeamDiscoveryInput()) == expected++ mock_get_teams.assert_called_once()+ _mock_ff.assert_called_once()+ assert mock_query.call_args_list == [call([1, 2, 9999])] * attempts+ assert sleep.await_count == attempts - 1+ if failed:+ metric_meter.return_value.create_counter.assert_called_once_with(+ "llma_coordinator_consent_query_failed",+ "Discovery activities that returned no teams because the consent query failed",+ )+ metric_meter.return_value.create_counter.return_value.add.assert_called_once_with(1)+ else:+ metric_meter.assert_not_called()+++class TestCoordinatorConsentGate:+ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "run",+ [+ pytest.param(+ partial(BatchTraceSummarizationCoordinatorWorkflow().run, BatchTraceSummarizationCoordinatorInputs()),+ id="summarization",+ ),+ pytest.param(+ partial(TraceClusteringCoordinatorWorkflow().run, TraceClusteringCoordinatorInputs()),+ id="trace_clustering",+ ),+ pytest.param(+ partial(AIObservabilityEvaluationSamplerCoordinatorWorkflow().run, SamplerCoordinatorInputs()),+ id="evaluation_sampling",+ ),+ pytest.param(+ partial(AIObservabilityEvaluationClusteringCoordinatorWorkflow().run, ClusteringCoordinatorInputs()),+ id="evaluation_clustering",+ ),+ ],+ )+ 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.execute_activity", side_effect=RuntimeError("Discovery unavailable")),+ patch("temporalio.workflow.start_child_workflow") as start_child,+ ):+ with pytest.raises(RuntimeError, match="Discovery unavailable"):+ await run()++ start_child.assert_not_called()diff --git a/posthog/temporal/ai_observability/tests/test_shared_activities.py b/posthog/temporal/ai_observability/tests/test_shared_activities.pynew file mode 100644index 000000000000..7a2168d82769--- /dev/null+++ b/posthog/temporal/ai_observability/tests/test_shared_activities.py@@ -0,0 +1,57 @@+import asyncio+from concurrent.futures import ThreadPoolExecutor++import pytest++from django.db import connection+from django.test import override_settings++from parameterized import parameterized++from posthog.sync import database_sync_to_async+from posthog.temporal.ai_observability.shared_activities import (+ TeamAIConsentInput,+ check_ai_data_processing_consent_activity,+)+++def _create_team(approved: bool | None) -> int:+ from posthog.models.organization import Organization+ from posthog.models.team import Team++ organization = Organization.objects.create(name="Org", is_ai_data_processing_approved=approved)+ return Team.objects.create(organization=organization, name="Team").id++[email protected]_db(transaction=True)+class TestCheckAIDataProcessingConsentActivity:+ @parameterized.expand(+ [+ ("approved", True, True),+ ("null_is_not_approved", None, False),+ ("not_approved", False, False),+ ]+ )+ @pytest.mark.asyncio+ async def test_consent_flag_decides(self, _name: str, approved: bool | None, expected: bool) -> None:+ team_id = await database_sync_to_async(_create_team)(approved)++ assert await check_ai_data_processing_consent_activity(TeamAIConsentInput(team_id=team_id)) is expected++ @pytest.mark.asyncio+ async def test_missing_team_is_not_approved(self) -> None:+ assert await check_ai_data_processing_consent_activity(TeamAIConsentInput(team_id=-1)) is False++ @pytest.mark.asyncio(loop_scope="function")+ async def test_consent_recovers_after_worker_connection_closes(self) -> None:+ team_id = await database_sync_to_async(_create_team)(True)+ asyncio.get_running_loop().set_default_executor(ThreadPoolExecutor(max_workers=1))++ def disconnect() -> None:+ connection.ensure_connection()+ connection.connection.close()++ await asyncio.to_thread(disconnect)++ with override_settings(TEST=False):+ assert await check_ai_data_processing_consent_activity(TeamAIConsentInput(team_id=team_id)) is Truediff --git a/posthog/temporal/ai_observability/trace_clustering/coordinator.py b/posthog/temporal/ai_observability/trace_clustering/coordinator.pyindex 9d2fb30bb575..bc220a3563b4 100644--- a/posthog/temporal/ai_observability/trace_clustering/coordinator.py+++ b/posthog/temporal/ai_observability/trace_clustering/coordinator.py@@ -51,6 +51,7 @@ with temporalio.workflow.unsafe.imports_passed_through():from posthog.temporal.ai_observability.team_discovery import (DISCOVERY_ACTIVITY_RETRY_POLICY,DISCOVERY_ACTIVITY_TIMEOUT,+ DISCOVERY_FAIL_CLOSED_PATCH_ID,GUARANTEED_TEAM_IDS,TeamDiscoveryInput,get_team_ids_for_ai_observability,@@ -140,8 +141,6 @@ class TraceClusteringCoordinatorWorkflow(PostHogWorkflow):max_samples=inputs.max_samples,)- # Discover teams dynamically via activity, falling back to guaranteed- # teams if the activity fails (e.g. ClickHouse timeout).try:team_ids = await temporalio.workflow.execute_activity(get_team_ids_for_ai_observability,@@ -150,6 +149,8 @@ class TraceClusteringCoordinatorWorkflow(PostHogWorkflow):retry_policy=DISCOVERY_ACTIVITY_RETRY_POLICY,)except Exception:+ if temporalio.workflow.patched(DISCOVERY_FAIL_CLOSED_PATCH_ID):+ raiselogger.warning("Team discovery activity failed, falling back to guaranteed teams", exc_info=True)team_ids = sorted(GUARANTEED_TEAM_IDS)diff --git a/posthog/temporal/ai_observability/trace_summarization/README.md b/posthog/temporal/ai_observability/trace_summarization/README.mdindex 438524362da9..f9af690979d1 100644--- a/posthog/temporal/ai_observability/trace_summarization/README.md+++ b/posthog/temporal/ai_observability/trace_summarization/README.md@@ -57,7 +57,7 @@ Both activities are unified — they handle trace-level and generation-level sum### Coordinator: `llma-trace-summarization-coordinator`-Discovers teams dynamically via `get_team_ids_for_ai_observability` (guaranteed teams + a random sample of teams with AI events, configured in `team_discovery.py`).+Discovers teams dynamically via `get_team_ids_for_ai_observability` (guaranteed teams + a random sample of teams with AI events, configured in `team_discovery.py`), less the teams without AI data processing consent.**Inputs** (`BatchTraceSummarizationCoordinatorInputs`): `max_traces`, `batch_size`, `mode`, `window_minutes`, `model` - all optional with sensible defaults.@@ -124,13 +124,39 @@ temporal workflow start \> Local dev uses `development-task-queue`, production uses `general-purpose-task-queue`.+A per-team run returns an empty result if the team's organization did not approve third-party AI data processing.+See [AI data processing consent](#ai-data-processing-consent).+### Scheduled ExecutionThe coordinator runs hourly via Temporal schedule (configured in `schedule.py`). Verify at http://localhost:8233 → schedule: `llma-trace-summarization-coordinator-schedule`.### Team Discovery-Teams are discovered dynamically via `team_discovery.py`. Guaranteed teams (in `GUARANTEED_TEAM_IDS`) are always included, plus a configurable random sample of teams with AI events. Manual triggers can target any team.+Teams are discovered dynamically via `team_discovery.py`: guaranteed teams (in `GUARANTEED_TEAM_IDS`) plus a configurable random sample of teams with AI events.+Every discovered team must also pass the consent gate below, guaranteed teams included.++### AI data processing consent++A team is summarized only if its organization approved third-party AI data processing (`Organization.is_ai_data_processing_approved`).+An unset flag counts as not approved.++The rule is applied in two places:++- Team discovery drops every team without consent, so a guaranteed team is not exempt.+- The per-team workflow repeats the check and returns an empty result when consent is absent. This also gates a manual trigger and a stale allowlist entry, which both skip discovery.++Discovery retries transient consent database connection errors up to three attempts, with a 100 ms wait between attempts.+These retries reuse the candidate teams without repeating the ClickHouse discovery query.+Discovery fails closed if consent remains unreadable: it returns no teams and increments `llma_coordinator_consent_query_failed` once.+Look for this counter and the `AI data processing consent filter failed` log line when discovery returns no teams unexpectedly.+If discovery exhausts its activity retries or times out, new summarization and clustering coordinator runs fail before they dispatch any team workflows.+The old hardcoded fallback is retained only for replaying existing workflow histories.++Each consent query reads all candidate teams at once and returns only team IDs.+Each per-team summarization run checks consent once more before sampling, including manual runs and queued work.+These queries run in the database thread pool with connection cleanup; they do not block the workflow event loop or run once per trace.+Once a team run passes its entry check, it finishes without further consent checks between processing steps.## Configurationdiff --git a/posthog/temporal/ai_observability/trace_summarization/constants.py b/posthog/temporal/ai_observability/trace_summarization/constants.pyindex a68024b7af8d..e31c90a13680 100644--- a/posthog/temporal/ai_observability/trace_summarization/constants.py+++ b/posthog/temporal/ai_observability/trace_summarization/constants.py@@ -78,6 +78,12 @@ SAMPLE_HEARTBEAT_TIMEOUT = timedelta(seconds=120) # 2 minutes - sampling has lo# the workflow indefinitely when something is fundamentally broken.SAMPLE_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(seconds=1200) # 20 min total for sampling (2 attempts * 900s + backoff)+# The patch id keeps executions that started before the consent check shipped deterministic+# on replay.+CONSENT_CHECK_PATCH_ID = "llma-summarization-ai-consent-check-2026-09"+CONSENT_CHECK_START_TO_CLOSE_TIMEOUT = timedelta(seconds=30)+CONSENT_CHECK_RETRY_POLICY = RetryPolicy(maximum_attempts=3)+# Activity 1: Fetch + format + store in Redis (fast, ClickHouse-bound)FETCH_AND_FORMAT_START_TO_CLOSE_TIMEOUT = timedelta(seconds=120)FETCH_AND_FORMAT_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(diff --git a/posthog/temporal/ai_observability/trace_summarization/coordinator.py b/posthog/temporal/ai_observability/trace_summarization/coordinator.pyindex 9f0c44729f2b..0e3eff476e63 100644--- a/posthog/temporal/ai_observability/trace_summarization/coordinator.py+++ b/posthog/temporal/ai_observability/trace_summarization/coordinator.py@@ -64,6 +64,7 @@ with temporalio.workflow.unsafe.imports_passed_through():from posthog.temporal.ai_observability.team_discovery import (DISCOVERY_ACTIVITY_RETRY_POLICY,DISCOVERY_ACTIVITY_TIMEOUT,+ DISCOVERY_FAIL_CLOSED_PATCH_ID,GUARANTEED_TEAM_IDS,TeamDiscoveryInput,get_team_ids_for_ai_observability,@@ -154,8 +155,6 @@ class BatchTraceSummarizationCoordinatorWorkflow(PostHogWorkflow):window_minutes=inputs.window_minutes,)- # Discover teams dynamically via activity, falling back to guaranteed- # teams if the activity fails (e.g. ClickHouse timeout).try:team_ids = await temporalio.workflow.execute_activity(get_team_ids_for_ai_observability,@@ -164,6 +163,8 @@ class BatchTraceSummarizationCoordinatorWorkflow(PostHogWorkflow):retry_policy=DISCOVERY_ACTIVITY_RETRY_POLICY,)except Exception:+ if temporalio.workflow.patched(DISCOVERY_FAIL_CLOSED_PATCH_ID):+ raiselogger.warning("Team discovery activity failed, falling back to guaranteed teams", exc_info=True)team_ids = sorted(GUARANTEED_TEAM_IDS)diff --git a/posthog/temporal/ai_observability/trace_summarization/tests/test_workflow.py b/posthog/temporal/ai_observability/trace_summarization/tests/test_workflow.pyindex 459c892e55f2..ec349e6babd6 100644--- a/posthog/temporal/ai_observability/trace_summarization/tests/test_workflow.py+++ b/posthog/temporal/ai_observability/trace_summarization/tests/test_workflow.py@@ -1,9 +1,10 @@"""Tests for batch trace summarization workflow and sampling."""from contextlib import asynccontextmanager+from datetime import UTC, datetimeimport pytest-from unittest.mock import patch+from unittest.mock import AsyncMock, patchfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.placeholders import replace_placeholders@@ -350,6 +351,30 @@ class TestSampleItemsInWindowActivity:class TestBatchTraceSummarizationWorkflow:+ @pytest.mark.asyncio+ @pytest.mark.parametrize("consent_unavailable", [False, True], ids=["denied", "unavailable"])+ async def test_does_not_process_items_without_verified_consent(self, consent_unavailable: bool) -> None:+ consent_error = RuntimeError("Consent unavailable")+ execute_activity = AsyncMock(side_effect=consent_error if consent_unavailable else [False])+ workflow_path = "posthog.temporal.ai_observability.trace_summarization.workflow"++ with (+ patch(f"{workflow_path}.temporalio.workflow.now", return_value=datetime(2026, 1, 1, tzinfo=UTC)),+ patch(f"{workflow_path}.temporalio.workflow.patched", return_value=True),+ patch(f"{workflow_path}.temporalio.workflow.execute_activity", execute_activity),+ patch(f"{workflow_path}.increment_workflow_started"),+ patch(f"{workflow_path}.increment_workflow_finished"),+ ):+ if consent_unavailable:+ with pytest.raises(RuntimeError, match="Consent unavailable"):+ await BatchTraceSummarizationWorkflow().run(BatchSummarizationInputs(team_id=1))+ else:+ result = await BatchTraceSummarizationWorkflow().run(BatchSummarizationInputs(team_id=1))+ assert result.metrics.items_queried == 0+ assert result.metrics.summaries_generated == 0++ assert execute_activity.await_count == 1+def test_parse_inputs_minimal(self):inputs = BatchTraceSummarizationWorkflow.parse_inputs(["123"])diff --git a/posthog/temporal/ai_observability/trace_summarization/workflow.py b/posthog/temporal/ai_observability/trace_summarization/workflow.pyindex ee7b295e48ab..ac1d2e813174 100644--- a/posthog/temporal/ai_observability/trace_summarization/workflow.py+++ b/posthog/temporal/ai_observability/trace_summarization/workflow.py@@ -18,8 +18,15 @@ from typing import Anyimport structlogimport temporalio+from posthog.temporal.ai_observability.shared_activities import (+ TeamAIConsentInput,+ check_ai_data_processing_consent_activity,+)from posthog.temporal.ai_observability.trace_summarization import constantsfrom posthog.temporal.ai_observability.trace_summarization.constants import (+ CONSENT_CHECK_PATCH_ID,+ CONSENT_CHECK_RETRY_POLICY,+ CONSENT_CHECK_START_TO_CLOSE_TIMEOUT,DEFAULT_BATCH_SIZE,DEFAULT_MAX_ITEMS_PER_WINDOW,DEFAULT_MODE,@@ -184,6 +191,19 @@ class BatchTraceSummarizationWorkflow(PostHogWorkflow):increment_workflow_started(inputs.analysis_level)+ # Defence in depth: team discovery already drops teams without consent, but a stale+ # allowlist entry must not send trace content to a third-party model either.+ if temporalio.workflow.patched(CONSENT_CHECK_PATCH_ID):+ consented = await temporalio.workflow.execute_activity(+ check_ai_data_processing_consent_activity,+ TeamAIConsentInput(team_id=inputs.team_id),+ start_to_close_timeout=CONSENT_CHECK_START_TO_CLOSE_TIMEOUT,+ retry_policy=CONSENT_CHECK_RETRY_POLICY,+ )+ if not consented:+ increment_workflow_finished("skipped_no_ai_consent", inputs.analysis_level)+ return BatchSummarizationResult(batch_run_id=batch_run_id, metrics=metrics)+# Compute window dates for queries using workflow time for determinismif inputs.window_start and inputs.window_end:window_start = inputs.window_startdiff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.pyindex 376f185e13c0..7f89aa0c57ee 100644--- a/posthog/temporal/tests/ai/test_module_integrity.py+++ b/posthog/temporal/tests/ai/test_module_integrity.py@@ -235,6 +235,7 @@ class TestAIObservabilityModuleIntegrity:"sample_items_in_window_activity","fetch_and_format_activity","summarize_and_save_activity",+ "check_ai_data_processing_consent_activity","fetch_all_clustering_filters_activity","fetch_all_clustering_jobs_activity","perform_clustering_compute_activity",