Skip to content

: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.

feat(subscriptions): freeze the AI report query plan for deterministic runs (#66819)

Vasco de Krijgerbb593893fd18
diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.py
index a5b44603ccd0..b1492c79f9ec 100644
--- a/ee/api/test/test_subscription.py
+++ b/ee/api/test/test_subscription.py
@@ -2471,6 +2471,51 @@ class TestAISubscriptionAPI(APILicensedTest):
)
assert response.status_code == expected_status, response.json()
+ @parameterized.expand(
+ [
+ ("prompt_change_clears_plan", {"prompt": "A completely different question about retention?"}, False),
+ ("title_change_keeps_plan", {"title": "Renamed"}, True),
+ ]
+ )
+ def test_editing_prompt_invalidates_frozen_query_plan(
+ self, mock_is_cloud, mock_flag, mock_sync, _name, body, plan_survives
+ ):
+ self._mock_temporal(mock_sync)
+ frozen = {
+ "version": 1,
+ "plan": {
+ "overall_intent": "i",
+ "steps": [
+ {
+ "description": "d",
+ "query_type": "hogql",
+ "hogql": "SELECT count() FROM events WHERE {{date_range}}",
+ }
+ ],
+ },
+ }
+ sub_id = self._create_subscription_for("ai_prompt")
+ Subscription.objects.filter(id=sub_id).update(ai_query_plan=frozen)
+
+ response = self.client.patch(f"/api/projects/{self.team.id}/subscriptions/{sub_id}", body)
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+ assert Subscription.objects.get(id=sub_id).ai_query_plan == (frozen if plan_survives else None)
+
+ def test_orm_prompt_edit_also_invalidates_frozen_query_plan(self, mock_is_cloud, mock_flag, mock_sync):
+ # The invalidation lives on Subscription.save() (not the serializer), so ORM-path edits —
+ # management commands, future code — can't leave a plan answering the old prompt.
+ self._mock_temporal(mock_sync)
+ sub_id = self._create_subscription_for("ai_prompt")
+ Subscription.objects.filter(id=sub_id).update(ai_query_plan={"version": 1, "plan": {}})
+
+ sub = Subscription.objects.get(id=sub_id)
+ sub.prompt = "A different question entirely?"
+ sub.save()
+
+ sub.refresh_from_db()
+ assert sub.ai_query_plan is None
+
def _enable_access_control_feature(self) -> None:
self.organization.available_product_features = [
{"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
diff --git a/products/exports/backend/migrations/0006_subscription_ai_query_plan.py b/products/exports/backend/migrations/0006_subscription_ai_query_plan.py
new file mode 100644
index 000000000000..860a2f329707
--- /dev/null
+++ b/products/exports/backend/migrations/0006_subscription_ai_query_plan.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.14 on 2026-06-29 17:04
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("exports", "0005_subscriptiondelivery_posthog_subdel_sub_fin"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="subscription",
+ name="ai_query_plan",
+ field=models.JSONField(blank=True, default=None, null=True),
+ ),
+ ]
diff --git a/products/exports/backend/migrations/max_migration.txt b/products/exports/backend/migrations/max_migration.txt
index 6678367b5e9b..b1dd778b87b3 100644
--- a/products/exports/backend/migrations/max_migration.txt
+++ b/products/exports/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0005_subscriptiondelivery_posthog_subdel_sub_fin
+0006_subscription_ai_query_plan
diff --git a/products/exports/backend/models/subscription.py b/products/exports/backend/models/subscription.py
index 078315c8047f..99bc713b94e8 100644
--- a/products/exports/backend/models/subscription.py
+++ b/products/exports/backend/models/subscription.py
@@ -169,6 +169,10 @@ class Subscription(ModelActivityMixin, models.Model):
prompt = models.TextField(null=True, blank=True)
+ # Frozen by the first successful delivery so later runs reuse the same HogQL deterministically
+ # instead of re-running the planner LLM; cleared on prompt change (see save()). Shape is versioned —
+ # see report_pipeline._plan_to_freeze.
+ ai_query_plan = models.JSONField(null=True, blank=True, default=None)
# Source of truth for the shape: ee.api.subscription.AIPromptConfigSerializer (writes) and
# normalize_ai_window below (reads).
ai_prompt_config = models.JSONField(default=dict, blank=True)
@@ -221,6 +225,8 @@ class Subscription(ModelActivityMixin, models.Model):
# a new instance with OTHER fields deferred, causing infinite recursion.
if not (self.get_deferred_fields() & self.RRULE_FIELDS):
self._rrule = self.rrule
+ if "prompt" not in self.get_deferred_fields():
+ self._initial_prompt = self.prompt
def save(self, *args, **kwargs) -> None:
# Only if the schedule has changed do we update the next delivery date
@@ -229,7 +235,14 @@ class Subscription(ModelActivityMixin, models.Model):
self.set_next_delivery_date()
if "update_fields" in kwargs:
kwargs["update_fields"].append("next_delivery_date")
+ # A changed prompt invalidates the frozen AI query plan at the model level (same pattern as
+ # next_delivery_date above), so ORM-path edits can't leave a plan answering the old prompt.
+ if self.id and self.prompt != getattr(self, "_initial_prompt", self.prompt) and self.ai_query_plan is not None:
+ self.ai_query_plan = None
+ if kwargs.get("update_fields") is not None:
+ kwargs["update_fields"] = [*kwargs["update_fields"], "ai_query_plan"]
super().save(*args, **kwargs)
+ self._initial_prompt = self.prompt
@classmethod
def derive_resource_type(cls, insight_id: int | None, dashboard_id: int | None, prompt: str | None) -> str:
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py
index d03717461744..9a356d3b8286 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py
@@ -140,9 +140,12 @@ def _last_scheduled_report_cutoff(subscription: Subscription) -> datetime | None
return None
-def _resolve_subscription_context(subscription: Subscription) -> tuple[Team, User | None, ReportWindow]:
+def _resolve_subscription_context(
+ subscription: Subscription,
+) -> tuple[Team, User | None, ReportWindow, dict | None]:
# team/created_by are FK relations and the last-delivery lookup hits the DB; resolving the window
- # here keeps all ORM access (and the timezone math) off the event loop in one sync hop.
+ # here keeps all ORM access (and the timezone math) off the event loop in one sync hop. The frozen
+ # plan (if any) is read here too so the generation path stays free of ORM access.
team = subscription.team
# Day-based window modes don't anchor to delivery history — skip the lookup for them.
last_scheduled_cutoff = (
@@ -159,25 +162,51 @@ def _resolve_subscription_context(subscription: Subscription) -> tuple[Team, Use
start_days_ago=subscription.ai_window_start_days_ago,
end_days_ago=subscription.ai_window_end_days_ago,
)
- return team, subscription.created_by, window
+ return team, subscription.created_by, window, subscription.ai_query_plan
+
+
+def _persist_ai_query_plan(subscription_id: int, team_id: int, prompt: str | None, plan: dict) -> None:
+ # Targeted update, never a full save() — that would re-emit the activity-log/analytics signals.
+ # Filtering on the planning-time prompt closes a race: a prompt edited mid-generation clears the
+ # plan via Subscription.save(), and this no-ops instead of re-freezing a plan for the old prompt.
+ Subscription.objects.filter(id=subscription_id, team_id=team_id, prompt=prompt).update(ai_query_plan=plan)
async def build_ai_subscription_report(subscription: Subscription) -> AiReportResult:
- team, user, window = await database_sync_to_async(_resolve_subscription_context, thread_sensitive=False)(
- subscription
- )
+ team, user, window, ai_query_plan = await database_sync_to_async(
+ _resolve_subscription_context, thread_sensitive=False
+ )(subscription)
# created_by is FK SET_NULL; the pipeline requires a non-None user
if user is None:
raise PromptRejectedError("AI subscription has no creator (created_by deleted); cannot deliver.")
- return await generate_ai_report(
+ result = await generate_ai_report(
team=team,
user=user,
prompt=subscription.prompt,
window=window,
+ ai_query_plan=ai_query_plan,
trace_correlation_id=subscription.id,
)
+ if result.plan_to_persist is not None:
+ try:
+ await database_sync_to_async(_persist_ai_query_plan, thread_sensitive=False)(
+ subscription.id, subscription.team_id, subscription.prompt, result.plan_to_persist
+ )
+ except Exception as exc:
+ # The frozen plan is an optimization — losing this write must not abort the delivery (the
+ # report is already generated; failing here would burn the LLM run and retry from scratch).
+ logger.warning(
+ "ai_report.query_plan_persist_failed",
+ subscription_id=subscription.id,
+ team_id=subscription.team_id,
+ exc_info=True,
+ )
+ capture_exception(exc, {"subscription_id": subscription.id, "feature": "ai_subscription"})
+
+ return result
+
def _build_feedback_url(subscription_url: str, delivery_id: uuid.UUID, feedback: str, source: str) -> str:
# Lands on the authenticated subscription page; the frontend reads these exact params
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/prompts.py b/products/exports/backend/temporal/subscriptions/ai_subscription/prompts.py
index c8d1fda2e23a..c4968c023f74 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/prompts.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/prompts.py
@@ -107,18 +107,22 @@ Output rules:
When context lists "Events matching your request", prefer those exact event names — they were
selected for this prompt. For an event's properties, use only the names listed under its
"`<event>` properties" line (access as `properties.<name>`); do not invent property names.
-- The analysis window is fixed and provided in <project_context> as "Analysis window start" and
- "Analysis window end" (concrete timestamps in the project timezone). Filter EVERY query on exactly
- that half-open range — copy the provided literals into a filter of the form
- `timestamp >= toDateTime('<start>') AND timestamp < toDateTime('<end>')`. Do NOT compute the window
- yourself with `now()` / `now() - INTERVAL …` / `today()` — those drift between runs and force fragile
- timezone math. Use the provided literals verbatim, even when the prompt names a relative period
- ("today", "this week"); the bounds already encode it. For sub-windows inside the range (e.g. day-over-day
- within the window), bucket with `toStartOfDay(timestamp)` etc., but keep the outer filter on the literals.
- The one exception is period-over-period growth ("vs last week/yesterday"), which may read back to the
- "Previous-period start" literal `<compare_start>` — see the growth reference pattern below.
+- The analysis window is fixed, but you must NOT write its dates yourself. Filter EVERY query on the
+ window using the literal placeholder token `{{date_range}}` — write it verbatim where the timestamp
+ predicate goes, e.g. `WHERE {{date_range}}` or `WHERE event = '$pageview' AND {{date_range}}`. The
+ system substitutes the concrete half-open range at run time, so the plan stays reusable as the window
+ advances. Do NOT write `timestamp >= toDateTime('…')`, `now()`, `now() - INTERVAL …`, or `today()` for
+ the window yourself. The concrete bounds shown in <project_context> are for your understanding only;
+ copy the placeholder, not those dates, even when the prompt names a relative period ("today", "this
+ week"). For sub-windows inside the range (e.g. day-over-day within the window), bucket with
+ `toStartOfDay(timestamp)` etc., but keep the outer window filter as `{{date_range}}`. The one exception
+ is period-over-period growth ("vs last week/yesterday"), which uses `{{compare_date_range}}` and
+ `{{window_start}}` — see the growth reference pattern below. Boundary tokens `{{window_start}}` /
+ `{{window_end}}` substitute to bare `toDateTime('…')` literals where a pattern needs a single bound.
- Each step's `description` must briefly explain *why* that query is relevant to the prompt.
- Keep queries cheap: prefer aggregation over raw selects; cap with LIMIT 50; avoid wildcards on large tables.
+- Format each query for readability: each clause (SELECT, FROM, WHERE, GROUP BY, ORDER BY, LIMIT) on
+ its own line, one selected column per line. Queries are shown to users verbatim.
HogQL syntax constraints — write queries that PARSE first. Each step's `hogql` is a SELECT statement,
ideally flat. A single level of subquery in the FROM clause is allowed (and is the right tool for
@@ -137,8 +141,8 @@ are common LLM mistakes that HogQL rejects:
null-safe join keys with "Cannot determine join keys", so a JOIN will fail at execution time.
(Person, session, and group/account data IS still available without a JOIN — see "Joined data
available" below.)
-- Window filter: use the provided literals — `timestamp >= toDateTime('<start>') AND timestamp <
- toDateTime('<end>')`. Never `now()` / `now() - INTERVAL …` / `today()` for the window.
+- Window filter: write the placeholder token `{{date_range}}` verbatim where the window predicate goes.
+ Never write `timestamp >= toDateTime('…')`, `now()`, `now() - INTERVAL …`, or `today()` for the window.
- Time bucketing (for sub-windows WITHIN the range): `toStartOfHour(timestamp)`,
`toStartOfDay(timestamp)`, `toStartOfWeek(timestamp)`.
- Conditional aggregation: `countIf(cond)`, `uniqIf(field, cond)`, `sumIf(field, cond)`,
@@ -147,14 +151,14 @@ are common LLM mistakes that HogQL rejects:
`arraySlice(arraySort(…), 1, N)` for many. Never `ROW_NUMBER() OVER (PARTITION BY …)`.
- String literals use single quotes; identifiers are unquoted.
-Reference patterns (use as templates). `<start>` and `<end>` below stand for the exact
-"Analysis window start" / "Analysis window end" literals from <project_context> — substitute them
-verbatim; never write `now()` or `now() - INTERVAL …`:
+Reference patterns (use as templates). Write the placeholder tokens verbatim; the system substitutes
+the concrete bounds at run time. Never write `toDateTime('…')` window bounds, `now()`, or
+`now() - INTERVAL …` yourself:
Top events across the window:
SELECT event, count() AS count, uniq(distinct_id) AS users
FROM events
- WHERE timestamp >= toDateTime('<start>') AND timestamp < toDateTime('<end>')
+ WHERE {{date_range}}
GROUP BY event
ORDER BY count DESC
LIMIT 50
@@ -162,14 +166,14 @@ Top events across the window:
Daily time series for a single event:
SELECT toStartOfDay(timestamp) AS day, count() AS count, uniq(distinct_id) AS users
FROM events
- WHERE event = '$pageview' AND timestamp >= toDateTime('<start>') AND timestamp < toDateTime('<end>')
+ WHERE event = '$pageview' AND {{date_range}}
GROUP BY day
ORDER BY day
Hourly distribution to spot spikes:
SELECT toStartOfHour(timestamp) AS hour, count() AS count
FROM events
- WHERE event = '$pageview' AND timestamp >= toDateTime('<start>') AND timestamp < toDateTime('<end>')
+ WHERE event = '$pageview' AND {{date_range}}
GROUP BY hour
ORDER BY hour
@@ -177,16 +181,16 @@ Period-over-period growth (the window vs the equal-length period immediately bef
regular send that's roughly the prior cadence period (about last week for a weekly report, yesterday
for a daily one), but it tracks the window's ACTUAL length — a short re-fire window compares two
short slices, so describe the result as "vs the previous period", not as an exact "week over week".
-This is the ONLY case that reads data before `<start>`: filter the wider `[<compare_start>, <end>)`
-range and split at `<start>` with conditional aggregation. `<compare_start>` is the "Previous-period
-start" literal from <project_context>. Still never `now()`:
+This is the ONLY case that reads data before the window: filter the wider previous+current range with
+the `{{compare_date_range}}` placeholder and split at `{{window_start}}` with conditional aggregation.
+Still never `now()`:
SELECT
event,
- countIf(timestamp >= toDateTime('<start>')) AS current,
- countIf(timestamp < toDateTime('<start>')) AS previous,
+ countIf(timestamp >= {{window_start}}) AS current,
+ countIf(timestamp < {{window_start}}) AS previous,
(current - previous) / nullIf(previous, 0) AS growth_rate
FROM events
- WHERE timestamp >= toDateTime('<compare_start>') AND timestamp < toDateTime('<end>')
+ WHERE {{compare_date_range}}
GROUP BY event
HAVING previous > 0 OR current > 0
ORDER BY growth_rate DESC
@@ -201,14 +205,14 @@ Top AND bottom events — a single `ORDER BY … DESC LIMIT n` only returns the
with an ASC tail to read both the most- and least-active events regardless of how many events exist:
(SELECT event, count() AS event_count, uniq(distinct_id) AS users
FROM events
- WHERE timestamp >= toDateTime('<start>') AND timestamp < toDateTime('<end>')
+ WHERE {{date_range}}
GROUP BY event
ORDER BY event_count DESC
LIMIT 25)
UNION ALL
(SELECT event, count() AS event_count, uniq(distinct_id) AS users
FROM events
- WHERE timestamp >= toDateTime('<start>') AND timestamp < toDateTime('<end>')
+ WHERE {{date_range}}
GROUP BY event
ORDER BY event_count ASC
LIMIT 25)
@@ -229,7 +233,7 @@ Breakdown by a person property (USE the dotted path, NOT a JOIN):
count() AS event_count,
uniq(distinct_id) AS users
FROM events
- WHERE timestamp >= toDateTime('<start>') AND timestamp < toDateTime('<end>')
+ WHERE {{date_range}}
GROUP BY plan
ORDER BY event_count DESC
LIMIT 50
@@ -250,7 +254,7 @@ window — never approximate it with a flat `countIf`, and never use a JOIN or w
WHERE event = 'Dashboard created'
GROUP BY distinct_id
)
- WHERE first_seen >= toDateTime('<start>') AND first_seen < toDateTime('<end>')
+ WHERE first_seen >= {{window_start}} AND first_seen < {{window_end}}
GROUP BY template
ORDER BY first_time_users DESC
LIMIT 50
@@ -331,10 +335,10 @@ rewrite MUST follow the same HogQL syntax constraints used by the planner:
UNNEST, or ARRAY JOIN on subqueries.
- No JOINs of any kind, including self-joins on `event`. Use conditional aggregation instead
(ClickHouse rejects HogQL's null-safe join keys).
-- Time window: PRESERVE the original query's `timestamp >= toDateTime('…') AND timestamp <
- toDateTime('…')` bounds verbatim — those are the report's fixed analysis window. Do NOT introduce
- `now()` / `now() - INTERVAL …` / `today()`; if the original already uses them, keep its existing
- literal bounds rather than inventing new ones.
+- Time window: PRESERVE the original query's window tokens (`{{date_range}}`,
+ `{{compare_date_range}}`, `{{window_start}}`, `{{window_end}}`) or literal `toDateTime('…')` bounds
+ verbatim — those are the report's fixed analysis window. Do NOT introduce `now()` /
+ `now() - INTERVAL …` / `today()`, and do NOT resolve a placeholder into dates yourself.
- Time bucketing: `toStartOfHour/Day/Week(timestamp)`.
- String literals use single quotes; identifiers are unquoted.
- Keep it cheap: LIMIT 50.
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py b/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py
index 0cf9034ea254..ac4c2fc77a0c 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py
@@ -30,14 +30,19 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.schemas imp
MAX_QUERY_PLAN_STEPS,
EnrichedPromptSpec,
HogQLFix,
+ QueryPlan,
QueryPlanStep,
)
from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import (
+ AI_QUERY_PLAN_VERSION,
DEFAULT_PLANNER_MODEL,
DEFAULT_SYNTHESIS_MODEL,
+ WINDOW_PLACEHOLDERS,
PromptRejectedError,
ReportWindow,
+ StoredPlanInvalidError,
build_enriched_prompt,
+ build_frozen_prompt,
)
from ee.hogai.context.insight.query_executor import AssistantQueryExecutor
@@ -146,6 +151,8 @@ class AiReportResult:
diagnostics: tuple[QueryStepDiagnostic, ...]
# The window's end as a UTC ISO instant — persisted so the next run can anchor exactly here.
window_end_utc: str
+ # Set only when the run planned from scratch; the caller freezes it onto the subscription.
+ plan_to_persist: Optional[dict] = None
async def generate_ai_report(
@@ -154,6 +161,7 @@ async def generate_ai_report(
user: Optional[User],
prompt: Optional[str],
window: ReportWindow,
+ ai_query_plan: Optional[dict] = None,
trace_correlation_id: Optional[Union[int, str]] = None,
) -> AiReportResult:
if user is None:
@@ -170,8 +178,28 @@ async def generate_ai_report(
properties={"window_start": window.start_literal, "window_end": window.end_literal},
) as slo:
try:
- spec = await _plan(team=team, user=user, prompt=prompt, window=window, trace_id=trace_correlation_id)
- rendered_results, failed_count, diagnostics = await _execute_plan(spec, team, user, trace_correlation_id)
+ # A stored plan that no longer validates self-heals by re-planning live.
+ if ai_query_plan is not None:
+ try:
+ spec = await _spec_from_frozen_plan(
+ team=team, prompt=prompt, window=window, ai_query_plan=ai_query_plan
+ )
+ freshly_planned = False
+ except StoredPlanInvalidError as exc:
+ logger.warning(
+ "ai_report.frozen_plan_invalid_replanning", trace_correlation_id=trace_correlation_id
+ )
+ capture_exception(exc, {"trace_correlation_id": trace_correlation_id, "feature": "ai_subscription"})
+ spec = await _plan(
+ team=team, user=user, prompt=prompt, window=window, trace_id=trace_correlation_id
+ )
+ freshly_planned = True
+ else:
+ spec = await _plan(team=team, user=user, prompt=prompt, window=window, trace_id=trace_correlation_id)
+ freshly_planned = True
+ rendered_results, failed_count, diagnostics = await _execute_plan(
+ spec, team, user, window, trace_correlation_id
+ )
report = await _synthesize(spec, rendered_results, team, user, trace_correlation_id)
except PromptRejectedError:
# A rejected prompt is the input guard doing its job, not a service failure — keep it out of
@@ -200,11 +228,43 @@ async def generate_ai_report(
# deterministic notice (not left to the synthesis LLM) so the recipient gets a clear signal
# instead of a confident-looking but empty report.
report = _all_queries_failed_notice(total_steps) + report
+ plan_to_persist = _plan_to_freeze(
+ spec.plan,
+ freshly_planned=freshly_planned,
+ failed_count=failed_count,
+ total_steps=total_steps,
+ trace_correlation_id=trace_correlation_id,
+ )
return AiReportResult(
markdown=report,
diagnostics=tuple(diagnostics),
window_end_utc=window.end.astimezone(UTC).isoformat(),
+ plan_to_persist=plan_to_persist,
+ )
+
+
+def _plan_to_freeze(
+ plan: QueryPlan,
+ *,
+ freshly_planned: bool,
+ failed_count: int,
+ total_steps: int,
+ trace_correlation_id: Optional[Union[int, str]],
+) -> Optional[dict]:
+ # Never freeze a plan the next delivery is better off re-planning: an all-failed plan would replay
+ # broken HogQL forever, and a step without any window placeholder would scan unbounded every run.
+ if not freshly_planned:
+ return None
+ if total_steps and failed_count >= total_steps:
+ return None
+ if not all(any(token in step.hogql for token in WINDOW_PLACEHOLDERS) for step in plan.steps):
+ logger.warning(
+ "ai_report.plan_missing_window_placeholder_not_frozen",
+ trace_correlation_id=trace_correlation_id,
)
+ return None
+ # Versioned envelope: bumping AI_QUERY_PLAN_VERSION lazily re-plans every frozen subscription.
+ return {"version": AI_QUERY_PLAN_VERSION, "plan": plan.model_dump()}
async def _plan(
@@ -224,14 +284,31 @@ async def _plan(
raise AiReportStageError(ReportStage.PLANNER, exc) from exc
+async def _spec_from_frozen_plan(
+ *, team: Team, prompt: Optional[str], window: ReportWindow, ai_query_plan: dict
+) -> EnrichedPromptSpec:
+ try:
+ return await database_sync_to_async(build_frozen_prompt, thread_sensitive=False)(
+ team=team,
+ prompt=prompt,
+ window=window,
+ ai_query_plan=ai_query_plan,
+ )
+ except (PromptRejectedError, StoredPlanInvalidError):
+ raise
+ except Exception as exc:
+ raise AiReportStageError(ReportStage.PLANNER, exc) from exc
+
+
async def _execute_plan(
spec: EnrichedPromptSpec,
team: Team,
user: User,
+ window: ReportWindow,
trace_correlation_id: Optional[Union[int, str]],
) -> tuple[list[str], int, list[QueryStepDiagnostic]]:
try:
- return await _run_steps(spec, team, user, trace_correlation_id)
+ return await _run_steps(spec, team, user, window, trace_correlation_id)
except Exception as exc:
# per-step failures degrade to placeholders in run_step; this catches orchestration failure
raise AiReportStageError(ReportStage.QUERY, exc) from exc
@@ -297,6 +374,7 @@ async def _run_steps(
spec: EnrichedPromptSpec,
team: Team,
user: User,
+ window: ReportWindow,
trace_correlation_id: Optional[Union[int, str]],
) -> tuple[list[str], int, list[QueryStepDiagnostic]]:
executor = AssistantQueryExecutor(team, datetime.now(tz=UTC), user=user)
@@ -311,14 +389,18 @@ async def _run_steps(
)
async def run_step(step: QueryPlanStep) -> tuple[str, QueryStepDiagnostic]:
+ # `current_hogql` keeps the window-agnostic form (the `{{date_range}}` placeholder) so it round-trips
+ # through the fix LLM unchanged; the run's fresh bounds are substituted into `executable_hogql` on
+ # every attempt. The diagnostic records the executed SQL (placeholder resolved) for debugging.
current_hogql = step.hogql
last_exc: Optional[BaseException] = None
# planner output — strip framing markers so it can't break the <query_results> envelope
safe_description = strip_llm_framing_markers(step.description, max_len=500)
for attempt in range(_MAX_QUERY_FIX_RETRIES + 1):
+ executable_hogql = window.render_window_filter(current_hogql)
try:
- query = AssistantHogQLQuery(query=current_hogql)
+ query = AssistantHogQLQuery(query=executable_hogql)
formatted, _ = await asyncio.wait_for(
executor.arun_and_format_query(query),
timeout=_HOGQL_STEP_TIMEOUT_SECONDS,
@@ -327,7 +409,7 @@ async def _run_steps(
safe_formatted = strip_llm_framing_markers(formatted, per_step_cap)
return (
f"### {safe_description}\n\n{safe_formatted}",
- QueryStepDiagnostic(description=safe_description, hogql=current_hogql, ok=True, error_type=None),
+ QueryStepDiagnostic(description=safe_description, hogql=executable_hogql, ok=True, error_type=None),
)
except Exception as exc:
last_exc = exc
@@ -371,7 +453,7 @@ async def _run_steps(
f"### {safe_description}\n\n_{QUERY_FAILED_PREFIX} ({type_name}) — metric not computed, not empty data._",
QueryStepDiagnostic(
description=safe_description,
- hogql=current_hogql,
+ hogql=window.render_window_filter(current_hogql),
ok=False,
error_type=type_name,
human_readable_error=_safe_error_message(last_exc) if last_exc is not None else None,
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.py b/products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.py
index dab6f7d937ae..ac0193ca81df 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.py
@@ -7,6 +7,7 @@ from typing import Optional, Union
from django.db.models import F, Q
import structlog
+from pydantic import ValidationError
from posthog.schema import CachedTeamTaxonomyQueryResponse, SubscriptionAIPromptMaxLength, TeamTaxonomyQuery
@@ -72,6 +73,23 @@ MAX_PINNED_EVENTS = 25
# or 'event name'. The capture groups are non-greedy so adjacent quotes don't merge into one token.
_QUOTED_TOKEN_RE = re.compile(r"`([^`]+)`|\"([^\"]+)\"|'([^']+)'")
+# Placeholder tokens the planner writes instead of concrete dates, so frozen HogQL stays
+# window-agnostic; ReportWindow.render_window_filter substitutes the run's fresh bounds.
+DATE_RANGE_PLACEHOLDER = "{{date_range}}"
+COMPARE_DATE_RANGE_PLACEHOLDER = "{{compare_date_range}}"
+WINDOW_START_PLACEHOLDER = "{{window_start}}"
+WINDOW_END_PLACEHOLDER = "{{window_end}}"
+WINDOW_PLACEHOLDERS = (
+ DATE_RANGE_PLACEHOLDER,
+ COMPARE_DATE_RANGE_PLACEHOLDER,
+ WINDOW_START_PLACEHOLDER,
+ WINDOW_END_PLACEHOLDER,
+)
+# Bumping invalidates every frozen plan (they lazily re-plan on next delivery), so prompt/harness
+# improvements reach existing subscriptions instead of only new ones.
+AI_QUERY_PLAN_VERSION = 1
+
+
DEFAULT_PLANNER_MODEL = "gpt-4.1"
DEFAULT_SYNTHESIS_MODEL = "gpt-4.1"
_PLANNER_LLM_TIMEOUT_SECONDS = 90.0
@@ -82,6 +100,14 @@ class PromptRejectedError(ValueError):
pass
+class StoredPlanInvalidError(Exception):
+ """A persisted query plan no longer validates (e.g. the `QueryPlan` schema changed since it was
+ frozen). The caller should self-heal by re-planning live rather than failing the delivery — unlike
+ `PromptRejectedError` (bad user input), this is recoverable and must not auto-disable the sub."""
+
+ pass
+
+
@dataclass(frozen=True)
class ReportWindow:
"""Half-open `[start, end)` analysis bounds for a report run, tz-aware in the team timezone.
@@ -105,12 +131,32 @@ class ReportWindow:
@property
def compare_start(self) -> datetime:
+ # The equal-length period immediately before the window, for period-over-period queries.
return self.start - (self.end - self.start)
@property
def compare_start_literal(self) -> str:
return self.compare_start.strftime("%Y-%m-%d %H:%M:%S")
+ @property
+ def window_filter_sql(self) -> str:
+ return f"timestamp >= toDateTime('{self.start_literal}') AND timestamp < toDateTime('{self.end_literal}')"
+
+ @property
+ def compare_filter_sql(self) -> str:
+ return (
+ f"timestamp >= toDateTime('{self.compare_start_literal}') AND timestamp < toDateTime('{self.end_literal}')"
+ )
+
+ def render_window_filter(self, hogql: str) -> str:
+ # str.replace is non-recursive, and the substituted SQL contains no tokens, so nothing re-expands.
+ return (
+ hogql.replace(DATE_RANGE_PLACEHOLDER, self.window_filter_sql)
+ .replace(COMPARE_DATE_RANGE_PLACEHOLDER, self.compare_filter_sql)
+ .replace(WINDOW_START_PLACEHOLDER, f"toDateTime('{self.start_literal}')")
+ .replace(WINDOW_END_PLACEHOLDER, f"toDateTime('{self.end_literal}')")
+ )
+
def _in_tz(dt: datetime, tz: tzinfo) -> datetime:
"""Normalise to `tz`. Naive inputs are assumed UTC (Django stores tz-aware UTC datetimes, but
@@ -396,17 +442,19 @@ def build_context_blob(team: Team, window: ReportWindow, relevant_events: Sequen
team_name = sanitize_user_text(team.name, EVENT_NAME_MAX_LENGTH) or "(unnamed)"
org_name = sanitize_user_text(team.organization.name, EVENT_NAME_MAX_LENGTH) or "(unnamed)"
- # Exact, code-computed bounds in the project timezone — the planner filters on these literals
- # instead of writing its own `now() - INTERVAL`, so there's no timezone math in HogQL and the
- # window is gap-free run-to-run. Half-open: include `start`, exclude `end`.
+ # The planner must NOT write its own date bounds — it emits the `{{date_range}}` placeholder and the
+ # executor substitutes the run's code-computed window. That keeps a frozen plan window-agnostic (the
+ # window advances every run) and keeps timezone math out of HogQL. The concrete bounds are still
+ # shown for context (so the planner understands the period the prompt refers to), but as
+ # informational lines the planner copies the PLACEHOLDER, not the literals, into its filter.
lines = [
f"- Project: {team_name}",
f"- Organization: {org_name}",
f"- Project timezone: {team.timezone}",
f"- Analysis window start (inclusive, project timezone): {window.start_literal}",
f"- Analysis window end (exclusive, project timezone): {window.end_literal}",
- f"- Filter timestamps with: timestamp >= toDateTime('{window.start_literal}') "
- f"AND timestamp < toDateTime('{window.end_literal}')",
+ f"- Filter timestamps with the placeholder token (verbatim, do NOT substitute the dates yourself): "
+ f"{DATE_RANGE_PLACEHOLDER}",
f"- Previous-period start (for period-over-period comparisons only, project timezone): "
f"{window.compare_start_literal}",
]
@@ -514,3 +562,27 @@ def build_enriched_prompt(
trace_correlation_id=trace_correlation_id,
)
return EnrichedPromptSpec(cleaned_prompt=cleaned, context_blob=context_blob, plan=plan)
+
+
+def build_frozen_prompt(
+ *,
+ team: Team,
+ prompt: Optional[str],
+ window: ReportWindow,
+ ai_query_plan: dict,
+) -> EnrichedPromptSpec:
+ """Rebuild the spec from a persisted plan without either LLM pass — the deterministic reuse path.
+
+ Any invalid stored plan (stale version or bad shape) raises `StoredPlanInvalidError` so the caller
+ re-plans live: a plan-schema or prompt-harness change must invalidate frozen plans, never brick
+ the subscription.
+ """
+ cleaned = sanitize_prompt(prompt)
+ if ai_query_plan.get("version") != AI_QUERY_PLAN_VERSION:
+ raise StoredPlanInvalidError("Stored query plan version is stale.")
+ try:
+ plan = QueryPlan.model_validate(ai_query_plan.get("plan"))
+ except ValidationError as exc:
+ raise StoredPlanInvalidError("Stored query plan is malformed.") from exc
+ context_blob = build_context_blob(team, window)
+ return EnrichedPromptSpec(cleaned_prompt=cleaned, context_blob=context_blob, plan=plan)
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.py b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.py
index 3f9b4242665a..5cb6cf7c4807 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.py
@@ -3,7 +3,9 @@ from datetime import UTC, datetime, timedelta
import pytest
from posthog.test.base import APIBaseTest
-from unittest.mock import MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from parameterized import parameterized
from posthog.helpers.slack_scopes import REQUIRED_SLACK_SCOPES
@@ -12,14 +14,20 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.delivery im
SLACK_MRKDWN_SECTION_LIMIT,
_build_ai_slack_message,
_last_scheduled_report_cutoff,
+ _persist_ai_query_plan,
_split_text_into_chunks,
+ build_ai_subscription_report,
render_ai_email_html,
send_email_ai_subscription_report,
)
+from products.exports.backend.temporal.subscriptions.ai_subscription.report_pipeline import AiReportResult
+from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import ReportWindow
from products.exports.backend.temporal.subscriptions.types import AI_REPORT_WINDOW_END_KEY, SubscriptionTriggerType
from ee.tasks.subscriptions.slack_subscriptions import SlackMessageData
+_DELIVERY = "products.exports.backend.temporal.subscriptions.ai_subscription.delivery"
+
_PARA = "a" * (SLACK_MRKDWN_SECTION_LIMIT - 100)
_DELIVERY_ID = uuid.UUID("12345678-1234-5678-1234-567812345678")
_SUBSCRIPTION_URL = "https://app.posthog.com/project/1/subscriptions/2"
@@ -284,6 +292,33 @@ class TestFeedbackFooter:
assert context[f"feedback_{feedback}_url"] == _feedback_url(feedback, "email")
+class TestPersistAiQueryPlanRaceGuard(APIBaseTest):
+ @parameterized.expand(
+ [
+ # The write is conditional on the planning-time prompt: an edit that landed mid-generation
+ # (clearing the plan via save()) must not be overwritten with a plan for the old prompt.
+ ("prompt_unchanged_persists", "original prompt?", True),
+ ("prompt_changed_noops", "edited mid-generation?", False),
+ ]
+ )
+ def test_persist_is_conditional_on_planning_prompt(self, _name: str, current_prompt: str, written: bool) -> None:
+ sub = Subscription.objects.create(
+ team=self.team,
+ prompt=current_prompt,
+ target_type="email",
+ target_value="[email protected]",
+ frequency="weekly",
+ interval=1,
+ start_date=datetime(2026, 1, 1, tzinfo=UTC),
+ )
+ plan = {"version": 1, "plan": {}}
+
+ _persist_ai_query_plan(sub.id, self.team.id, "original prompt?", plan)
+
+ sub.refresh_from_db()
+ assert sub.ai_query_plan == (plan if written else None)
+
+
class TestLastSuccessfulDeliveryAnchor(APIBaseTest):
def _delivery(
self, trigger_type: str, status: str, finished_at: datetime | None, snapshot: dict | None = None
@@ -361,3 +396,93 @@ class TestLastSuccessfulDeliveryAnchor(APIBaseTest):
)
assert _last_scheduled_report_cutoff(self.subscription) is None
+
+
+class TestFreezePlanPersistence:
+ """build_ai_subscription_report freezes a freshly-generated plan and skips persistence on reuse.
+ These guard the freeze contract without touching the DB — the persist write itself is a one-line
+ queryset .update() exercised by the integration/activity suites."""
+
+ def _subscription(self, ai_query_plan: dict | None) -> MagicMock:
+ sub = MagicMock()
+ sub.id = 42
+ sub.team_id = 7
+ sub.prompt = "how are exports doing?"
+ sub.ai_query_plan = ai_query_plan
+ return sub
+
+ def _context(self, sub: MagicMock) -> tuple[MagicMock, MagicMock, ReportWindow, dict | None]:
+ end = datetime(2026, 6, 29, 16, 0, tzinfo=UTC)
+ window = ReportWindow(start=end - timedelta(days=1), end=end)
+ return MagicMock(), MagicMock(), window, sub.ai_query_plan
+
+ async def test_first_run_persists_freshly_generated_plan(self) -> None:
+ sub = self._subscription(ai_query_plan=None)
+ fresh_plan = {
+ "overall_intent": "i",
+ "steps": [{"description": "d", "query_type": "hogql", "hogql": "SELECT 1"}],
+ }
+ with (
+ patch(f"{_DELIVERY}._resolve_subscription_context", return_value=self._context(sub)),
+ patch(
+ f"{_DELIVERY}.generate_ai_report",
+ new=AsyncMock(
+ return_value=AiReportResult(
+ markdown="# R",
+ diagnostics=(),
+ window_end_utc="2026-06-29T16:00:00+00:00",
+ plan_to_persist=fresh_plan,
+ )
+ ),
+ ),
+ patch(f"{_DELIVERY}._persist_ai_query_plan") as mock_persist,
+ ):
+ await build_ai_subscription_report(sub)
+
+ # The plan generated on the first delivery is frozen onto the (id, team_id)-scoped subscription.
+ mock_persist.assert_called_once_with(sub.id, sub.team_id, sub.prompt, fresh_plan)
+
+ async def test_persist_failure_does_not_abort_the_delivery(self) -> None:
+ # The report is already generated when the freeze write runs; a transient DB error must not
+ # fail the delivery (which would discard the report and burn a full LLM re-run on retry).
+ sub = self._subscription(ai_query_plan=None)
+ result = AiReportResult(
+ markdown="# R",
+ diagnostics=(),
+ window_end_utc="2026-06-29T16:00:00+00:00",
+ plan_to_persist={"version": 1, "plan": {}},
+ )
+ with (
+ patch(f"{_DELIVERY}._resolve_subscription_context", return_value=self._context(sub)),
+ patch(f"{_DELIVERY}.generate_ai_report", new=AsyncMock(return_value=result)),
+ patch(f"{_DELIVERY}._persist_ai_query_plan", side_effect=Exception("db blip")),
+ patch(f"{_DELIVERY}.capture_exception") as mock_capture,
+ ):
+ returned = await build_ai_subscription_report(sub)
+
+ assert returned is result
+ mock_capture.assert_called_once()
+
+ async def test_reused_run_does_not_persist(self) -> None:
+ frozen = {"overall_intent": "i", "steps": [{"description": "d", "query_type": "hogql", "hogql": "SELECT 1"}]}
+ sub = self._subscription(ai_query_plan=frozen)
+ with (
+ patch(f"{_DELIVERY}._resolve_subscription_context", return_value=self._context(sub)) as mock_ctx,
+ patch(
+ f"{_DELIVERY}.generate_ai_report",
+ new=AsyncMock(
+ return_value=AiReportResult(
+ markdown="# R", diagnostics=(), window_end_utc="2026-06-29T16:00:00+00:00", plan_to_persist=None
+ )
+ ),
+ ) as mock_gen,
+ patch(f"{_DELIVERY}._persist_ai_query_plan") as mock_persist,
+ ):
+ await build_ai_subscription_report(sub)
+
+ # Reuse path returns plan_to_persist=None, so there's no write; the frozen plan is forwarded
+ # to generation so it can skip the planner.
+ mock_persist.assert_not_called()
+ assert mock_gen.await_args is not None
+ assert mock_gen.await_args.kwargs["ai_query_plan"] == frozen
+ mock_ctx.assert_called_once()
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline.py b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline.py
index c59af03e333b..5b24371e8ff1 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline.py
@@ -24,8 +24,10 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.schemas imp
QueryPlanStep,
)
from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import (
+ AI_QUERY_PLAN_VERSION,
PromptRejectedError,
ReportWindow,
+ StoredPlanInvalidError,
)
_RP = "products.exports.backend.temporal.subscriptions.ai_subscription.report_pipeline"
@@ -39,6 +41,14 @@ def _test_window() -> ReportWindow:
return ReportWindow(start=_WINDOW_END - timedelta(days=1), end=_WINDOW_END)
+_ALL_FAILED_RUN = (
+ ["### s0\n\n_Query failed to run (ExposedHogQLError)_"],
+ 1,
+ [QueryStepDiagnostic("s0", "SELECT bad", False, "ExposedHogQLError")],
+)
+_OK_RUN = (["### s\n\nok"], 0, [QueryStepDiagnostic("s", "SELECT count() FROM events", True, None)])
+
+
def _spec(steps: int = 1) -> EnrichedPromptSpec:
return EnrichedPromptSpec(
cleaned_prompt="p",
@@ -50,6 +60,17 @@ def _spec(steps: int = 1) -> EnrichedPromptSpec:
)
+def _spec_with_window_placeholder() -> EnrichedPromptSpec:
+ return EnrichedPromptSpec(
+ cleaned_prompt="p",
+ context_blob="c",
+ plan=QueryPlan(
+ overall_intent="i",
+ steps=[QueryPlanStep(description="s0", hogql="SELECT count() FROM events WHERE {{date_range}}")],
+ ),
+ )
+
+
def _slo_completed(capture_mock: MagicMock) -> dict:
for call in capture_mock.call_args_list:
if call.kwargs.get("event") == "slo_operation_completed":
@@ -204,7 +225,7 @@ async def test_request_hogql_fix_returns_none_on_wrong_type(mock_chat: MagicMock
@patch(f"{_RP}.AssistantQueryExecutor")
async def test_run_steps_non_retryable_error_degrades_to_placeholder(mock_executor_cls: MagicMock) -> None:
mock_executor_cls.return_value.arun_and_format_query = AsyncMock(side_effect=RuntimeError("boom"))
- rendered, failed, diagnostics = await _run_steps(_spec(steps=1), MagicMock(), MagicMock(), None)
+ rendered, failed, diagnostics = await _run_steps(_spec(steps=1), MagicMock(), MagicMock(), _test_window(), None)
assert failed == 1
assert "Query failed to run" in rendered[0]
assert diagnostics[0].ok is False
@@ -223,7 +244,7 @@ async def test_run_steps_forwards_resolution_error_message_to_fix(
side_effect=[ResolutionError("Unable to resolve field 'operaton'"), ("formatted table", None)]
)
mock_fix.return_value = "SELECT fixed"
- await _run_steps(_spec(steps=1), MagicMock(), MagicMock(), None)
+ await _run_steps(_spec(steps=1), MagicMock(), MagicMock(), _test_window(), None)
assert mock_fix.await_args is not None
assert mock_fix.await_args.kwargs["error_message"] == "Unable to resolve field 'operaton'"
@@ -261,7 +282,7 @@ async def test_run_steps_retries_then_succeeds(mock_executor_cls: MagicMock, moc
side_effect=[ExposedHogQLError("bad query"), ("formatted table", None)]
)
mock_fix.return_value = "SELECT fixed"
- rendered, failed, diagnostics = await _run_steps(_spec(steps=1), MagicMock(), MagicMock(), None)
+ rendered, failed, diagnostics = await _run_steps(_spec(steps=1), MagicMock(), MagicMock(), _test_window(), None)
assert failed == 0
assert "formatted table" in rendered[0]
mock_fix.assert_awaited_once()
@@ -279,7 +300,7 @@ async def test_run_steps_breaks_early_when_fix_returns_same_query(
# degrade rather than burn the retry budget on an identical query.
mock_executor_cls.return_value.arun_and_format_query = AsyncMock(side_effect=ExposedHogQLError("bad query"))
mock_fix.return_value = "SELECT 1" # identical to QueryPlanStep.hogql in _spec()
- rendered, failed, diagnostics = await _run_steps(_spec(steps=1), MagicMock(), MagicMock(), None)
+ rendered, failed, diagnostics = await _run_steps(_spec(steps=1), MagicMock(), MagicMock(), _test_window(), None)
assert failed == 1
assert "Query failed to run" in rendered[0]
# Executor ran exactly once (no rerun of the identical fixed query); the fix was requested once.
@@ -312,7 +333,7 @@ async def test_run_steps_bounds_concurrent_query_execution(mock_executor_cls: Ma
mock_executor_cls.return_value.arun_and_format_query = AsyncMock(side_effect=_track)
- await _run_steps(_spec(steps=_MAX_CONCURRENT_STEPS * 2), MagicMock(), MagicMock(), None)
+ await _run_steps(_spec(steps=_MAX_CONCURRENT_STEPS * 2), MagicMock(), MagicMock(), _test_window(), None)
assert max_concurrent == _MAX_CONCURRENT_STEPS
@@ -347,3 +368,145 @@ def _wrap(
)
def test_safe_error_message_only_surfaces_query_structure_errors(exc, expected):
assert _safe_error_message(exc) == expected
+
+
+def _frozen_plan() -> dict:
+ return {
+ "version": AI_QUERY_PLAN_VERSION,
+ "plan": QueryPlan(
+ overall_intent="count events",
+ steps=[QueryPlanStep(description="counts", hogql="SELECT count() FROM events WHERE {{date_range}}")],
+ ).model_dump(),
+ }
+
+
+@patch(_SLO_CAPTURE)
+@patch(f"{_RP}.MaxChatOpenAI")
+@patch(f"{_RP}._run_steps", new_callable=AsyncMock)
+@patch(f"{_RP}.build_frozen_prompt")
+@patch(f"{_RP}.build_enriched_prompt")
+async def test_frozen_plan_reused_skips_planner_and_event_selection(
+ mock_bep: MagicMock, mock_frozen: MagicMock, mock_run: AsyncMock, mock_chat: MagicMock, _mock_capture: MagicMock
+) -> None:
+ # The determinism guarantee: when a plan is frozen, the run reconstructs the spec from it and runs
+ # NEITHER LLM pass the live path uses — build_enriched_prompt wraps both the planner and the
+ # event-selection model, so asserting it's never called proves both are skipped.
+ mock_frozen.return_value = _spec(steps=1)
+ mock_run.return_value = (["### s0\n\nok"], 0, [QueryStepDiagnostic("s0", "SELECT 1", True, None)])
+ mock_chat.return_value.invoke.return_value = MagicMock(content="# Report")
+
+ result = await generate_ai_report(
+ team=MagicMock(), user=MagicMock(), prompt="x", window=_test_window(), ai_query_plan=_frozen_plan()
+ )
+
+ mock_bep.assert_not_called() # planner + event-selection LLMs never run on a frozen sub
+ mock_frozen.assert_called_once()
+ # Nothing new to freeze on a reused run — the caller must not re-persist the same plan.
+ assert result.plan_to_persist is None
+
+
+@patch(_SLO_CAPTURE)
+@patch(f"{_RP}.MaxChatOpenAI")
+@patch(f"{_RP}._run_steps", new_callable=AsyncMock)
+@patch(f"{_RP}.build_enriched_prompt")
+async def test_unfrozen_run_returns_plan_to_persist(
+ mock_bep: MagicMock, mock_run: AsyncMock, mock_chat: MagicMock, _mock_capture: MagicMock
+) -> None:
+ # First run (no frozen plan): the freshly-planned QueryPlan is returned for the caller to persist,
+ # so the next delivery is deterministic. The shape must equal QueryPlan.model_dump() — that exact
+ # dict is what build_frozen_prompt validates back on reuse, so this guards the persist↔reuse contract.
+ spec = _spec_with_window_placeholder()
+ mock_bep.return_value = spec
+ mock_run.return_value = (["### s0\n\nok"], 0, [QueryStepDiagnostic("s0", "SELECT 1", True, None)])
+ mock_chat.return_value.invoke.return_value = MagicMock(content="# Report")
+
+ result = await generate_ai_report(team=MagicMock(), user=MagicMock(), prompt="x", window=_test_window())
+
+ assert result.plan_to_persist == {"version": AI_QUERY_PLAN_VERSION, "plan": spec.plan.model_dump()}
+
+
+@patch(f"{_RP}.AssistantQueryExecutor")
+async def test_run_steps_substitutes_fresh_window_into_placeholder_sql(mock_executor_cls: MagicMock) -> None:
+ # The frozen HogQL keeps the {{date_range}} placeholder; the executor substitutes THIS run's bounds.
+ # Two runs of the same frozen step at different `now` must execute different window literals (so the
+ # window advances) while the rest of the SQL is byte-identical (so the metric structure is frozen).
+ captured: list[str] = []
+
+ async def _capture(query: object) -> tuple[str, None]:
+ captured.append(query.query) # type: ignore[attr-defined]
+ return ("formatted", None)
+
+ mock_executor_cls.return_value.arun_and_format_query = AsyncMock(side_effect=_capture)
+ spec = EnrichedPromptSpec(
+ cleaned_prompt="p",
+ context_blob="c",
+ plan=QueryPlan(
+ overall_intent="i",
+ steps=[QueryPlanStep(description="s", hogql="SELECT count() FROM events WHERE {{date_range}}")],
+ ),
+ )
+ early = ReportWindow(start=_WINDOW_END - timedelta(days=1), end=_WINDOW_END)
+ later = ReportWindow(start=_WINDOW_END, end=_WINDOW_END + timedelta(days=1))
+
+ await _run_steps(spec, MagicMock(), MagicMock(), early, None)
+ await _run_steps(spec, MagicMock(), MagicMock(), later, None)
+
+ assert "{{date_range}}" not in captured[0] # placeholder fully resolved before execution
+ assert captured[0] != captured[1] # window advanced run-to-run
+ # Same structure: only the substituted bounds differ. Stripping the window predicate makes them equal.
+ skeleton_0 = captured[0].replace(early.window_filter_sql, "")
+ skeleton_1 = captured[1].replace(later.window_filter_sql, "")
+ assert skeleton_0 == skeleton_1
+
+
+ "spec,run_result",
+ [
+ # All steps failed: freezing would replay a broken plan every delivery instead of re-planning.
+ pytest.param(_spec_with_window_placeholder(), _ALL_FAILED_RUN, id="all_failed"),
+ # No window placeholder: freezing would cement an unbounded, window-less scan forever.
+ pytest.param(_spec(steps=1), _OK_RUN, id="missing_window_placeholder"),
+ ],
+)
+@patch(_SLO_CAPTURE)
+@patch(f"{_RP}.MaxChatOpenAI")
+@patch(f"{_RP}._run_steps", new_callable=AsyncMock)
+@patch(f"{_RP}.build_enriched_prompt")
+async def test_unfreezable_plans_are_not_frozen(
+ mock_bep: MagicMock,
+ mock_run: AsyncMock,
+ mock_chat: MagicMock,
+ _mock_capture: MagicMock,
+ spec: EnrichedPromptSpec,
+ run_result: tuple,
+) -> None:
+ mock_bep.return_value = spec
+ mock_run.return_value = run_result
+ mock_chat.return_value.invoke.return_value = MagicMock(content="# Report")
+
+ result = await generate_ai_report(team=MagicMock(), user=MagicMock(), prompt="x", window=_test_window())
+
+ assert result.plan_to_persist is None
+
+
+@patch(_SLO_CAPTURE)
+@patch(f"{_RP}.MaxChatOpenAI")
+@patch(f"{_RP}._run_steps", new_callable=AsyncMock)
+@patch(f"{_RP}.build_frozen_prompt", side_effect=StoredPlanInvalidError("malformed"))
+@patch(f"{_RP}.build_enriched_prompt")
+async def test_invalid_stored_plan_self_heals_by_replanning(
+ mock_bep: MagicMock, _mock_frozen: MagicMock, mock_run: AsyncMock, mock_chat: MagicMock, _mock_capture: MagicMock
+) -> None:
+ # A stored plan that no longer validates (e.g. QueryPlan schema changed) must re-plan live, not fail
+ # the delivery — otherwise a schema change would auto-disable every frozen subscription.
+ mock_bep.return_value = _spec_with_window_placeholder()
+ mock_run.return_value = (["### s0\n\nok"], 0, [QueryStepDiagnostic("s0", "SELECT 1", True, None)])
+ mock_chat.return_value.invoke.return_value = MagicMock(content="# Report")
+
+ result = await generate_ai_report(
+ team=MagicMock(), user=MagicMock(), prompt="x", window=_test_window(), ai_query_plan={"bad": "plan"}
+ )
+
+ mock_bep.assert_called_once() # self-healed by re-planning live
+ assert result.markdown == "# Report"
+ assert result.plan_to_persist is not None # the fresh re-plan is frozen for next time
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.py
index 73d10deecb74..3297912dd161 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
@@ -16,11 +16,13 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.schemas imp
RelevantEvents,
)
from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import (
+ AI_QUERY_PLAN_VERSION,
MAX_PINNED_EVENTS,
PROMPT_MAX_LENGTH,
RELEVANT_EVENTS_LIMIT,
PromptRejectedError,
ReportWindow,
+ StoredPlanInvalidError,
_event_property_names,
_extract_quoted_event_tokens,
_group_type_labels,
@@ -30,6 +32,7 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.spec_genera
_recent_event_names,
_select_relevant_events,
build_context_blob,
+ build_frozen_prompt,
compute_report_window,
generate_query_plan,
sanitize_prompt,
@@ -619,9 +622,12 @@ class TestComputeReportWindow:
class TestContextBlob(APIBaseTest):
@patch(f"{_SG}.get_group_types_for_project", return_value=[])
@patch(f"{_SG}._top_event_names", return_value=[])
- def test_states_explicit_window_bounds_in_project_timezone(self, _mock_top: object, _mock_groups: object) -> None:
- # The window-text regression: the blob must hand the planner concrete `[start, end)` literals
- # (so it never writes `now() - INTERVAL`), not the old "last N day(s)" relative phrasing.
+ def test_states_window_bounds_and_placeholder_in_project_timezone(
+ self, _mock_top: object, _mock_groups: object
+ ) -> None:
+ # The blob hands the planner the concrete `[start, end)` bounds for context, but instructs it to
+ # filter via the `{{date_range}}` placeholder (the executor substitutes the real window at run
+ # time) — never literal dates or the old "last N day(s)" relative phrasing.
self.team.timezone = "Australia/Sydney"
self.team.save()
window = compute_report_window(
@@ -635,12 +641,10 @@ class TestContextBlob(APIBaseTest):
assert f"Analysis window start (inclusive, project timezone): {window.start_literal}" in blob
assert f"Analysis window end (exclusive, project timezone): {window.end_literal}" in blob
- assert (
- f"timestamp >= toDateTime('{window.start_literal}') AND timestamp < toDateTime('{window.end_literal}')"
- in blob
- )
- # The prior-period anchor for period-over-period growth is injected as its own literal, so the
- # planner never reaches for `now() - INTERVAL` to build a "vs last week" baseline.
+ # The filter instruction names the placeholder, not the literal bounds — so a frozen plan stays
+ # window-agnostic and the dates never get baked into the planner's HogQL.
+ assert "{{date_range}}" in blob
+ assert f"toDateTime('{window.start_literal}')" not in blob
assert (
f"Previous-period start (for period-over-period comparisons only, project timezone): "
f"{window.compare_start_literal}" in blob
@@ -739,3 +743,58 @@ class TestGenerateQueryPlanSubstitution(APIBaseTest):
with pytest.raises(PromptRejectedError, match="malformed"):
generate_query_plan(cleaned_prompt="p", context_blob="c", team=self.team, user=self.user)
+
+
+class TestBuildFrozenPrompt(APIBaseTest):
+ """The deterministic reuse path: reconstruct the spec from a persisted plan with NO LLM calls."""
+
+ def _stored_plan(self) -> dict:
+ return {
+ "version": AI_QUERY_PLAN_VERSION,
+ "plan": QueryPlan(
+ overall_intent="count events",
+ steps=[QueryPlanStep(description="counts", hogql="SELECT count() FROM events WHERE {{date_range}}")],
+ ).model_dump(),
+ }
+
+ @patch(f"{_SG}.MaxChatOpenAI")
+ @patch(f"{_SG}._select_relevant_events")
+ @patch(f"{_SG}.get_group_types_for_project", return_value=[])
+ @patch(f"{_SG}._top_event_names", return_value=[])
+ def test_reconstructs_plan_without_calling_any_llm(
+ self, _mock_top: object, _mock_groups: object, mock_select: MagicMock, mock_chat: MagicMock
+ ) -> None:
+ stored = self._stored_plan()
+
+ spec = build_frozen_prompt(
+ team=self.team, prompt="how are exports doing?", window=_window(7), ai_query_plan=stored
+ )
+
+ # Neither the event-selection model nor the planner runs on the frozen path...
+ mock_select.assert_not_called()
+ mock_chat.assert_not_called()
+ # ...and the plan round-trips byte-for-byte (persist shape == reuse shape), HogQL placeholder intact.
+ assert spec.plan.model_dump() == stored["plan"]
+ assert "{{date_range}}" in spec.plan.steps[0].hogql
+
+ @parameterized.expand(
+ [
+ # A corrupted plan and a stale schema version both raise StoredPlanInvalidError, NOT
+ # PromptRejectedError — the caller self-heals by re-planning live, so neither a QueryPlan
+ # schema change nor an AI_QUERY_PLAN_VERSION bump can brick a frozen subscription.
+ (
+ "malformed_plan",
+ {"version": AI_QUERY_PLAN_VERSION, "plan": {"overall_intent": "i", "steps": []}},
+ "malformed",
+ ),
+ ("stale_version", {"version": AI_QUERY_PLAN_VERSION - 1, "plan": {}}, "stale"),
+ ("pre_versioning_shape", {"overall_intent": "i", "steps": []}, "stale"),
+ ]
+ )
+ @patch(f"{_SG}.get_group_types_for_project", return_value=[])
+ @patch(f"{_SG}._top_event_names", return_value=[])
+ def test_invalid_stored_plan_raises_recoverable_error(
+ self, _name: str, stored: dict, match: str, _mock_top: object, _mock_groups: object
+ ) -> None:
+ with pytest.raises(StoredPlanInvalidError, match=match):
+ build_frozen_prompt(team=self.team, prompt="p", window=_window(7), ai_query_plan=stored)