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): deterministically pin user-named events in AI reports (#66809)

Vasco de Krijgerc5f4996d9486
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 89950ead4536..dab6f7d937ae 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.py
@@ -1,3 +1,4 @@
+import re
from collections.abc import Sequence
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta, tzinfo
@@ -60,6 +61,16 @@ CANDIDATE_EVENTS_LIMIT = 500
# schema stays a few thousand property names at most.
RELEVANT_EVENTS_LIMIT = 100
EVENT_PROPERTIES_PER_EVENT_LIMIT = 15
+# A user-named event is pinned even when it falls outside the LLM candidate cap, but both ends are
+# bounded so neither a large taxonomy nor a degenerate prompt can blow up generation. The pin scan
+# reads at most PINNED_EVENT_SCAN_LIMIT definitions (most-recently-seen first — far past
+# CANDIDATE_EVENTS_LIMIT, so any realistically-recent named event still resolves), and at most
+# MAX_PINNED_EVENTS pins survive (keeps the planner context / property lookup predictable).
+PINNED_EVENT_SCAN_LIMIT = 2000
+MAX_PINNED_EVENTS = 25
+# Tokens the user quoted in the prompt to name a specific event: `event name`, "event name",
+# or 'event name'. The capture groups are non-greedy so adjacent quotes don't merge into one token.
+_QUOTED_TOKEN_RE = re.compile(r"`([^`]+)`|\"([^\"]+)\"|'([^']+)'")
DEFAULT_PLANNER_MODEL = "gpt-4.1"
DEFAULT_SYNTHESIS_MODEL = "gpt-4.1"
@@ -222,15 +233,10 @@ def _group_type_labels(team: Team) -> list[str]:
return labels
-def _candidate_event_names(team: Team, limit: int) -> dict[str, str]:
- # {sanitized_name: raw_name} for the team's events, most-recently-seen first. Sanitized keys are what
- # the selection LLM sees (event names are user-controlled); raw values feed the EventProperty lookup,
- # which is keyed on the stored name. First raw wins if two names sanitize to the same string.
- raw_names = (
- EventDefinition.objects.filter(team_id=team.pk)
- .order_by(F("last_seen_at").desc(nulls_last=True), "name")
- .values_list("name", flat=True)[:limit]
- )
+def _candidate_event_names(raw_names: Sequence[str]) -> dict[str, str]:
+ # {sanitized_name: raw_name}. Sanitized keys are what the selection LLM sees (event names are
+ # user-controlled); raw values feed the EventProperty lookup, which is keyed on the stored name.
+ # First raw wins if two names sanitize to the same string.
candidates: dict[str, str] = {}
for raw in raw_names:
clean = sanitize_user_text(raw, EVENT_NAME_MAX_LENGTH)
@@ -239,16 +245,72 @@ def _candidate_event_names(team: Team, limit: int) -> dict[str, str]:
return candidates
-def _select_relevant_events(
- team: Team, user: User, prompt: str, trace_correlation_id: Optional[Union[int, str]] = None
-) -> list[str]:
- # Pass 1: the model picks relevant events from the project's vocabulary (vs lexical matching). Returns
- # RAW event names (the EventProperty lookup is keyed on them); any failure degrades to no relevant-events
- # section rather than breaking generation.
- candidates = _candidate_event_names(team, CANDIDATE_EVENTS_LIMIT)
- if not candidates:
+def _normalize_event_token(value: str) -> str:
+ # Sanitize (event names are user-controlled) then case-fold + collapse whitespace so a quoted
+ # `Export Created` matches a stored `export created`. Empty if nothing survives sanitization.
+ return sanitize_user_text(value, EVENT_NAME_MAX_LENGTH).casefold()
+
+
+def _extract_quoted_event_tokens(prompt: str) -> set[str]:
+ tokens: set[str] = set()
+ for match in _QUOTED_TOKEN_RE.finditer(prompt):
+ raw = next(group for group in match.groups() if group is not None)
+ normalized = _normalize_event_token(raw)
+ if normalized:
+ tokens.add(normalized)
+ return tokens
+
+
+def _appears_as_standalone_token(needle: str, haystack: str) -> bool:
+ # Match `needle` only when flanked by string edges or non-identifier chars, so a bare `pageview`
+ # reference is pinned but `my_pageview_handler` is not. `$`/`.` are treated as part of the token
+ # (event names like `$pageview` and `app.opened` are common), so they don't form a false boundary.
+ if not needle:
+ return False
+ return re.search(rf"(?<![\w$.]){re.escape(needle)}(?![\w$.])", haystack) is not None
+
+
+def _pinned_event_names(prompt: str, event_names: Sequence[str]) -> list[str]:
+ """The events the user explicitly named in the prompt, resolved to their raw taxonomy names.
+
+ Why: naming an event is a statement of intent, not a relevance judgment — routing it through the
+ probabilistic LLM selection means a report can silently ignore the one event the user asked about.
+ Pins are matched deterministically (quoted/backticked, or a standalone token of the prompt) so an
+ explicit mention always reaches the planner, and capped at `MAX_PINNED_EVENTS` so a degenerate
+ prompt can't flood the context.
+ """
+ quoted = _extract_quoted_event_tokens(prompt)
+ haystack = _normalize_event_token(prompt)
+ if not quoted and not haystack:
return []
+ pinned: list[str] = []
+ seen: set[str] = set()
+ for raw in event_names:
+ normalized = _normalize_event_token(raw)
+ if not normalized or normalized in seen:
+ continue
+ if normalized in quoted or _appears_as_standalone_token(normalized, haystack):
+ seen.add(normalized)
+ pinned.append(raw)
+ if len(pinned) >= MAX_PINNED_EVENTS:
+ break
+ return pinned
+
+
+def _recent_event_names(team: Team, limit: int) -> list[str]:
+ return list(
+ EventDefinition.objects.filter(team_id=team.pk)
+ .order_by(F("last_seen_at").desc(nulls_last=True), "name")
+ .values_list("name", flat=True)[:limit]
+ )
+
+
+def _llm_selected_events(
+ team: Team, user: User, prompt: str, candidates: dict[str, str], trace_correlation_id: Optional[Union[int, str]]
+) -> list[str]:
+ # The model picks relevant events from the project's vocabulary (vs lexical matching). Any failure
+ # degrades to no picks rather than breaking generation — deterministic pins still survive.
posthog_properties: dict[str, Union[str, int]] = {"feature": "ai_subscription", "stage": "event_selection"}
if trace_correlation_id is not None:
posthog_properties["subscription_id"] = trace_correlation_id
@@ -283,11 +345,28 @@ def _select_relevant_events(
if raw is not None and raw not in seen:
seen.add(raw)
selected.append(raw)
- if len(selected) >= RELEVANT_EVENTS_LIMIT:
- break
return selected
+def _select_relevant_events(
+ team: Team, user: User, prompt: str, trace_correlation_id: Optional[Union[int, str]] = None
+) -> list[str]:
+ # Returns RAW event names (the EventProperty lookup is keyed on them).
+ recent_names = _recent_event_names(team, PINNED_EVENT_SCAN_LIMIT)
+ candidates = _candidate_event_names(recent_names[:CANDIDATE_EVENTS_LIMIT])
+ pinned = _pinned_event_names(prompt, recent_names)
+ if not candidates:
+ # No candidate vocabulary for the LLM pass, but explicit pins still count — the pin scan
+ # covers the full recent-names window, not just the candidate slice.
+ return pinned
+
+ llm_selected = _llm_selected_events(team, user, prompt, candidates, trace_correlation_id)
+
+ # Pins lead so the cap can only ever drop LLM picks — an explicitly named event is never truncated.
+ union_pinned_first = list(dict.fromkeys((*pinned, *llm_selected)))
+ return union_pinned_first[: max(RELEVANT_EVENTS_LIMIT, len(pinned))]
+
+
def _event_property_names(team: Team, events: list[str], per_event_limit: int) -> dict[str, list[str]]:
# One indexed (team, event) query. Without it the planner gets no event-property schema and guesses
# property names — the top cause of InternalHogQLError.
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 620be8128092..73d10deecb74 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,13 +16,18 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.schemas imp
RelevantEvents,
)
from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import (
+ MAX_PINNED_EVENTS,
PROMPT_MAX_LENGTH,
+ RELEVANT_EVENTS_LIMIT,
PromptRejectedError,
ReportWindow,
_event_property_names,
+ _extract_quoted_event_tokens,
_group_type_labels,
_no_data_event_names,
_person_property_names,
+ _pinned_event_names,
+ _recent_event_names,
_select_relevant_events,
build_context_blob,
compute_report_window,
@@ -172,6 +177,135 @@ class TestSelectRelevantEvents(APIBaseTest):
assert _select_relevant_events(self.team, self.user, "exports") == []
mock_chat.assert_not_called()
+ @patch(f"{_SG}.MaxChatOpenAI")
+ def test_pins_named_event_the_llm_did_not_pick(self, mock_chat: MagicMock) -> None:
+ # The deterministic guarantee: a backticked event the LLM ignores is still force-included.
+ EventDefinition.objects.create(team=self.team, name="export created")
+ mock_chat.return_value.with_structured_output.return_value.invoke.return_value = RelevantEvents(events=[])
+
+ assert _select_relevant_events(self.team, self.user, "how is `export created` doing?") == ["export created"]
+
+ @patch(f"{_SG}.MaxChatOpenAI")
+ def test_unions_pinned_event_ahead_of_llm_picks(self, mock_chat: MagicMock) -> None:
+ # Pinned event leads; the LLM's own (real) pick is kept and de-duped against it.
+ EventDefinition.objects.create(team=self.team, name="export created")
+ EventDefinition.objects.create(team=self.team, name="alert created")
+ mock_chat.return_value.with_structured_output.return_value.invoke.return_value = RelevantEvents(
+ events=["alert created", "export created"]
+ )
+
+ assert _select_relevant_events(self.team, self.user, "how is `export created` doing?") == [
+ "export created",
+ "alert created",
+ ]
+
+ @patch(f"{_SG}.MaxChatOpenAI")
+ def test_pinned_event_survives_when_llm_fills_the_cap(self, mock_chat: MagicMock) -> None:
+ # The named event is created last (oldest last_seen_at → outside the LLM's leading picks) and the
+ # LLM returns a full cap's worth of other events. The pin must not be truncated by the cap.
+ for i in range(RELEVANT_EVENTS_LIMIT):
+ EventDefinition.objects.create(team=self.team, name=f"event_{i}", last_seen_at=datetime.now(tz=UTC))
+ EventDefinition.objects.create(team=self.team, name="named_event", last_seen_at=None)
+ mock_chat.return_value.with_structured_output.return_value.invoke.return_value = RelevantEvents(
+ events=[f"event_{i}" for i in range(RELEVANT_EVENTS_LIMIT)]
+ )
+
+ selected = _select_relevant_events(self.team, self.user, "tell me about `named_event`")
+
+ # The pin leads and survives; the cap drops the LLM's last pick instead of the named event.
+ assert selected[0] == "named_event"
+ assert len(selected) == RELEVANT_EVENTS_LIMIT
+
+ @patch(f"{_SG}.CANDIDATE_EVENTS_LIMIT", 5)
+ @patch(f"{_SG}.MaxChatOpenAI")
+ def test_pins_event_outside_the_candidate_cap(self, mock_chat: MagicMock) -> None:
+ # The whole reason the pin scan has its own (larger) bound: an event ranked below the candidate
+ # cap is invisible to the selection LLM, but an explicit mention must still resolve. With the cap
+ # patched to 5, the named event (oldest last_seen_at) falls outside the candidate slice.
+ for i in range(5):
+ EventDefinition.objects.create(team=self.team, name=f"common_{i}", last_seen_at=datetime.now(tz=UTC))
+ EventDefinition.objects.create(team=self.team, name="rare_event", last_seen_at=None)
+ mock_chat.return_value.with_structured_output.return_value.invoke.return_value = RelevantEvents(events=[])
+
+ assert _select_relevant_events(self.team, self.user, "what about `rare_event`?") == ["rare_event"]
+
+ @patch(f"{_SG}.CANDIDATE_EVENTS_LIMIT", 0)
+ @patch(f"{_SG}.MaxChatOpenAI")
+ def test_pins_survive_when_candidate_slice_is_empty(self, mock_chat: MagicMock) -> None:
+ # An empty candidate slice skips the LLM pass but must not drop explicit pins — the pin scan
+ # covers the full recent-names window, not just the candidate slice.
+ EventDefinition.objects.create(team=self.team, name="export created")
+
+ assert _select_relevant_events(self.team, self.user, "how is `export created`?") == ["export created"]
+ mock_chat.assert_not_called()
+
+
+class TestExtractQuotedEventTokens:
+ @parameterized.expand(
+ [
+ ("backticks", "how is `export created`?", {"export created"}),
+ ("double_quotes", 'how is "export created"?', {"export created"}),
+ ("single_quotes", "how is 'export created'?", {"export created"}),
+ ("mixed_quote_styles", "`a` and \"b\" and 'c'", {"a", "b", "c"}),
+ ("casefolds_and_collapses_whitespace", "`Export Created`", {"export created"}),
+ ("none_present", "how are exports doing?", set()),
+ ("ignores_unbalanced_quote", "how is `export created doing?", set()),
+ ]
+ )
+ def test_extracts_normalized_quoted_tokens(self, _name: str, prompt: str, expected: set[str]) -> None:
+ assert _extract_quoted_event_tokens(prompt) == expected
+
+
+class TestPinnedEventNames:
+ @parameterized.expand(
+ [
+ ("quoted_name_pinned", "how is `export created`?", ["export created"]),
+ ("case_insensitive_match", "how is `EXPORT CREATED`?", ["export created"]),
+ ("bare_exact_single_word_pinned", "trends for signup over time", ["signup"]),
+ ("bare_exact_multi_word_pinned", "how is export created trending", ["export created"]),
+ ("nonexistent_quoted_name_ignored", "how is `totally made up`?", []),
+ ("substring_does_not_match", "tell me about signups please", []),
+ ("no_reference_pins_nothing", "give me a weekly summary", []),
+ ]
+ )
+ def test_pins_only_validated_named_events(self, _name: str, prompt: str, expected: list[str]) -> None:
+ assert _pinned_event_names(prompt, ["export created", "signup"]) == expected
+
+ @parameterized.expand(
+ [
+ # `$` and `.` are part of an event-name token, so `$pageview` and `app.opened` match as
+ # whole names but never as a bare `pageview`/`opened` slice of a larger token.
+ ("quoted_dollar_name", "how is `$pageview`?", ["$pageview"]),
+ ("bare_dollar_name_excludes_plain", "spike in $pageview today", ["$pageview"]),
+ ("bare_plain_name_excludes_dollar", "how many pageview events", ["pageview"]),
+ ("dotted_name_pinned", "trend of app.opened", ["app.opened"]),
+ ("embedded_in_identifier_not_matched", "check my_pageview_handler logs", []),
+ ]
+ )
+ def test_special_char_token_boundaries(self, _name: str, prompt: str, expected: list[str]) -> None:
+ assert _pinned_event_names(prompt, ["$pageview", "pageview", "app.opened"]) == expected
+
+ def test_caps_pinned_count_at_max(self) -> None:
+ # A degenerate prompt naming more events than the ceiling pins at most MAX_PINNED_EVENTS, so the
+ # planner context and the downstream property lookup stay bounded.
+ names = [f"evt_{i}" for i in range(MAX_PINNED_EVENTS + 5)]
+ prompt = " ".join(f"`{n}`" for n in names)
+
+ assert len(_pinned_event_names(prompt, names)) == MAX_PINNED_EVENTS
+
+
+class TestRecentEventNames(APIBaseTest):
+ def test_scopes_to_team_and_respects_limit(self) -> None:
+ other = Team.objects.create(organization=self.organization, name="other")
+ EventDefinition.objects.create(team=other, name="other_team_event")
+ for i in range(3):
+ EventDefinition.objects.create(team=self.team, name=f"evt_{i}", last_seen_at=datetime.now(tz=UTC))
+
+ names = _recent_event_names(self.team, limit=2)
+
+ assert len(names) == 2
+ assert "other_team_event" not in names
+
class TestEventPropertyNames(APIBaseTest):
def test_groups_properties_by_event_in_one_query(self) -> None: