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.

fix(subscriptions): send invented date placeholders in ai reports to the fixer (#121561)

Vasco de Krijger0589fa248054
diff --git a/products/subscriptions/backend/temporal/ai_subscription/prompts.py b/products/subscriptions/backend/temporal/ai_subscription/prompts.py
index 9a2de834acdf..045e35897336 100644
--- a/products/subscriptions/backend/temporal/ai_subscription/prompts.py
+++ b/products/subscriptions/backend/temporal/ai_subscription/prompts.py
@@ -211,8 +211,9 @@ Output rules:
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.
+ `{{window_start}}` — see the growth reference pattern below. Boundary tokens `{{window_start}}`,
+ `{{window_end}}` and `{{compare_window_start}}` (the start of the comparison period) 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.
- 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.
@@ -490,9 +491,12 @@ rewrite MUST follow the same HogQL syntax constraints used by the planner:
`uniqIf($group_2, cond)`). A bare `group_<index>` is only valid as `group_<index>.properties.<name>`;
used as a scalar it does not resolve; replace it with `$group_<index>`. The same `$`-prefixed form
applies to person/session keys only via their documented paths, so do not add `$` elsewhere.
-- 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()` /
+- Time window: PRESERVE the original query's window tokens or literal `toDateTime('…')` bounds
+ verbatim — those are the report's fixed analysis window. `{{date_range}}` and `{{compare_date_range}}`
+ are whole time filters (`timestamp >= … AND timestamp < …`); `{{window_start}}`, `{{window_end}}` and
+ `{{compare_window_start}}` are single timestamps. `{{compare_date_range}}` covers the previous and the
+ current period together; for the previous period alone, use
+ `timestamp >= {{compare_window_start}} AND timestamp < {{window_start}}`. Do NOT introduce `now()` /
`now() - INTERVAL …` / `today()`, and do NOT resolve a placeholder into dates yourself.
- The normal result ceiling is `LIMIT 250`. If the error specifically indicates memory pressure,
excessive result size, or a timeout, simplify or preaggregate the query and lower the final `LIMIT`
diff --git a/products/subscriptions/backend/temporal/ai_subscription/report_pipeline.py b/products/subscriptions/backend/temporal/ai_subscription/report_pipeline.py
index 6885b23ab519..99c2122edc5c 100644
--- a/products/subscriptions/backend/temporal/ai_subscription/report_pipeline.py
+++ b/products/subscriptions/backend/temporal/ai_subscription/report_pipeline.py
@@ -13,7 +13,7 @@ from openai.lib._pydantic import to_strict_json_schema
from posthog.schema import AssistantHogQLQuery
-from posthog.hogql.errors import ExposedHogQLError, InternalHogQLError
+from posthog.hogql.errors import ExposedHogQLError, InternalHogQLError, QueryError
from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
@@ -58,15 +58,21 @@ from products.subscriptions.backend.temporal.ai_subscription.schemas import (
)
from products.subscriptions.backend.temporal.ai_subscription.spec_generator import (
AI_QUERY_PLAN_VERSION,
+ COMPARE_DATE_RANGE_PLACEHOLDER,
+ COMPARE_WINDOW_START_PLACEHOLDER,
DEFAULT_PLANNER_MODEL,
DEFAULT_SYNTHESIS_MODEL,
+ WINDOW_BOUND_PLACEHOLDERS,
+ WINDOW_FILTER_PLACEHOLDERS,
WINDOW_PLACEHOLDERS,
+ WINDOW_START_PLACEHOLDER,
ReportWindow,
StoredPlanInvalidError,
build_enriched_prompt,
build_frozen_prompt,
get_ai_query_plan_status,
resolve_ai_query_plan_status,
+ window_token_problems,
)
from products.subscriptions.backend.temporal.types import safe_query_error_details
@@ -122,6 +128,25 @@ _RETRYABLE_QUERY_ERRORS: tuple[type[BaseException], ...] = (
)
+def _or_list(tokens: Sequence[str]) -> str:
+ quoted = [f"`{token}`" for token in tokens]
+ return f"{', '.join(quoted[:-1])} or {quoted[-1]}"
+
+
+WINDOW_TOKEN_HINT = (
+ f"For the report window, use {_or_list(WINDOW_FILTER_PLACEHOLDERS)} as a whole time filter, or "
+ f"{_or_list(WINDOW_BOUND_PLACEHOLDERS)} as a single timestamp, outside quotes. "
+ f"`{COMPARE_DATE_RANGE_PLACEHOLDER}` covers the previous and the current period together. For the previous "
+ f"period alone, use `timestamp >= {COMPARE_WINDOW_START_PLACEHOLDER} AND timestamp < {WINDOW_START_PLACEHOLDER}`. "
+ "The report fills in the dates when it runs."
+)
+
+
+def _reject_unknown_placeholders(hogql: str) -> None:
+ if problems := window_token_problems(hogql):
+ raise QueryError(" ".join([*problems, WINDOW_TOKEN_HINT]))
+
+
def _all_queries_failed_notice(total_steps: int, *, include_manage_link: bool = True) -> str:
noun = "the query" if total_steps == 1 else f"all {total_steps} queries"
notice = f"> ⚠️ This report could not be generated — {noun} the assistant wrote failed to run."
@@ -616,6 +641,7 @@ async def _run_steps(
for attempt in range(_MAX_QUERY_FIX_RETRIES + 1):
executable_hogql = window.render_window_filter(current_hogql)
try:
+ _reject_unknown_placeholders(current_hogql)
query = AssistantHogQLQuery(query=executable_hogql)
query_result = await asyncio.wait_for(
executor.arun_format_and_capture(query),
diff --git a/products/subscriptions/backend/temporal/ai_subscription/spec_generator.py b/products/subscriptions/backend/temporal/ai_subscription/spec_generator.py
index 4532c3ee78f9..733369d7a013 100644
--- a/products/subscriptions/backend/temporal/ai_subscription/spec_generator.py
+++ b/products/subscriptions/backend/temporal/ai_subscription/spec_generator.py
@@ -12,6 +12,12 @@ from pydantic import ValidationError
from posthog.schema import CachedTeamTaxonomyQueryResponse, SubscriptionAIPromptMaxLength, TeamTaxonomyQuery
+from posthog.hogql import ast
+from posthog.hogql.errors import BaseHogQLError
+from posthog.hogql.functions import find_hogql_function
+from posthog.hogql.parser import parse_select
+from posthog.hogql.visitor import TraversingVisitor
+
from posthog.hogql_queries.ai.team_taxonomy_query_runner import TeamTaxonomyQueryRunner
from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.models import EventDefinition, EventProperty, PropertyDefinition, Team, User
@@ -87,12 +93,12 @@ 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,
-)
+COMPARE_WINDOW_START_PLACEHOLDER = "{{compare_window_start}}"
+WINDOW_FILTER_PLACEHOLDERS = (DATE_RANGE_PLACEHOLDER, COMPARE_DATE_RANGE_PLACEHOLDER)
+WINDOW_BOUND_PLACEHOLDERS = (WINDOW_START_PLACEHOLDER, WINDOW_END_PLACEHOLDER, COMPARE_WINDOW_START_PLACEHOLDER)
+WINDOW_PLACEHOLDERS = (*WINDOW_FILTER_PLACEHOLDERS, *WINDOW_BOUND_PLACEHOLDERS)
+_SILENT_ON_FAILURE_SUFFIXES = ("OrNull", "OrZero")
+_PLACEHOLDER_TOKEN = re.compile(r"\{\{[^{}]*\}\}|[{<][^{}<>A-Za-z_]*[A-Za-z_][^{}<>]*[}>]")
# 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 = 8
@@ -227,7 +233,75 @@ class ReportWindow:
.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}')")
+ .replace(COMPARE_WINDOW_START_PLACEHOLDER, f"toDateTime('{self.compare_start_literal}')")
+ )
+
+
+class _PlaceholderTokenFinder(TraversingVisitor):
+ def __init__(self, hogql: str) -> None:
+ self.hogql = hogql
+ self.tokens: list[str] = []
+ self.quoted_window_tokens: list[str] = []
+ self.compared_filter_tokens: list[str] = []
+
+ def _text(self, node: ast.Placeholder) -> str | None:
+ if node.start is None or node.end is None:
+ return None
+ return self.hogql[node.start : node.end]
+
+ def visit_placeholder(self, node: ast.Placeholder) -> None:
+ if (text := self._text(node)) is not None:
+ self.tokens.append(text)
+
+ def visit_compare_operation(self, node: ast.CompareOperation) -> None:
+ for side in (node.left, node.right):
+ if isinstance(side, ast.Placeholder) and self._text(side) in WINDOW_FILTER_PLACEHOLDERS:
+ self.compared_filter_tokens.append(self.hogql[side.start : side.end])
+ super().visit_compare_operation(node)
+
+ def visit_constant(self, node: ast.Constant) -> None:
+ if isinstance(node.value, str):
+ self.quoted_window_tokens.extend(token for token in WINDOW_PLACEHOLDERS if token in node.value)
+ super().visit_constant(node)
+
+ def visit_call(self, node: ast.Call) -> None:
+ literal = node.args[0] if node.args else None
+ function = find_hogql_function(node.name)
+ if (
+ function is not None
+ and function.clickhouse_name.endswith(_SILENT_ON_FAILURE_SUFFIXES)
+ and isinstance(literal, ast.Constant)
+ and isinstance(literal.value, str)
+ ):
+ self.tokens.extend(_PLACEHOLDER_TOKEN.findall(literal.value))
+ super().visit_call(node)
+
+
+def _backticked(tokens: Sequence[str]) -> str:
+ return ", ".join(f"`{token}`" for token in dict.fromkeys(tokens))
+
+
+def window_token_problems(hogql: str) -> list[str]:
+ try:
+ query = parse_select(hogql)
+ except BaseHogQLError:
+ return []
+ finder = _PlaceholderTokenFinder(hogql)
+ finder.visit(query)
+ problems = []
+ if unknown := [token for token in finder.tokens if token not in WINDOW_PLACEHOLDERS]:
+ problems.append(f"The query uses {_backticked(unknown)}, which the report doesn't fill in.")
+ if finder.quoted_window_tokens:
+ problems.append(
+ f"The query puts {_backticked(finder.quoted_window_tokens)} inside quotes, where the report "
+ "can't fill it in."
+ )
+ if finder.compared_filter_tokens:
+ problems.append(
+ f"The query compares a value with {_backticked(finder.compared_filter_tokens)}, which is a whole "
+ "time filter, not a timestamp."
)
+ return problems
def _in_tz(dt: datetime, tz: tzinfo) -> datetime:
diff --git a/products/subscriptions/backend/temporal/ai_subscription/test/test_report_pipeline.py b/products/subscriptions/backend/temporal/ai_subscription/test/test_report_pipeline.py
index 5e3a77a880a9..9a9c8e09f3ca 100644
--- a/products/subscriptions/backend/temporal/ai_subscription/test/test_report_pipeline.py
+++ b/products/subscriptions/backend/temporal/ai_subscription/test/test_report_pipeline.py
@@ -26,6 +26,7 @@ from products.subscriptions.backend.temporal.ai_subscription.report_pipeline imp
_MAX_CONCURRENT_STEPS,
QUERY_FAILED_PREFIX,
QUERY_RETURNED_NO_ROWS,
+ WINDOW_TOKEN_HINT,
AiReportStageError,
PlanExecution,
QueryStepDiagnostic,
@@ -512,6 +513,97 @@ async def test_synthesis_prompt_carries_the_failure_marker(
assert "{{{" not in system_message # no placeholder left unrendered
+ "hogql,error_message",
+ [
+ pytest.param(
+ "SELECT count() FROM events WHERE timestamp >= toDateTime('{{D-2}} 00:00:00', 'UTC')",
+ ("The query uses `{{D-2}}`, which the report doesn't fill in. " + WINDOW_TOKEN_HINT),
+ id="double_brace_in_date",
+ ),
+ pytest.param(
+ "SELECT count() FROM events WHERE timestamp >= toDateTime('{D-1} 00:00:00','UTC')",
+ ("The query uses `{D-1}`, which the report doesn't fill in. " + WINDOW_TOKEN_HINT),
+ id="single_brace_in_date",
+ ),
+ pytest.param(
+ "SELECT count() FROM events WHERE timestamp >= toDateTime('<prior_day_start>', 'UTC')",
+ ("The query uses `<prior_day_start>`, which the report doesn't fill in. " + WINDOW_TOKEN_HINT),
+ id="angle_brackets_in_date",
+ ),
+ pytest.param(
+ "SELECT count() FROM events WHERE timestamp >= toDateTime\n ('{D-1} 00:00:00', 'UTC')",
+ ("The query uses `{D-1}`, which the report doesn't fill in. " + WINDOW_TOKEN_HINT),
+ id="whitespace_before_parenthesis",
+ ),
+ pytest.param(
+ "SELECT count() FROM events WHERE day = toDate('{{utc_report_yesterday}}') AND {{date_range}}",
+ ("The query uses `{{utc_report_yesterday}}`, which the report doesn't fill in. " + WINDOW_TOKEN_HINT),
+ id="unknown_next_to_known",
+ ),
+ pytest.param(
+ "SELECT count() FROM events WHERE timestamp >= toDateTime('{{D-1}}') AND timestamp < toDate('{D-1}')",
+ ("The query uses `{{D-1}}`, `{D-1}`, which the report doesn't fill in. " + WINDOW_TOKEN_HINT),
+ id="double_and_single_brace_with_one_name",
+ ),
+ pytest.param(
+ "SELECT count() FROM events WHERE timestamp >= {{yesterday_start}}",
+ ("The query uses `{{yesterday_start}}`, which the report doesn't fill in. " + WINDOW_TOKEN_HINT),
+ id="double_brace_outside_quotes",
+ ),
+ pytest.param(
+ "SELECT count() FROM events WHERE timestamp >= {{date_range}} AND timestamp < {{window_end}}",
+ (
+ "The query compares a value with `{{date_range}}`, which is a whole time filter, not a timestamp. "
+ + WINDOW_TOKEN_HINT
+ ),
+ id="filter_token_used_as_timestamp",
+ ),
+ pytest.param(
+ "SELECT count() FROM events WHERE timestamp >= toDateTime('{{window_start}}') AND {{date_range}}",
+ (
+ "The query puts `{{window_start}}` inside quotes, where the report can't fill it in. "
+ + WINDOW_TOKEN_HINT
+ ),
+ id="known_token_inside_quotes",
+ ),
+ pytest.param(
+ "SELECT count() FROM events WHERE timestamp >= toDateTime('{{D-1}}') AND timestamp < toDateTime('{{window_end}}')",
+ (
+ "The query uses `{{D-1}}`, which the report doesn't fill in. "
+ "The query puts `{{window_end}}` inside quotes, where the report can't fill it in. " + WINDOW_TOKEN_HINT
+ ),
+ id="invented_and_quoted_tokens",
+ ),
+ ],
+)
+@patch(f"{_RP}._arequest_hogql_fix", new_callable=AsyncMock)
+@patch(f"{_RP}.AssistantQueryExecutor")
+async def test_run_steps_sends_an_invented_placeholder_to_the_fixer_without_running_it(
+ mock_executor_cls: MagicMock, mock_fix: AsyncMock, hogql: str, error_message: str
+) -> None:
+ mock_executor_cls.return_value.arun_format_and_capture = AsyncMock(
+ return_value=FormattedQueryResult(formatted="formatted table", fallback_used=False, response=_RESPONSE)
+ )
+ mock_fix.return_value = "SELECT count() FROM events WHERE {{date_range}}"
+ spec = EnrichedPromptSpec(
+ cleaned_prompt="p",
+ context_blob="c",
+ plan=QueryPlan(overall_intent="i", steps=[QueryPlanStep(description="s", hogql=hogql)]),
+ )
+ window = _test_window()
+
+ execution = await _run_steps(spec, MagicMock(), MagicMock(), window, None, charts_enabled_for_team=True)
+
+ assert mock_fix.await_args is not None
+ assert mock_fix.await_args.kwargs["error_message"] == error_message
+ (executed,) = [
+ call.args[0].query for call in mock_executor_cls.return_value.arun_format_and_capture.await_args_list
+ ]
+ assert executed == f"SELECT count() FROM events WHERE {window.window_filter_sql}"
+ assert execution.failed_count == 0
+
+
@pytest.mark.parametrize(
"response,expected_rendered,expected_no_rows",
[
@@ -543,6 +635,57 @@ async def test_run_steps_marks_a_step_that_returned_no_rows(
assert execution.failed_count == 0
+ "hogql",
+ [
+ pytest.param(
+ "SELECT count() FROM events WHERE {{date_range}} AND timestamp < {{window_end}} "
+ "AND timestamp >= {{compare_window_start}}",
+ id="known_tokens",
+ ),
+ pytest.param(
+ "SELECT countIf(timestamp >= {{window_start}}) AS current, countIf(timestamp < {{window_start}}) AS previous "
+ "FROM events WHERE {{compare_date_range}}",
+ id="growth_pattern",
+ ),
+ pytest.param(
+ "SELECT JSONExtractString('{\"name\": 1}', 'name') FROM events WHERE {{date_range}}", id="json_literal"
+ ),
+ pytest.param(
+ "SELECT count() FROM events WHERE match(properties.$current_url, '[a-z]{2,8}') AND {{date_range}}",
+ id="regex_quantifier",
+ ),
+ pytest.param("SELECT toDate('2026{10}20') FROM events WHERE {{date_range}}", id="brace_date_separator"),
+ pytest.param(
+ "SELECT count() FROM events WHERE properties.template = 'Hi {{first_name}}, it''s {{day}}' AND {{date_range}}",
+ id="double_brace_in_string_value",
+ ),
+ pytest.param(
+ "SELECT count() FROM events WHERE {{date_range}} /* {{unused}} */ -- AND timestamp >= toDateTime('{D-1}')",
+ id="tokens_in_comments",
+ ),
+ ],
+)
+@patch(f"{_RP}._arequest_hogql_fix", new_callable=AsyncMock)
+@patch(f"{_RP}.AssistantQueryExecutor")
+async def test_run_steps_runs_queries_without_invented_placeholders(
+ mock_executor_cls: MagicMock, mock_fix: AsyncMock, hogql: str
+) -> None:
+ mock_executor_cls.return_value.arun_format_and_capture = AsyncMock(
+ return_value=FormattedQueryResult(formatted="formatted table", fallback_used=False, response=_RESPONSE)
+ )
+ spec = EnrichedPromptSpec(
+ cleaned_prompt="p",
+ context_blob="c",
+ plan=QueryPlan(overall_intent="i", steps=[QueryPlanStep(description="s", hogql=hogql)]),
+ )
+
+ execution = await _run_steps(spec, MagicMock(), MagicMock(), _test_window(), None, charts_enabled_for_team=True)
+
+ assert execution.failed_count == 0
+ mock_fix.assert_not_awaited()
+
+
@pytest.mark.parametrize(
"run_result,include_manage_link,expected_report,synthesizes",
[
diff --git a/products/subscriptions/backend/temporal/ai_subscription/test/test_spec_generator.py b/products/subscriptions/backend/temporal/ai_subscription/test/test_spec_generator.py
index f3673b0c7979..dba3d61782e8 100644
--- a/products/subscriptions/backend/temporal/ai_subscription/test/test_spec_generator.py
+++ b/products/subscriptions/backend/temporal/ai_subscription/test/test_spec_generator.py
@@ -1,3 +1,4 @@
+import re
from datetime import UTC, datetime, timedelta
from zoneinfo import ZoneInfo
@@ -9,6 +10,8 @@ from parameterized import parameterized
from posthog.schema import CachedTeamTaxonomyQueryResponse, TeamTaxonomyItem, TeamTaxonomyQuery
+from posthog.hogql.functions.mapping import HOGQL_CLICKHOUSE_FUNCTIONS
+
from posthog.exceptions import ClickHouseQueryTimeOut
from posthog.models import EventDefinition, EventProperty, PropertyDefinition, Team
@@ -20,6 +23,7 @@ from products.subscriptions.backend.temporal.ai_subscription.spec_generator impo
MAX_PINNED_EVENTS,
PROMPT_MAX_LENGTH,
RELEVANT_EVENTS_LIMIT,
+ WINDOW_PLACEHOLDERS,
ReportWindow,
StoredPlanInvalidError,
_event_property_names,
@@ -38,6 +42,7 @@ from products.subscriptions.backend.temporal.ai_subscription.spec_generator impo
get_ai_query_plan_status,
sanitize_prompt,
validate_stored_query_plan,
+ window_token_problems,
)
_SG = "products.subscriptions.backend.temporal.ai_subscription.spec_generator"
@@ -48,6 +53,64 @@ def _window(days: int = 7) -> ReportWindow:
return ReportWindow(start=end - timedelta(days=days), end=end)
+# Strict targets such as toDate and toDateTime64 raise on a string they can't parse, so ClickHouse
+# already rejects an invented placeholder there. Only the targets that return NULL hide it.
+_NULL_ON_FAILURE_DATE_ALIASES = sorted(
+ name
+ for name, meta in HOGQL_CLICKHOUSE_FUNCTIONS.items()
+ if meta.clickhouse_name.endswith(("OrNull", "OrZero"))
+ and re.search(r"Date|^toModifiedJulianDay", meta.clickhouse_name)
+)
+
+
[email protected]("alias", _NULL_ON_FAILURE_DATE_ALIASES)
+def test_window_token_problems_covers_every_null_on_failure_date_parser(alias: str) -> None:
+ assert window_token_problems(f"SELECT {alias}('{{{{D-1}}}}') FROM events") == [
+ "The query uses `{{D-1}}`, which the report doesn't fill in."
+ ]
+
+
+_RENDER_WINDOW = ReportWindow(start=datetime(2026, 6, 8, tzinfo=UTC), end=datetime(2026, 6, 15, tzinfo=UTC))
+
+
+ "hogql,expected",
+ [
+ pytest.param(
+ "WHERE {{date_range}}",
+ "WHERE timestamp >= toDateTime('2026-06-08 00:00:00') AND timestamp < toDateTime('2026-06-15 00:00:00')",
+ id="date_range",
+ ),
+ pytest.param(
+ "WHERE {{compare_date_range}}",
+ "WHERE timestamp >= toDateTime('2026-06-01 00:00:00') AND timestamp < toDateTime('2026-06-15 00:00:00')",
+ id="compare_date_range",
+ ),
+ pytest.param(
+ "WHERE timestamp >= {{window_start}}",
+ "WHERE timestamp >= toDateTime('2026-06-08 00:00:00')",
+ id="window_start",
+ ),
+ pytest.param(
+ "WHERE timestamp < {{window_end}}",
+ "WHERE timestamp < toDateTime('2026-06-15 00:00:00')",
+ id="window_end",
+ ),
+ pytest.param(
+ "WHERE first_seen >= {{compare_window_start}}",
+ "WHERE first_seen >= toDateTime('2026-06-01 00:00:00')",
+ id="compare_window_start",
+ ),
+ ],
+)
+def test_render_window_filter_fills_in_each_window_token(hogql: str, expected: str) -> None:
+ assert _RENDER_WINDOW.render_window_filter(hogql) == expected
+
+
+def test_render_window_filter_fills_in_every_supported_token() -> None:
+ assert "{{" not in _RENDER_WINDOW.render_window_filter(" AND ".join(WINDOW_PLACEHOLDERS))
+
+
class TestSanitizePrompt:
"""`sanitize_prompt` is the public input-validation gate, so its three reject branches and the
framing-marker stripping are pinned explicitly — a dropped branch would silently admit bad input."""