: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: stop a taxonomy timeout killing every AI subscription report (#77911)
Lucas Fariac2468e6543d3
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.py b/products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.pyindex 72c20506d9af..56d30e9b4cca 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.py@@ -225,8 +225,9 @@ def sanitize_prompt(raw: str | None) -> str:def _top_event_names(team: Team, limit: int) -> list[str]:- query = TeamTaxonomyQuery(limit=limit)- response = TeamTaxonomyQueryRunner(query, team).run(+ # Unlimited on purpose: the limit bounds output rows, not the 30-day GROUP BY behind them, so it+ # saves ClickHouse nothing and only forks our cache key away from the other AI callers'.+ response = TeamTaxonomyQueryRunner(TeamTaxonomyQuery(), team).run(ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE_AND_BLOCKING_ON_MISS,)if not isinstance(response, CachedTeamTaxonomyQueryResponse):@@ -234,8 +235,10 @@ def _top_event_names(team: Team, limit: int) -> list[str]:# Event names are user-controlled (project tokens are public — anyone can fire# events with arbitrary names). Sanitize so an attacker can't seed the LLM# context with prompt-injection payloads via crafted event names.- sanitized = (sanitize_user_text(item.event, EVENT_NAME_MAX_LENGTH) for item in response.results)- return [name for name in sanitized if name]+ # `count > 0` drops the runner's count=0 WELL_KNOWN_EVENT_NAMES padding: under a "Top events"+ # heading it would claim events fired that never did. Dormant ones are `_no_data_event_names`.+ sanitized = (sanitize_user_text(item.event, EVENT_NAME_MAX_LENGTH) for item in response.results if item.count > 0)+ return [name for name in sanitized if name][:limit]def _no_data_event_names(team: Team, limit: int) -> list[str]:@@ -435,7 +438,15 @@ def _event_property_names(team: Team, events: list[str], per_event_limit: int) -def build_context_blob(team: Team, window: ReportWindow, relevant_events: Sequence[str] = ()) -> str:- event_names = _top_event_names(team, EVENT_NAMES_SAMPLE_LIMIT)+ # Only a hint — the planner's actual event names arrive via `relevant_events` from the Postgres+ # taxonomy — so a ClickHouse timeout on the 30-day scan behind it degrades rather than costing the+ # whole report, as `_llm_selected_events` already does. None means "unknown", never "none".+ event_names: list[str] | None+ try:+ event_names = _top_event_names(team, EVENT_NAMES_SAMPLE_LIMIT)+ except Exception:+ logger.warning("ai_subscription.top_event_names_failed", team_id=team.pk, exc_info=True)+ event_names = None# Team / org names are also user-controlled and end up in the LLM context, so# apply the same sanitization as event names.@@ -458,14 +469,19 @@ def build_context_blob(team: Team, window: ReportWindow, relevant_events: Sequenf"- Previous-period start (for period-over-period comparisons only, project timezone): "f"{window.compare_start_literal}",]- if event_names:+ if event_names is None:+ # State, not an instruction to the model: this blob is also quoted verbatim into the synthesis+ # prompt, so an imperative here can end up paraphrased at the reader. Distinct from the empty+ # case because the projects whose scan times out are the ones with the most data.+ lines.append("- Top events: (unavailable this run)")+ elif event_names:lines.append("- Top events: " + ", ".join(event_names))else:lines.append("- Top events: (none recorded yet)")if relevant_events:props_by_event = _event_property_names(team, list(relevant_events), EVENT_PROPERTIES_PER_EVENT_LIMIT)- top_set = set(event_names)+ top_set = set(event_names or ())seen: set[str] = set()matched: list[tuple[str, str]] = [] # (raw, clean), deduped on the sanitized namefor raw in relevant_events:diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_spec_generator.py b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_spec_generator.pyindex 226a4672bb30..49341411389c 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_spec_generator.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_spec_generator.py@@ -7,6 +7,9 @@ from unittest.mock import MagicMock, patchfrom parameterized import parameterized+from posthog.schema import CachedTeamTaxonomyQueryResponse, TeamTaxonomyItem, TeamTaxonomyQuery++from posthog.exceptions import ClickHouseQueryTimeOutfrom posthog.models import EventDefinition, EventProperty, PropertyDefinition, Teamfrom products.exports.backend.models.subscription import Subscription@@ -31,6 +34,7 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.spec_genera_pinned_event_names,_recent_event_names,_select_relevant_events,+ _top_event_names,build_context_blob,build_frozen_prompt,compute_report_window,@@ -731,6 +735,101 @@ class TestContextBlob(APIBaseTest):assert "Events matching your request" not in blob+ @parameterized.expand(+ [+ ("clickhouse_timeout", ClickHouseQueryTimeOut()),+ ("unexpected_error", Exception("boom")),+ ]+ )+ @patch(f"{_SG}.get_group_types_for_project", return_value=[])+ def test_builds_blob_when_top_events_lookup_fails(self, _name: str, exc: Exception, _mock_groups: object) -> None:+ # The top-events list is only a hint; on a high-volume project its 30-day scan can exceed+ # ClickHouse's execution limit. Losing the hint must not cost the whole report, so the blob+ # still has to carry the parts the planner cannot work without.+ window = _window(7)++ with patch(f"{_SG}._top_event_names", side_effect=exc):+ blob = build_context_blob(self.team, window)++ assert f"Analysis window start (inclusive, project timezone): {window.start_literal}" in blob+ assert "{{date_range}}" in blob+ # A failed lookup must not read as an empty project: the projects whose scan times out are the+ # ones with the most data, so "none recorded yet" here would invite a "nothing happened" report.+ assert "none recorded yet" not in blob+ assert "- Top events: (unavailable this run)" in blob+ # The blob is quoted verbatim into the synthesis prompt, so this line has to stay a statement of+ # state — an imperative aimed at the planner can reach the reader as report prose. (The blob does+ # carry imperatives elsewhere, e.g. the date-placeholder rule, hence asserting on this line only.)+ (top_events_line,) = [line for line in blob.splitlines() if line.startswith("- Top events:")]+ assert "do NOT" not in top_events_line++ @patch(f"{_SG}.get_group_types_for_project", return_value=[])+ def test_still_injects_relevant_event_schema_when_top_events_lookup_fails(self, _mock_groups: object) -> None:+ # The relevant-events section cross-references the top-events list to avoid repeating names, so+ # the failure path has to stay compatible with it rather than blowing up downstream.+ EventDefinition.objects.create(team=self.team, name="export created")+ EventProperty.objects.create(team=self.team, event="export created", property="duration_ms")++ with patch(f"{_SG}._top_event_names", side_effect=ClickHouseQueryTimeOut()):+ blob = build_context_blob(self.team, _window(7), relevant_events=["export created"])++ assert "export created" in blob+ assert "duration_ms" in blob++ @patch(f"{_SG}.get_group_types_for_project", return_value=[])+ @patch(f"{_SG}._top_event_names", return_value=[])+ def test_still_reports_a_genuinely_empty_project_as_empty(self, _mock_top: object, _mock_groups: object) -> None:+ # The counterpart to the failure case: a project that really has no events must keep saying so,+ # or the two states become indistinguishable to the planner.+ blob = build_context_blob(self.team, _window(7))++ assert "- Top events: (none recorded yet)" in blob+++class TestTopEventNames(APIBaseTest):+ def _run_with_results(self, results: list[TeamTaxonomyItem], limit: int) -> tuple[list[str], TeamTaxonomyQuery]:+ response = CachedTeamTaxonomyQueryResponse(+ cache_key="test_key",+ is_cached=True,+ last_refresh=datetime(2026, 1, 1, tzinfo=UTC),+ next_allowed_client_refresh=datetime(2026, 1, 1, 1, 0, tzinfo=UTC),+ timezone="UTC",+ results=results,+ )+ with patch(f"{_SG}.TeamTaxonomyQueryRunner") as mock_runner:+ mock_runner.return_value.run.return_value = response+ names = _top_event_names(self.team, limit)+ return names, mock_runner.call_args.args[0]++ def test_asks_for_no_limit_so_the_cache_key_is_shared(self) -> None:+ # `limit` is hashed into the cache key but applied to the query's output rows, so passing one+ # buys no ClickHouse saving and partitions us off the entry other AI callers keep warm —+ # turning every run into a recompute of a scan that may not finish.+ _, query = self._run_with_results([TeamTaxonomyItem(event="$pageview", count=1)], limit=20)++ assert query.limit is None++ def test_returns_at_most_limit_names_ranked_by_volume(self) -> None:+ results = [TeamTaxonomyItem(event=f"event_{i}", count=100 - i) for i in range(5)]++ names, _ = self._run_with_results(results, limit=3)++ assert names == ["event_0", "event_1", "event_2"]++ def test_excludes_zero_count_padding_events(self) -> None:+ # The runner appends WELL_KNOWN_EVENT_NAMES at count=0 when there are no more real rows. Under a+ # "Top events" heading those read as events that fired, so a project with fewer real events than+ # the limit would be handed fabricated ones — the same misinformation the None/empty split avoids.+ results = [+ TeamTaxonomyItem(event="export created", count=42),+ TeamTaxonomyItem(event="$pageleave", count=0),+ TeamTaxonomyItem(event="$identify", count=0),+ ]++ names, _ = self._run_with_results(results, limit=20)++ assert names == ["export created"]+class TestGenerateQueryPlanSubstitution(APIBaseTest):"""Test the substitution *behaviour* — that the planner actually receives the prompt and context