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(data-warehouse): route semantic enrichment through the ai-gateway (#94494)

Brandon8aa1c0c9e80e
diff --git a/posthog/llm/semantic_enrichment.py b/posthog/llm/semantic_enrichment.py
index 448588e7c5ba..ae0eee125c77 100644
--- a/posthog/llm/semantic_enrichment.py
+++ b/posthog/llm/semantic_enrichment.py
@@ -14,20 +14,47 @@ takes the annotation model class and its owner fields as arguments so one code p
import re
import json
-from collections.abc import Callable
+from collections.abc import Callable, Iterable
+from math import ceil
from typing import Any
from django.utils import timezone
import posthoganalytics
+from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
-from posthog.llm.gateway_client import Product, get_llm_client
+from posthog.llm.gateway_client import (
+ Product,
+ build_anthropic_client,
+ get_llm_client,
+ resolve_ai_gateway_config,
+ team_distinct_id,
+)
from posthog.models import Team
DEFAULT_ENRICHMENT_MODEL = "claude-haiku-4-5"
+# Ceiling for one reply, not the value sent: the reply echoes each column name as a JSON key, so a
+# table's need scales with its name lengths. `bound_prompt_over_columns` sizes and bounds the ask.
+MAX_OUTPUT_TOKENS = 16384
+# Floor for the sized ceiling, so a narrow table still has room to answer.
+MIN_OUTPUT_TOKENS = 1024
+# What one `"name": "sentence"` pair costs beyond the name itself: the quotes, colon, comma and
+# newline, then a sentence of description.
+_JSON_PAIR_OVERHEAD_CHARS = 8
+_DESCRIPTION_BUDGET_CHARS = 240
+# Deliberately below the ~3.5 chars/token English average: under-reserving truncates the reply, while
+# over-reserving only leaves headroom unused.
+_CHARS_PER_OUTPUT_TOKEN = 3.0
# Keep the prompt and response bounded — wide tables shouldn't blow up the context or the cost.
MAX_COLUMNS_PER_TABLE = 200
+# Calls one run may spend finishing a table one reply cannot hold. A caller whose completion marker
+# covers the whole object has to finish here, or a column it never asked about is latched as done.
+MAX_ENRICHMENT_BATCHES = 4
+# Wall clock after which a run starts no further batches; the first call always runs, so batching
+# cannot breach a deadline one call would have met. Sized inside the enrichment activity's timeout
+# but not derived from it: across packages a silent drift would surface as a timeout, not a shortfall.
+ENRICHMENT_BATCH_BUDGET_SECONDS = 300.0
# The team's core memory is free-form and unbounded; a large dump alone can push the prompt past the
# model's 200k-token context window. Cap it — a concise company summary is all the enrichment needs.
MAX_BUSINESS_CONTEXT_CHARS = 20_000
@@ -55,10 +82,10 @@ def collapse_untrusted(text: str) -> str:
def extract_json_object(content: str) -> dict[str, Any] | None:
"""Parse the model's JSON reply, tolerating markdown fences or surrounding prose.
- `response_format={"type": "json_object"}` isn't reliably honoured through the gateway's Anthropic
- route, so the reply can arrive fenced (```json … ```) or with leading text — a bare `json.loads`
- then dies on the first non-`{` character. Try the whole string, then a fenced block, then the
- outermost `{…}` span. Returns the dict, or None if nothing parses to a JSON object.
+ Callers that cannot set a response-format parameter, the Messages leg among them, ask for JSON in
+ the prompt, so the reply can arrive fenced (```json … ```) or with leading text and a bare
+ `json.loads` dies on the first non-`{` character. Try the whole string, then a fenced block, then
+ the outermost `{…}` span. Returns the dict, or None if nothing parses to a JSON object.
"""
text = content.strip()
candidates = [text]
@@ -123,6 +150,118 @@ def get_team_business_context(team: Team) -> str:
return (core_memory.text or "").strip() if core_memory else ""
+class TruncatedCompletionError(ValueError):
+ """The model hit its output ceiling, so the reply is cut off rather than malformed.
+
+ A `ValueError` so the callers' existing `except Exception` handlers keep reporting "partial",
+ but a distinct type and message so a too-small ceiling is separable from a bad reply.
+ """
+
+
+@frozen
+class _Completion:
+ """One model reply, normalised across the two request shapes."""
+
+ text: str
+ usage: dict[str, Any]
+ truncated: bool
+ # The ceiling this leg sent, for the truncation message. None when the provider applied its own.
+ max_output_tokens: int | None = None
+
+
+class _MessagesClient:
+ """Anthropic Messages, the only shape the Go ai-gateway plans Claude models under."""
+
+ def __init__(self, client: Any) -> None:
+ self._client = client
+
+ def complete(
+ self, *, model: str, prompt: str, temperature: float, team_id: int, max_output_tokens: int = MAX_OUTPUT_TOKENS
+ ) -> _Completion:
+ response = self._client.messages.create(
+ model=model,
+ max_tokens=max_output_tokens,
+ messages=[{"role": "user", "content": prompt}],
+ temperature=temperature,
+ metadata={"user_id": team_distinct_id(team_id)},
+ )
+ usage_obj = getattr(response, "usage", None)
+ prompt_tokens = getattr(usage_obj, "input_tokens", None)
+ completion_tokens = getattr(usage_obj, "output_tokens", None)
+ return _Completion(
+ text=_messages_text(response),
+ usage=_usage(model, prompt_tokens, completion_tokens),
+ truncated=getattr(response, "stop_reason", None) == "max_tokens",
+ max_output_tokens=max_output_tokens,
+ )
+
+
+class _ChatClient:
+ """OpenAI Chat Completions, the shape the Python gateway has always served this product."""
+
+ def __init__(self, client: Any) -> None:
+ self._client = client
+
+ def complete(
+ self, *, model: str, prompt: str, temperature: float, team_id: int, max_output_tokens: int = MAX_OUTPUT_TOKENS
+ ) -> _Completion:
+ # No max_tokens: this leg lets the provider apply its own ceiling, and the bounded ask list
+ # already keeps the reply to one response.
+ response = self._client.chat.completions.create(
+ model=model,
+ messages=[{"role": "user", "content": prompt}],
+ temperature=temperature,
+ response_format={"type": "json_object"},
+ user=team_distinct_id(team_id),
+ )
+ choice = response.choices[0]
+ usage_obj = getattr(response, "usage", None)
+ return _Completion(
+ text=choice.message.content or "",
+ usage=_usage(
+ model,
+ getattr(usage_obj, "prompt_tokens", None),
+ getattr(usage_obj, "completion_tokens", None),
+ ),
+ truncated=getattr(choice, "finish_reason", None) == "length",
+ )
+
+
+def _usage(model: str, prompt_tokens: int | None, completion_tokens: int | None) -> dict[str, Any]:
+ """Token counts under the OpenAI key names the enrichment analytics events already carry."""
+ return {
+ "model": model,
+ "prompt_tokens": prompt_tokens,
+ "completion_tokens": completion_tokens,
+ "total_tokens": None
+ if prompt_tokens is None or completion_tokens is None
+ else prompt_tokens + completion_tokens,
+ }
+
+
+def _messages_text(response: Any) -> str:
+ """Concatenate the text blocks of a Messages reply; other block types are ignored."""
+ blocks = getattr(response, "content", None) or []
+ return "".join(getattr(block, "text", None) or "" for block in blocks if getattr(block, "type", None) == "text")
+
+
+def build_enrichment_client(product: Product, team_id: int) -> _MessagesClient | _ChatClient:
+ """Client for one enrichment call, on whichever shape the resolved gateway serves.
+
+ The Go ai-gateway plans Claude models only under Anthropic's native Messages shape, so the cutover
+ sends Messages there. The Python gateway keeps receiving Chat Completions, which is what this
+ product has always sent it, so clearing `AI_GATEWAY_URL` restores the previous wire behaviour rather
+ than falling back onto a route the product has never exercised.
+ """
+ if resolve_ai_gateway_config():
+ # The Messages `metadata.user_id` goes upstream to the provider; capture identity comes from
+ # the X-PostHog-Distinct-Id header this sets, so without it the team is not attributed.
+ return _MessagesClient(
+ build_anthropic_client(product, ai_product=product, team_id=team_id, distinct_id=team_distinct_id(team_id))
+ )
+ return _ChatClient(get_llm_client(product=product, team_id=team_id))
+
+
def generate_json_completion(
*,
product: Product,
@@ -130,35 +269,56 @@ def generate_json_completion(
prompt: str,
model: str = DEFAULT_ENRICHMENT_MODEL,
temperature: float = 0.2,
- client: Any = None,
+ client: "_MessagesClient | _ChatClient | None" = None,
+ max_output_tokens: int = MAX_OUTPUT_TOKENS,
) -> tuple[dict[str, Any], dict[str, Any]]:
"""Call the LLM for a JSON reply. Returns `(parsed_payload, usage)` — usage carries model + tokens.
- `client` lets a caller inject an already-resolved gateway client (the warehouse path does this so
- its existing test seam keeps working); when omitted we resolve one for `product`/`team_id`.
+ `client` lets a caller inject an already-resolved enrichment client (the warehouse path does this
+ so its existing test seam keeps working); when omitted we resolve one for `product`/`team_id`.
+ Raises `TruncatedCompletionError` when the reply was cut off by the output ceiling.
"""
if client is None:
- client = get_llm_client(product=product, team_id=team_id)
- response = client.chat.completions.create(
- model=model,
- messages=[{"role": "user", "content": prompt}],
- temperature=temperature,
- response_format={"type": "json_object"},
- user=f"team-{team_id}",
+ client = build_enrichment_client(product, team_id)
+ completion = client.complete(
+ model=model, prompt=prompt, temperature=temperature, team_id=team_id, max_output_tokens=max_output_tokens
)
- usage_obj = getattr(response, "usage", None)
- usage: dict[str, Any] = {
- "model": model,
- "prompt_tokens": getattr(usage_obj, "prompt_tokens", None),
- "completion_tokens": getattr(usage_obj, "completion_tokens", None),
- "total_tokens": getattr(usage_obj, "total_tokens", None),
- }
- parsed = extract_json_object(response.choices[0].message.content or "")
+ if completion.truncated:
+ # Terminal even when the fragment parses: the view consumer stores its enrichment hash on
+ # any non-exception return, so a partial column set latches and no later run retries.
+ ceiling = f"{completion.max_output_tokens}-token" if completion.max_output_tokens else "provider-default"
+ raise TruncatedCompletionError(f"model response hit the {ceiling} output ceiling")
+ parsed = extract_json_object(completion.text)
if parsed is None:
# Surface as an LLM failure (caught by the caller → "partial") rather than silently
# persisting nothing, so the error stays visible in analytics.
raise ValueError("model response was not valid JSON")
- return parsed, usage
+ return parsed, completion.usage
+
+
+def projected_output_tokens(column_names: Iterable[str]) -> int:
+ """Tokens the JSON reply needs to answer for `column_names`.
+
+ Every column echoes its own name back as a key before its sentence, so a table of long names needs
+ a far larger ceiling than a table of short ones with the same column count.
+ """
+ chars = sum(len(name) + _JSON_PAIR_OVERHEAD_CHARS + _DESCRIPTION_BUDGET_CHARS for name in column_names)
+ # The enclosing braces, then the floor so a narrow table still has room to answer.
+ return max(MIN_OUTPUT_TOKENS, ceil((chars + 2) / _CHARS_PER_OUTPUT_TOKEN))
+
+
+@frozen
+class BoundedPrompt:
+ """A prompt sized to fit, plus the columns the bounding gave up to make it fit.
+
+ `deferred` is what the caller still owes: it is empty on the ordinary path, and a caller whose
+ idempotency marker covers the whole object must withhold that marker while it is not.
+ """
+
+ prompt: str
+ max_output_tokens: int
+ requested: list[str]
+ deferred: list[str]
def bound_prompt_over_columns(
@@ -166,25 +326,45 @@ def bound_prompt_over_columns(
columns: list[dict[str, Any]],
columns_needing_description: list[str],
max_prompt_chars: int = MAX_PROMPT_CHARS,
-) -> str:
- """Build a prompt via `builder`, dropping tail columns until it fits the context window.
+ max_output_tokens: int = MAX_OUTPUT_TOKENS,
+) -> BoundedPrompt:
+ """Build a prompt via `builder`, dropping tail columns until both the prompt and its reply fit.
`builder(shown_columns, columns_needing_description)` assembles the surface-specific prompt from a
subset of columns; anything else it depends on (foreign keys, business context, …) is closed over
by the caller and re-derived from `shown_columns` on each call so the prompt never references a
- column it no longer lists. If the assembled prompt is still too long — a pathologically wide table,
- say — columns are dropped from the tail until it fits. Skipped columns keep their place in the
- idempotency snapshot, so a later pass enriches them.
+ column it no longer lists. Two bounds drop tail columns: an assembled prompt too long for the
+ context window, and an ask list whose reply could not fit under `max_output_tokens`. The second
+ bound otherwise truncates the reply on every attempt, so the table never gets past a partial result.
+
+ Dropping is deferral, not completion: the returned `deferred` names were never asked about, so a
+ caller that records "enriched" for the whole object has to withhold that record until it is empty,
+ or those columns are never described again. A caller whose idempotency is per column (an annotation
+ row each) needs no such guard, because an undescribed column is simply still unannotated.
"""
shown_columns = columns
needing = columns_needing_description
while True:
prompt = builder(shown_columns, needing)
- if len(prompt) <= max_prompt_chars or len(shown_columns) <= 1:
- return prompt
- # Drop ~10% of the tail columns and re-measure. Prune the ask list to the surviving columns too.
+ needed_tokens = projected_output_tokens(needing)
+ if (len(prompt) <= max_prompt_chars and needed_tokens <= max_output_tokens) or len(shown_columns) <= 1:
+ asked = set(needing)
+ return BoundedPrompt(
+ prompt=prompt,
+ max_output_tokens=min(needed_tokens, max_output_tokens),
+ requested=list(needing),
+ deferred=[name for name in columns_needing_description if name not in asked],
+ )
+ # Unasked columns go first: they cost prompt space without producing an answer, while dropping
+ # an asked one defers real work. This ordering is what lets a caller batch; a blind tail slice
+ # sheds the same names every pass, so the next batch asks for nothing.
cut = max(1, len(shown_columns) // 10)
- shown_columns = shown_columns[:-cut]
+ asked = set(needing)
+ tail = range(len(shown_columns) - 1, -1, -1)
+ droppable = [i for i in tail if shown_columns[i]["name"] not in asked]
+ droppable += [i for i in tail if shown_columns[i]["name"] in asked]
+ dropped_indices = set(droppable[:cut])
+ shown_columns = [column for i, column in enumerate(shown_columns) if i not in dropped_indices]
kept_names = {column["name"] for column in shown_columns}
needing = [name for name in needing if name in kept_names]
diff --git a/posthog/llm/test_semantic_enrichment.py b/posthog/llm/test_semantic_enrichment.py
new file mode 100644
index 000000000000..b20c5058aab0
--- /dev/null
+++ b/posthog/llm/test_semantic_enrichment.py
@@ -0,0 +1,515 @@
+import json
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from django.test import override_settings
+
+from posthog.llm.gateway_client import team_distinct_id, team_trace_id
+from posthog.llm.semantic_enrichment import (
+ MAX_COLUMNS_PER_TABLE,
+ MAX_ENRICHMENT_BATCHES,
+ MAX_OUTPUT_TOKENS,
+ MIN_OUTPUT_TOKENS,
+ TruncatedCompletionError,
+ _ChatClient,
+ _Completion,
+ _MessagesClient,
+ bound_prompt_over_columns,
+ build_enrichment_client,
+ generate_json_completion,
+ projected_output_tokens,
+)
+
+AI_GATEWAY_URL = "https://ai-gateway.example/v1"
+AI_GATEWAY_KEY = "phs_project_secret"
+
+
+class TestBuildEnrichmentClient:
+ @override_settings(AI_GATEWAY_URL=AI_GATEWAY_URL, AI_GATEWAY_API_KEY=AI_GATEWAY_KEY)
+ @patch("posthog.llm.gateway_client.httpx.Client")
+ @patch("posthog.llm.gateway_client.Anthropic")
+ def test_gateway_mode_uses_native_messages_with_product_and_team(self, mock_anthropic, mock_httpx):
+ result = build_enrichment_client("warehouse_semantic_enrichment", 7)
+
+ assert isinstance(result, _MessagesClient)
+ mock_httpx.assert_called_once_with(trust_env=False)
+ kwargs = mock_anthropic.call_args.kwargs
+ assert kwargs["api_key"] == AI_GATEWAY_KEY
+ assert kwargs["base_url"] == "https://ai-gateway.example"
+ headers = kwargs["default_headers"]
+ assert json.loads(headers["X-PostHog-Properties"]) == {
+ "ai_product": "warehouse_semantic_enrichment",
+ "team_id": "7",
+ }
+ assert headers["X-PostHog-Product"] == "warehouse_semantic_enrichment"
+ assert headers["X-PostHog-Trace-Id"] == team_trace_id(7)
+ # aig reads the capture identity from this header; the Messages `metadata.user_id` goes
+ # upstream to the provider instead, so without it the spend lands on the shared credential.
+ assert headers["X-PostHog-Distinct-Id"] == team_distinct_id(7)
+
+ @override_settings(AI_GATEWAY_URL="", AI_GATEWAY_API_KEY="")
+ @patch("posthog.llm.semantic_enrichment.get_llm_client")
+ def test_fallback_keeps_the_chat_completions_shape(self, mock_get_llm_client):
+ """Clearing the env must restore the pre-cutover wire behaviour, not a new route."""
+ result = build_enrichment_client("warehouse_semantic_enrichment", 7)
+
+ assert isinstance(result, _ChatClient)
+ mock_get_llm_client.assert_called_once_with(product="warehouse_semantic_enrichment", team_id=7)
+
+ @override_settings(AI_GATEWAY_URL=AI_GATEWAY_URL, AI_GATEWAY_API_KEY="")
+ @patch("posthog.llm.semantic_enrichment.get_llm_client")
+ def test_half_applied_env_falls_back_to_chat(self, mock_get_llm_client):
+ assert isinstance(build_enrichment_client("warehouse_semantic_enrichment", 7), _ChatClient)
+ mock_get_llm_client.assert_called_once()
+
+
+def _messages_response(text: str, *, stop_reason: str = "end_turn", usage: MagicMock | None = None) -> MagicMock:
+ response = MagicMock()
+ response.content = [MagicMock(type="text", text=text)]
+ response.usage = MagicMock(input_tokens=10, output_tokens=2) if usage is None else usage
+ response.stop_reason = stop_reason
+ return response
+
+
+def _chat_response(text: str | None, *, finish_reason: str = "stop") -> MagicMock:
+ response = MagicMock()
+ choice = MagicMock(finish_reason=finish_reason)
+ choice.message.content = text
+ response.choices = [choice]
+ response.usage = MagicMock(prompt_tokens=10, completion_tokens=2)
+ return response
+
+
+class TestMessagesClient:
+ def _sdk(self, response: MagicMock) -> MagicMock:
+ sdk = MagicMock()
+ sdk.messages.create.return_value = response
+ return sdk
+
+ def test_sends_a_bounded_request_and_normalises_usage(self):
+ sdk = self._sdk(_messages_response('{"columns": {"a": "desc"}}'))
+
+ completion = _MessagesClient(sdk).complete(model="m", prompt="p", temperature=0.2, team_id=7)
+
+ kwargs = sdk.messages.create.call_args.kwargs
+ assert kwargs["model"] == "m"
+ # Against the literal, not the constant, so lowering the ceiling goes red.
+ assert kwargs["max_tokens"] == 16384
+ assert MAX_OUTPUT_TOKENS == 16384
+ assert kwargs["messages"] == [{"role": "user", "content": "p"}]
+ assert kwargs["temperature"] == 0.2
+ assert kwargs["metadata"] == {"user_id": "team-7"}
+ assert completion.truncated is False
+ assert completion.max_output_tokens == 16384
+ assert completion.usage == {"model": "m", "prompt_tokens": 10, "completion_tokens": 2, "total_tokens": 12}
+
+ def test_reports_a_max_tokens_stop_as_truncated(self):
+ sdk = self._sdk(_messages_response('{"columns": ', stop_reason="max_tokens"))
+
+ assert _MessagesClient(sdk).complete(model="m", prompt="p", temperature=0.2, team_id=7).truncated is True
+
+ def test_joins_text_blocks_and_skips_other_block_types(self):
+ response = _messages_response("")
+ response.content = [
+ MagicMock(type="thinking"),
+ MagicMock(type="text", text='{"columns": '),
+ MagicMock(type="text", text='{"a": "desc"}}'),
+ ]
+
+ completion = _MessagesClient(self._sdk(response)).complete(model="m", prompt="p", temperature=0.2, team_id=7)
+
+ assert completion.text == '{"columns": {"a": "desc"}}'
+
+ def test_absent_token_counts_leave_the_total_unset(self):
+ response = _messages_response("{}", usage=MagicMock(input_tokens=None, output_tokens=None))
+
+ completion = _MessagesClient(self._sdk(response)).complete(model="m", prompt="p", temperature=0.2, team_id=7)
+
+ assert completion.usage["total_tokens"] is None
+
+
+class TestChatClient:
+ def _sdk(self, response: MagicMock) -> MagicMock:
+ sdk = MagicMock()
+ sdk.chat.completions.create.return_value = response
+ return sdk
+
+ def test_sends_the_pre_cutover_request_shape(self):
+ sdk = self._sdk(_chat_response('{"columns": {"a": "desc"}}'))
+
+ completion = _ChatClient(sdk).complete(model="m", prompt="p", temperature=0.2, team_id=7)
+
+ kwargs = sdk.chat.completions.create.call_args.kwargs
+ assert kwargs["model"] == "m"
+ assert kwargs["messages"] == [{"role": "user", "content": "p"}]
+ assert kwargs["temperature"] == 0.2
+ assert kwargs["response_format"] == {"type": "json_object"}
+ assert kwargs["user"] == "team-7"
+ assert "max_tokens" not in kwargs
+ # This leg sends no ceiling of ours, so the truncation message must not claim one.
+ assert completion.max_output_tokens is None
+ assert completion.truncated is False
+ assert completion.usage == {"model": "m", "prompt_tokens": 10, "completion_tokens": 2, "total_tokens": 12}
+
+ def test_reports_a_length_finish_as_truncated(self):
+ sdk = self._sdk(_chat_response('{"columns": ', finish_reason="length"))
+
+ assert _ChatClient(sdk).complete(model="m", prompt="p", temperature=0.2, team_id=7).truncated is True
+
+
+class TestGenerateJsonCompletion:
+ def _client(self, text: str, *, truncated: bool = False) -> MagicMock:
+ client = MagicMock()
+ client.complete.return_value = MagicMock(
+ text=text,
+ usage={"model": "claude-haiku-4-5", "prompt_tokens": 10, "completion_tokens": 2, "total_tokens": 12},
+ truncated=truncated,
+ )
+ return client
+
+ def test_resolves_a_client_and_passes_the_call_through(self):
+ client = self._client('{"columns": {"a": "desc"}}')
+ with patch("posthog.llm.semantic_enrichment.build_enrichment_client", return_value=client) as mock_build:
+ parsed, usage = generate_json_completion(product="warehouse_semantic_enrichment", team_id=7, prompt="p")
+
+ mock_build.assert_called_once_with("warehouse_semantic_enrichment", 7)
+ client.complete.assert_called_once_with(
+ model="claude-haiku-4-5", prompt="p", temperature=0.2, team_id=7, max_output_tokens=MAX_OUTPUT_TOKENS
+ )
+ assert parsed == {"columns": {"a": "desc"}}
+ assert usage["total_tokens"] == 12
+
+ def test_truncated_reply_raises_its_own_error(self):
+ """A too-small ceiling must not read as a model that cannot format JSON."""
+ client = self._client('{"columns": ', truncated=True)
+
+ with pytest.raises(TruncatedCompletionError):
+ generate_json_completion(product="warehouse_semantic_enrichment", team_id=7, prompt="p", client=client)
+
+ def test_unparseable_reply_that_was_not_truncated_raises_plain_value_error(self):
+ client = self._client("sorry, no")
+
+ with pytest.raises(ValueError) as excinfo:
+ generate_json_completion(product="warehouse_semantic_enrichment", team_id=7, prompt="p", client=client)
+
+ assert not isinstance(excinfo.value, TruncatedCompletionError)
+
+ def test_injected_client_is_used_as_is(self):
+ client = self._client("{}")
+ with patch("posthog.llm.semantic_enrichment.build_enrichment_client") as mock_build:
+ generate_json_completion(product="warehouse_semantic_enrichment", team_id=7, prompt="p", client=client)
+
+ mock_build.assert_not_called()
+
+
+class TestRoundTripThroughGenerateJsonCompletion:
+ """Drives the real client classes through the real consumer.
+
+ The class-level tests build a `_Completion` by hand, so they cannot see how the two halves fit
+ together: whether the truncation guard runs before the parse, or what the chat leg does with a
+ null content field.
+ """
+
+ def _messages_client(self, text: str, *, stop_reason: str) -> _MessagesClient:
+ sdk = MagicMock()
+ sdk.messages.create.return_value = _messages_response(text, stop_reason=stop_reason)
+ return _MessagesClient(sdk)
+
+ def _chat_client(self, content: str | None, *, finish_reason: str = "stop") -> _ChatClient:
+ sdk = MagicMock()
+ sdk.chat.completions.create.return_value = _chat_response(content, finish_reason=finish_reason)
+ return _ChatClient(sdk)
+
+ def test_truncated_reply_that_still_parses_is_rejected(self):
+ """The guard has to run before the parse: a cut-off reply whose fragment happens to close is
+ a subset of the columns asked for, and the view consumer latches its hash on any success."""
+ client = self._messages_client('{"columns": {"a": "desc"}}', stop_reason="max_tokens")
+
+ with pytest.raises(TruncatedCompletionError) as excinfo:
+ generate_json_completion(product="warehouse_semantic_enrichment", team_id=7, prompt="p", client=client)
+
+ # The message names the ceiling this leg actually sent, not a constant the other leg uses.
+ assert "16384" in str(excinfo.value)
+
+ def test_untruncated_reply_parses_normally(self):
+ client = self._messages_client('{"columns": {"a": "desc"}}', stop_reason="end_turn")
+
+ parsed, usage = generate_json_completion(
+ product="warehouse_semantic_enrichment", team_id=7, prompt="p", client=client
+ )
+
+ assert parsed == {"columns": {"a": "desc"}}
+ assert usage["total_tokens"] == 12
+
+ def test_chat_leg_null_content_raises_value_error_not_attribute_error(self):
+ """OpenAI sends content: null on a refusal or a tool call, and this leg carries all the
+ traffic until the worker env lands."""
+ client = self._chat_client(None)
+
+ # An AttributeError would propagate out of pytest.raises(ValueError) as a test error, so
+ # the raises() is what pins this; dropping `or ""` fails here with exactly that.
+ with pytest.raises(ValueError):
+ generate_json_completion(product="warehouse_semantic_enrichment", team_id=7, prompt="p", client=client)
+
+ def test_chat_leg_truncation_names_the_provider_default(self):
+ """This leg sends no ceiling of ours, so the message must not name one."""
+ client = self._chat_client('{"columns": ', finish_reason="length")
+
+ with pytest.raises(TruncatedCompletionError) as excinfo:
+ generate_json_completion(product="warehouse_semantic_enrichment", team_id=7, prompt="p", client=client)
+
+ assert "provider-default" in str(excinfo.value)
+ assert "16384" not in str(excinfo.value)
+
+
+class TestUsageNormalisation:
+ def test_one_absent_token_count_is_enough_to_leave_the_total_unset(self):
+ """Each conjunct has to be the sole reason for the outcome, or `or` weakens to `and`."""
+ sdk = MagicMock()
+ sdk.chat.completions.create.return_value = _chat_response("{}")
+ sdk.chat.completions.create.return_value.usage = MagicMock(prompt_tokens=10, completion_tokens=None)
+
+ completion = _ChatClient(sdk).complete(model="m", prompt="p", temperature=0.2, team_id=7)
+
+ assert completion.usage["total_tokens"] is None
+
+ def test_the_other_absent_count_also_leaves_it_unset(self):
+ sdk = MagicMock()
+ sdk.chat.completions.create.return_value = _chat_response("{}")
+ sdk.chat.completions.create.return_value.usage = MagicMock(prompt_tokens=None, completion_tokens=2)
+
+ completion = _ChatClient(sdk).complete(model="m", prompt="p", temperature=0.2, team_id=7)
+
+ assert completion.usage["total_tokens"] is None
+
+
+def test_the_cap_is_reachable_above_the_floor():
+ """The ceiling is sized per table now, so the old assertion that the cap covers the widest table
+ at a flat per-column rate no longer describes anything. What still has to hold is that the clamp
+ cannot invert: a floor above the cap would make `min(needed, cap)` return less than the floor the
+ estimator promises."""
+ assert MIN_OUTPUT_TOKENS < MAX_OUTPUT_TOKENS
+
+
+def test_the_output_ceiling_stays_under_the_sdk_non_streaming_limit():
+ """The other direction is the worse failure. The Anthropic SDK refuses a non-streaming call
+ whose `max_tokens` implies a timeout past its ceiling, and raises before any request goes out,
+ so overshooting takes the whole leg down rather than degrading to truncation. Raising
+ `MAX_COLUMNS_PER_TABLE` far enough would walk the floor above this bound, so pin both ends."""
+ assert MAX_OUTPUT_TOKENS <= 128_000 * 600 // 3600
+
+
+class TestMessagesTextGuards:
+ """The Messages leg is the one the cutover switches traffic onto, so its null defaults need the
+ same pinning the chat leg's `content or ""` got."""
+
+ def _completion(self, blocks: list[MagicMock]) -> _Completion:
+ sdk = MagicMock()
+ response = _messages_response("")
+ response.content = blocks
+ sdk.messages.create.return_value = response
+ return _MessagesClient(sdk).complete(model="m", prompt="p", temperature=0.2, team_id=7)
+
+ def test_a_text_block_with_no_text_contributes_nothing(self):
+ completion = self._completion([MagicMock(type="text", text=None), MagicMock(type="text", text="{}")])
+
+ assert completion.text == "{}"
+
+ def test_an_absent_content_array_yields_empty_text(self):
+ sdk = MagicMock()
+ response = _messages_response("")
+ response.content = None
+ sdk.messages.create.return_value = response
+
+ completion = _MessagesClient(sdk).complete(model="m", prompt="p", temperature=0.2, team_id=7)
+
+ assert completion.text == ""
+
+ def test_an_empty_content_array_surfaces_as_a_parse_failure(self):
+ sdk = MagicMock()
+ response = _messages_response("")
+ response.content = []
+ sdk.messages.create.return_value = response
+
+ with pytest.raises(ValueError):
+ generate_json_completion(
+ product="warehouse_semantic_enrichment", team_id=7, prompt="p", client=_MessagesClient(sdk)
+ )
+
+
+def _wide_names(count: int) -> list[str]:
+ """Distinct names at the 400-char annotation key limit, the width that outruns a flat ceiling."""
+ return [f"{i:04d}" + "c" * 396 for i in range(count)]
+
+
+class TestOutputCeilingSizing:
+ """The reply echoes every column name as a JSON key, so the ceiling has to follow the names."""
+
+ def _columns(self, names: list[str]) -> list[dict[str, str]]:
+ return [{"name": name} for name in names]
+
+ def test_long_names_need_more_than_short_ones_at_the_same_count(self):
+ short = projected_output_tokens(["a"] * 50)
+ long = projected_output_tokens(_wide_names(50))
+
+ assert long > short, "a ceiling that ignores name length truncates wide-named tables"
+
+ def test_a_full_width_table_of_long_names_outruns_the_cap(self):
+ """The case a flat ceiling gets wrong: the ask alone cannot fit, so every attempt truncates."""
+ assert projected_output_tokens(_wide_names(MAX_COLUMNS_PER_TABLE)) > MAX_OUTPUT_TOKENS
+
+ def test_bounding_drops_columns_until_the_reply_can_fit(self):
+ names = _wide_names(MAX_COLUMNS_PER_TABLE)
+ columns = self._columns(names)
+ asked: list[list[str]] = []
+
+ def builder(shown_columns, needing):
+ asked.append(needing)
+ return "prompt"
+
+ bounded = bound_prompt_over_columns(builder, columns, names)
+ prompt, ceiling = bounded.prompt, bounded.max_output_tokens
+
+ assert prompt == "prompt"
+ assert ceiling <= MAX_OUTPUT_TOKENS
+ assert len(asked[-1]) < MAX_COLUMNS_PER_TABLE, "the ask list has to shrink or the reply is cut off"
+ assert projected_output_tokens(asked[-1]) <= MAX_OUTPUT_TOKENS
+
+ def test_a_narrow_table_keeps_every_column_and_a_small_ceiling(self):
+ names = ["id", "email", "created_at"]
+ columns = self._columns(names)
+
+ bounded = bound_prompt_over_columns(lambda shown, needing: "prompt", columns, names)
+ prompt, ceiling = bounded.prompt, bounded.max_output_tokens
+
+ assert prompt == "prompt"
+ assert ceiling < MAX_OUTPUT_TOKENS, "a three-column table should not reserve the whole cap"
+
+ def test_the_sized_ceiling_reaches_the_request(self):
+ client = MagicMock()
+ client.messages.create.return_value = _messages_response('{"columns": {}}')
+
+ generate_json_completion(
+ product="warehouse_semantic_enrichment",
+ team_id=7,
+ prompt="p",
+ client=_MessagesClient(client),
+ max_output_tokens=2048,
+ )
+
+ assert client.messages.create.call_args.kwargs["max_tokens"] == 2048
+
+
+class TestDeferralContract:
+ """`deferred` is what makes the drop safe: a caller whose idempotency covers the whole object
+ reads it to decide whether it may record completion."""
+
+ def test_nothing_deferred_when_everything_fits(self):
+ names = ["id", "email", "created_at"]
+ bounded = bound_prompt_over_columns(lambda shown, needing: "prompt", [{"name": n} for n in names], names)
+
+ assert bounded.deferred == []
+ assert bounded.requested == names
+
+ def test_dropped_columns_are_reported_as_deferred(self):
+ names = _wide_names(MAX_COLUMNS_PER_TABLE)
+ bounded = bound_prompt_over_columns(lambda shown, needing: "prompt", [{"name": n} for n in names], names)
+
+ assert bounded.deferred, "a full-width table of 400-char names cannot fit one reply"
+ assert set(bounded.requested) | set(bounded.deferred) == set(names)
+ assert set(bounded.requested).isdisjoint(bounded.deferred)
+ # The ask list is what the ceiling was sized for, so the two must agree.
+ assert bounded.max_output_tokens == min(projected_output_tokens(bounded.requested), MAX_OUTPUT_TOKENS)
+
+ def test_deferred_preserves_the_callers_order(self):
+ """Callers persist or re-ask these names, so a reordering would make the retry ask for a
+ different set than the one that was dropped."""
+ names = _wide_names(MAX_COLUMNS_PER_TABLE)
+ bounded = bound_prompt_over_columns(lambda shown, needing: "prompt", [{"name": n} for n in names], names)
+
+ assert bounded.deferred == [name for name in names if name in set(bounded.deferred)]
+
+ def test_the_prompt_char_bound_also_reports_deferral(self):
+ """Both bounds drop columns, so both owe the caller the same signal."""
+ names = [f"col_{i}" for i in range(100)]
+ bounded = bound_prompt_over_columns(
+ lambda shown, needing: "x" * (len(shown) * 100),
+ [{"name": n} for n in names],
+ names,
+ max_prompt_chars=1000,
+ )
+
+ assert bounded.deferred
+ assert len(bounded.prompt) <= 1000
+
+
+class TestBatchingConverges:
+ """Batching only helps if each pass asks for something the last one could not fit. The ask list is
+ the only input that changes between batches, so the bounding has to protect it from the drop."""
+
+ def _columns(self, count: int) -> list[dict[str, str]]:
+ return [{"name": f"col_{i:03d}"} for i in range(count)]
+
+ def test_context_columns_are_dropped_before_asked_ones(self):
+ columns = self._columns(100)
+ names = [str(column["name"]) for column in columns]
+ # Ask about the tail only, so a blind tail-drop would shed exactly the asked columns.
+ asked = names[-10:]
+
+ bounded = bound_prompt_over_columns(lambda shown, needing: "x" * (len(shown) * 3000), columns, asked)
+
+ assert bounded.requested == asked, "the ask list must survive while context remains to drop"
+ assert bounded.deferred == []
+
+ def test_a_second_batch_asks_for_what_the_first_deferred(self):
+ """The regression. Dropping the tail blind made every later batch rebuild the same prompt,
+ shed the same names, and ask for nothing, so the deferred columns were never described."""
+ columns = self._columns(200)
+ names = [str(column["name"]) for column in columns]
+
+ def builder(shown, needing):
+ return "x" * (len(shown) * 3000)
+
+ first = bound_prompt_over_columns(builder, columns, names)
+ assert first.deferred, "this fixture must defer, or it is not testing batching"
+
+ second = bound_prompt_over_columns(builder, columns, first.deferred)
+
+ assert second.requested, "a batch that asks for nothing is a wasted call"
+ assert set(second.requested) <= set(first.deferred)
+ assert len(second.deferred) < len(first.deferred), "each batch must make progress"
+
+
+class TestBatchBudgetCoversTheCaps:
+ """The relationship that actually governs correctness after the ceiling became per-table: the
+ batch budget has to finish the widest table the column cap allows at the longest name the
+ annotation key permits. Nothing else pins the three constants against each other."""
+
+ def test_the_budget_finishes_the_widest_table_the_caps_allow(self):
+ names = _wide_names(MAX_COLUMNS_PER_TABLE)
+ columns = [{"name": name} for name in names]
+
+ remaining = names
+ batches = 0
+ while remaining and batches < MAX_ENRICHMENT_BATCHES:
+ bounded = bound_prompt_over_columns(lambda shown, needing: "prompt", columns, remaining)
+ assert bounded.requested, "a batch that asks for nothing spends a call for no answer"
+ remaining = bounded.deferred
+ batches += 1
+
+ assert not remaining, (
+ f"{len(remaining)} columns left after {MAX_ENRICHMENT_BATCHES} batches. "
+ f"MAX_ENRICHMENT_BATCHES={MAX_ENRICHMENT_BATCHES} no longer covers "
+ f"MAX_COLUMNS_PER_TABLE={MAX_COLUMNS_PER_TABLE} at the 400-char annotation key limit; "
+ "raise the budget or lower the column cap."
+ )
+
+ def test_the_cap_bounds_the_ceiling_even_on_the_single_column_escape(self):
+ """The loop gives up at one column. A name whose own reply cannot fit still has to declare a
+ ceiling the provider will accept, so the cap has to survive that exit."""
+ huge = "c" * 400_000
+ bounded = bound_prompt_over_columns(lambda shown, needing: "prompt", [{"name": huge}], [huge])
+
+ assert bounded.max_output_tokens == MAX_OUTPUT_TOKENS
+ assert projected_output_tokens([huge]) > MAX_OUTPUT_TOKENS, "fixture must exceed the cap"
diff --git a/products/data_modeling/backend/logic/enrich_view_semantics.py b/products/data_modeling/backend/logic/enrich_view_semantics.py
index 1c82e115b0fa..2c10ade9d60e 100644
--- a/products/data_modeling/backend/logic/enrich_view_semantics.py
+++ b/products/data_modeling/backend/logic/enrich_view_semantics.py
@@ -11,6 +11,7 @@ definition + column set is stored on the saved query so an unchanged view never
"""
import json
+import time
import asyncio
import hashlib
from typing import Any
@@ -26,9 +27,12 @@ from posthog.exceptions_capture import capture_exception
from posthog.llm.gateway_client import Product
from posthog.llm.semantic_enrichment import (
DEFAULT_ENRICHMENT_MODEL,
+ ENRICHMENT_BATCH_BUDGET_SECONDS,
MAX_BUSINESS_CONTEXT_CHARS,
MAX_COLUMNS_PER_TABLE,
+ MAX_ENRICHMENT_BATCHES,
MAX_PROMPT_CHARS,
+ BoundedPrompt,
bound_prompt_over_columns,
collapse_untrusted,
generate_json_completion,
@@ -281,8 +285,12 @@ def build_bounded_view_enrichment_prompt(
known_descriptions: dict[str, str],
columns_needing_description: list[str],
business_context: str,
-) -> str:
- """Build the view prompt, capping the unbounded free-text inputs and trimming columns to fit the window."""
+) -> BoundedPrompt:
+ """Build the view prompt, capping the unbounded free-text inputs and trimming columns to fit the window.
+
+ The result carries the columns it had to defer; this surface records enrichment per view rather
+ than per column, so the caller must not store the hash while any are outstanding.
+ """
business_context = business_context[:MAX_BUSINESS_CONTEXT_CHARS]
if len(query_definition) > MAX_VIEW_DEFINITION_CHARS:
# Signal the cut so the model treats the SQL as partial, not the whole definition.
@@ -371,46 +379,92 @@ def enrich_view_semantics_sync(team_id: int, saved_query_id: str) -> dict[str, A
view_row = existing.get("")
view_needs_description = not (view_row and view_row.is_user_edited)
+ # Columns past the per-pass cap are never asked about. The cap is deterministic, so a retry cannot
+ # reach them and withholding the hash would repeat the same pass forever; logged instead.
+ over_cap = [
+ column["name"]
+ for column in all_columns[MAX_COLUMNS_PER_TABLE:]
+ if not (existing.get(column["name"]) and existing[column["name"]].is_user_edited)
+ ]
+
ai_count = 0
+ unfinished: list[str] = []
if columns_needing_description or view_needs_description:
business_context = get_team_business_context(team)
lineage = _gather_lineage(team, saved_query, query_str)
# Only sample a materialized view — running the raw view query for an unmaterialized one is unbounded.
row_sample = _get_row_sample(saved_query) if _has_sampleable_rows(saved_query) else []
- prompt = build_bounded_view_enrichment_prompt(
- view_name=saved_query.name,
- query_definition=query_str,
- columns=columns,
- lineage=lineage,
- row_sample=row_sample,
- known_descriptions=known_descriptions,
- columns_needing_description=columns_needing_description,
- business_context=business_context,
- )
- log.info("view_enrichment.llm_call_started", columns_requested=len(columns_needing_description))
- try:
- generated, usage = generate_json_completion(
- product=GATEWAY_PRODUCT, team_id=team_id, prompt=prompt, model=DEFAULT_ENRICHMENT_MODEL
+
+ # Batched rather than dropping the tail: enrichment is recorded per view, so a dropped column is
+ # latched as done by the hash below. A later pass cannot recover it either, because only
+ # user-edited columns leave the ask list, so the same tail would drop again.
+ remaining = columns_needing_description
+ wants_view_description = view_needs_description
+ batch_deadline = time.monotonic() + ENRICHMENT_BATCH_BUDGET_SECONDS
+ batch_number = 0
+ # The view-level description still needs one call when every column is user-edited, so an
+ # empty ask list is not on its own a reason to skip the first batch.
+ while (remaining or wants_view_description) and batch_number < MAX_ENRICHMENT_BATCHES:
+ # The first call always runs, so batching cannot push this activity past a deadline one
+ # call would have met. Later batches yield to the clock and leave the rest for the retry.
+ if batch_number and time.monotonic() > batch_deadline:
+ log.info("view_enrichment.batch_budget_exhausted", columns_remaining=len(remaining))
+ break
+ batch_number += 1
+ bounded = build_bounded_view_enrichment_prompt(
+ view_name=saved_query.name,
+ query_definition=query_str,
+ columns=columns,
+ lineage=lineage,
+ row_sample=row_sample,
+ known_descriptions=known_descriptions,
+ columns_needing_description=remaining,
+ business_context=business_context,
+ )
+ if not bounded.requested and not wants_view_description:
+ # Nothing fit even after context was dropped first, so another identical call buys
+ # nothing. Backstop only; the loop condition covers the ordinary exit.
+ break
+ log.info(
+ "view_enrichment.llm_call_started",
+ columns_requested=len(bounded.requested),
+ columns_remaining=len(bounded.deferred),
)
- except Exception as e:
- capture_exception(e)
- log.error("view_enrichment.llm_failed", error=str(e), exc_info=True)
- # Don't store the hash — the next trigger retries.
- return {"status": "partial", "ai_annotations": 0, "error": "llm_failed"}
-
- log.info("view_enrichment.llm_call", columns_requested=len(columns_needing_description), **usage)
-
- generated_columns = generated.get("columns") or {}
- if isinstance(generated_columns, dict):
- for column_name in columns_needing_description:
- description = generated_columns.get(column_name)
- if isinstance(description, str) and description.strip():
- _upsert(saved_query, team_id, column_name, description.strip())
- ai_count += 1
-
- view_description = generated.get("view_description")
- if view_needs_description and isinstance(view_description, str) and view_description.strip():
- _upsert(saved_query, team_id, "", view_description.strip())
+ try:
+ generated, usage = generate_json_completion(
+ product=GATEWAY_PRODUCT,
+ team_id=team_id,
+ prompt=bounded.prompt,
+ model=DEFAULT_ENRICHMENT_MODEL,
+ max_output_tokens=bounded.max_output_tokens,
+ )
+ except Exception as e:
+ capture_exception(e)
+ log.error("view_enrichment.llm_failed", error=str(e), exc_info=True)
+ # Don't store the hash, so the next trigger retries. Any earlier batch's annotations
+ # are already persisted and are simply re-drafted then.
+ return {"status": "partial", "ai_annotations": ai_count, "error": "llm_failed"}
+
+ log.info("view_enrichment.llm_call", columns_requested=len(bounded.requested), **usage)
+
+ generated_columns = generated.get("columns") or {}
+ if isinstance(generated_columns, dict):
+ for column_name in bounded.requested:
+ description = generated_columns.get(column_name)
+ if isinstance(description, str) and description.strip():
+ _upsert(saved_query, team_id, column_name, description.strip())
+ ai_count += 1
+
+ if wants_view_description:
+ view_description = generated.get("view_description")
+ if isinstance(view_description, str) and view_description.strip():
+ _upsert(saved_query, team_id, "", view_description.strip())
+ # Cleared whether or not the model answered: the next batch carries the same definition,
+ # so re-asking cannot produce what this reply withheld, and would burn the budget.
+ wants_view_description = False
+
+ remaining = bounded.deferred
+ unfinished = remaining
# Drop non-user-edited annotations for columns that no longer exist; keep user edits and the view row.
stale = [
@@ -424,13 +478,20 @@ def enrich_view_semantics_sync(team_id: int, saved_query_id: str) -> dict[str, A
).delete()
# Store the hash via queryset update() — bypasses post_save so it never re-triggers the signal.
- DataWarehouseSavedQuery.objects.filter(id=saved_query.id).update(semantic_enrichment_hash=current_hash)
+ # Withheld only for columns still unasked when the budget ran out: the hash short-circuits the next
+ # run. `over_cap` is exempt, since a deterministic cap makes the retry repeat the same pass.
+ if not unfinished:
+ DataWarehouseSavedQuery.objects.filter(id=saved_query.id).update(semantic_enrichment_hash=current_hash)
log.info(
"view_enrichment.done",
ai=ai_count,
stale_deleted=len(stale),
llm_called=bool(columns_needing_description or view_needs_description),
+ unfinished=len(unfinished),
+ over_cap=len(over_cap),
)
+ if unfinished:
+ return {"status": "partial", "ai_annotations": ai_count, "unfinished_columns": len(unfinished)}
return {"status": "done", "ai_annotations": ai_count}
diff --git a/products/data_modeling/backend/tests/test_enrich_view_semantics.py b/products/data_modeling/backend/tests/test_enrich_view_semantics.py
index e5dfa532a1f1..494eeffe18d4 100644
--- a/products/data_modeling/backend/tests/test_enrich_view_semantics.py
+++ b/products/data_modeling/backend/tests/test_enrich_view_semantics.py
@@ -6,6 +6,7 @@ from unittest.mock import patch
from parameterized import parameterized
+from posthog.llm.semantic_enrichment import MAX_OUTPUT_TOKENS
from posthog.models import Organization, Team
from posthog.models.scoping.manager import TeamScopedQuerySet
@@ -87,6 +88,168 @@ class TestEnrichViewSemanticsSync:
sq.refresh_from_db()
assert sq.semantic_enrichment_hash == compute_enrichment_hash(sq)
+ def test_an_ordinary_view_is_finished_in_one_call(self):
+ """Pins the ordinary path to a single call. Batching is for views the ceiling cannot hold; if
+ the loop's exit condition were deleted every view would spend the whole batch budget, which
+ no other test here would notice."""
+ team = _team()
+ sq = _saved_query(team, columns=_columns("amount", "status"))
+ generated = {"view_description": "v", "columns": {"amount": "a", "status": "s"}}
+
+ result, mock_llm = _run(team, sq, generated=generated)
+
+ assert mock_llm.call_count == 1
+ assert result["status"] == "done"
+
+ def test_a_reply_without_a_view_description_does_not_spend_another_batch(self):
+ """The view description is asked for once. Re-asking carries the same definition, so a reply
+ that omitted it will omit it again, and looping on that would burn the budget."""
+ team = _team()
+ sq = _saved_query(team, columns=_columns("amount"))
+ generated = {"columns": {"amount": "a"}}
+
+ result, mock_llm = _run(team, sq, generated=generated)
+
+ assert mock_llm.call_count == 1
+ assert result["status"] == "done"
+ assert "" not in _annotations(team, sq)
+
+ def test_a_wide_view_is_finished_in_batches_rather_than_losing_columns(self):
+ """The fix. The output ceiling cannot hold every column of a wide view in one reply, and this
+ surface records enrichment per view, so a dropped column would be latched as described and
+ never come back. Finishing the remainder in a second call is what keeps the hash honest."""
+ team = _team()
+ names = [f"c{i:04d}" for i in range(enrich.MAX_COLUMNS_PER_TABLE)]
+ sq = _saved_query(team, columns=_columns(*names))
+ generated = {"view_description": "v", "columns": {name: f"desc {name}" for name in names}}
+
+ result, mock_llm = _run(team, sq, generated=generated)
+
+ assert mock_llm.call_count > 1, "a full-width view does not fit one reply, so it must batch"
+ assert result["status"] == "done"
+ annotations = _annotations(team, sq)
+ assert set(annotations) == {*names, ""}, "every column described, plus the view row"
+ sq.refresh_from_db()
+ assert sq.semantic_enrichment_hash == compute_enrichment_hash(sq)
+
+ def test_columns_past_the_cap_are_not_described_and_the_view_still_settles(self):
+ """Documents an acknowledged gap rather than asserting it is fine. Columns past the per-pass
+ cap are never asked about, and the hash IS stored for them: the cap is deterministic, so a
+ retry would repeat the same pass, and withholding would re-run forever. If that trade is ever
+ revisited, this test is what changes."""
+ team = _team()
+ names = [f"c{i:04d}" for i in range(enrich.MAX_COLUMNS_PER_TABLE + 25)]
+ sq = _saved_query(team, columns=_columns(*names))
+ generated = {"view_description": "v", "columns": {name: f"desc {name}" for name in names}}
+
+ result, _ = _run(team, sq, generated=generated)
+
+ assert result["status"] == "done"
+ described = {name for name in _annotations(team, sq) if name}
+ assert len(described) == enrich.MAX_COLUMNS_PER_TABLE
+ assert not described & set(names[enrich.MAX_COLUMNS_PER_TABLE :])
+ sq.refresh_from_db()
+ assert sq.semantic_enrichment_hash == compute_enrichment_hash(sq)
+
+ def test_the_wall_clock_budget_stops_after_the_first_batch(self):
+ """Pins the deadline. With no budget left, the first call still runs, because batching must
+ never make a caller worse off than the single call it replaced; the rest yield to the clock
+ and the hash stays unstored. Deleting the guard, its first-call exemption, or its log left
+ every other test green."""
+ team = _team()
+ names = [f"c{i:04d}" for i in range(enrich.MAX_COLUMNS_PER_TABLE)]
+ sq = _saved_query(team, columns=_columns(*names))
+ generated = {"view_description": "v", "columns": {name: f"desc {name}" for name in names}}
+
+ with patch.object(enrich, "ENRICHMENT_BATCH_BUDGET_SECONDS", 0.0):
+ result, mock_llm = _run(team, sq, generated=generated)
+
+ assert mock_llm.call_count == 1, "the first batch is exempt; a spent budget must not skip it"
+ assert result["status"] == "partial"
+ assert result["unfinished_columns"] > 0
+ sq.refresh_from_db()
+ assert not sq.semantic_enrichment_hash
+
+ def test_a_generous_budget_does_not_stop_a_converging_run(self):
+ """The other side of the same guard: a run that fits inside the budget is not cut short."""
+ team = _team()
+ names = [f"c{i:04d}" for i in range(enrich.MAX_COLUMNS_PER_TABLE)]
+ sq = _saved_query(team, columns=_columns(*names))
+ generated = {"view_description": "v", "columns": {name: f"desc {name}" for name in names}}
+
+ with patch.object(enrich, "ENRICHMENT_BATCH_BUDGET_SECONDS", 3600.0):
+ result, mock_llm = _run(team, sq, generated=generated)
+
+ assert mock_llm.call_count > 1
+ assert result["status"] == "done"
+
+ def test_the_hash_is_withheld_when_the_batch_budget_runs_out(self):
+ """Pins the withhold itself. Batching normally finishes the job, so unless the budget is
+ forced to run out this guard never decides anything and could be deleted unnoticed while
+ every other test stays green."""
+ team = _team()
+ names = [f"c{i:04d}" for i in range(enrich.MAX_COLUMNS_PER_TABLE)]
+ sq = _saved_query(team, columns=_columns(*names))
+ generated = {"view_description": "v", "columns": {name: f"desc {name}" for name in names}}
+
+ with patch.object(enrich, "MAX_ENRICHMENT_BATCHES", 1):
+ result, mock_llm = _run(team, sq, generated=generated)
+
+ assert mock_llm.call_count == 1
+ assert result["status"] == "partial"
+ assert result["unfinished_columns"] > 0
+ sq.refresh_from_db()
+ assert not sq.semantic_enrichment_hash, "an unfinished view must not be latched as enriched"
+
+ def test_the_view_description_is_asked_for_once_across_batches(self):
+ team = _team()
+ names = [f"c{i:04d}" for i in range(enrich.MAX_COLUMNS_PER_TABLE)]
+ sq = _saved_query(team, columns=_columns(*names))
+ generated = {"view_description": "v", "columns": {name: f"desc {name}" for name in names}}
+
+ _result, mock_llm = _run(team, sq, generated=generated)
+
+ assert mock_llm.call_count > 1
+ assert _annotations(team, sq)[""].description == "v"
+
+ def test_a_failure_mid_batch_keeps_the_earlier_work_and_withholds_the_hash(self):
+ """Annotations are per-column upserts, so a later batch failing must not discard an earlier
+ batch's descriptions, and the hash must stay unstored so the next trigger finishes the job."""
+ team = _team()
+ names = [f"c{i:04d}" for i in range(enrich.MAX_COLUMNS_PER_TABLE)]
+ sq = _saved_query(team, columns=_columns(*names))
+ generated = {"view_description": "v", "columns": {name: f"desc {name}" for name in names}}
+
+ with (
+ patch.object(enrich, "get_team_business_context", return_value=""),
+ patch.object(enrich, "_gather_lineage", return_value=[]),
+ patch.object(enrich, "_get_row_sample", return_value=[]),
+ patch.object(
+ enrich,
+ "generate_json_completion",
+ side_effect=[(generated, _USAGE), RuntimeError("provider down")],
+ ),
+ ):
+ result = enrich_view_semantics_sync(team.pk, str(sq.id))
+
+ assert result["status"] == "partial"
+ assert result["error"] == "llm_failed"
+ assert result["ai_annotations"] > 0, "the first batch's columns are already persisted"
+ sq.refresh_from_db()
+ assert not sq.semantic_enrichment_hash
+
+ def test_the_bounded_ceiling_reaches_the_request(self):
+ """Pins the hand-off on this surface: without it the `max_output_tokens=` argument can be
+ deleted here with the suite green, restoring the flat cap."""
+ team = _team()
+ sq = _saved_query(team, columns=_columns("amount", "status"))
+ generated = {"view_description": "v", "columns": {"amount": "a", "status": "s"}}
+
+ _result, mock_llm = _run(team, sq, generated=generated)
+
+ sent = mock_llm.call_args.kwargs["max_output_tokens"]
+ assert sent < MAX_OUTPUT_TOKENS, "a two-column view must not reserve the whole cap"
+
def test_unchanged_view_skips_without_calling_llm(self):
team = _team()
sq = _saved_query(team, columns=_columns("amount"))
@@ -250,7 +413,7 @@ class TestBuildViewEnrichmentPrompt:
known_descriptions={},
columns_needing_description=[str(c["name"]) for c in columns],
business_context="",
- )
+ ).prompt
assert len(prompt) <= MAX_PROMPT_CHARS
assert str(columns[0]["name"]) in prompt
assert str(columns[-1]["name"]) not in prompt
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/enrich_table_semantics.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/enrich_table_semantics.py
index 9ac45a385a5c..04dc5bd799f6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/enrich_table_semantics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/enrich_table_semantics.py
@@ -27,13 +27,14 @@ from temporalio import activity, workflow
from temporalio.common import RetryPolicy
from posthog.exceptions_capture import capture_exception
-from posthog.llm.gateway_client import get_llm_client
from posthog.llm.semantic_enrichment import (
DEFAULT_ENRICHMENT_MODEL,
MAX_BUSINESS_CONTEXT_CHARS,
MAX_COLUMNS_PER_TABLE,
MAX_PROMPT_CHARS,
+ BoundedPrompt,
bound_prompt_over_columns,
+ build_enrichment_client,
capture_enrichment_event,
collapse_untrusted,
enrichment_enabled as _shared_enrichment_enabled,
@@ -182,7 +183,7 @@ def build_bounded_enrichment_prompt(
known_descriptions: dict[str, str],
columns_needing_description: list[str],
business_context: str,
-) -> str:
+) -> BoundedPrompt:
"""Build the prompt, trimming inputs so it can't exceed the model's context window.
The business context (the team's core memory) is unbounded free text and is the usual culprit
@@ -230,7 +231,7 @@ def _generate_descriptions(
business_context: str,
) -> tuple[dict[str, Any], dict[str, Any]]:
"""Call the LLM. Returns `(parsed_payload, usage)` — usage carries the model and token counts."""
- prompt = build_bounded_enrichment_prompt(
+ bounded = build_bounded_enrichment_prompt(
source_name=source_name,
table_name=table_name,
endpoint_name=endpoint_name,
@@ -241,15 +242,23 @@ def _generate_descriptions(
columns_needing_description=columns_needing_description,
business_context=business_context,
)
- # Resolve the client through this module's get_llm_client so the existing test seam keeps working,
- # then hand it to the shared JSON completion.
- client = get_llm_client(product="warehouse_semantic_enrichment", team_id=team_id)
+ # Resolved here so this module exposes a seam the activity tests can patch.
+ client = build_enrichment_client("warehouse_semantic_enrichment", team_id)
+ if bounded.deferred:
+ # Per-column annotation rows are the idempotency record here, so a deferred column is still
+ # unannotated and the next sync asks for it. Logged because the event reports only the ask.
+ logger.info(
+ "Deferred columns to a later enrichment pass to fit the request bounds",
+ deferred_columns=len(bounded.deferred),
+ requested_columns=len(bounded.requested),
+ )
return generate_json_completion(
product="warehouse_semantic_enrichment",
team_id=team_id,
- prompt=prompt,
+ prompt=bounded.prompt,
model=ENRICHMENT_MODEL,
client=client,
+ max_output_tokens=bounded.max_output_tokens,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_enrich_table_semantics.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_enrich_table_semantics.py
index 2db1155ecb6f..77a930822b44 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_enrich_table_semantics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_enrich_table_semantics.py
@@ -7,6 +7,7 @@ from unittest.mock import MagicMock, patch
from temporalio.testing import ActivityEnvironment
+from posthog.llm.semantic_enrichment import MAX_OUTPUT_TOKENS, TruncatedCompletionError
from posthog.models import Organization, Team
from posthog.models.scoping.manager import TeamScopedQuerySet
@@ -228,7 +229,7 @@ class TestBuildBoundedEnrichmentPrompt:
known_descriptions={},
columns_needing_description=[c["name"] for c in columns],
business_context="short context",
- )
+ ).prompt
assert len(prompt) <= MAX_PROMPT_CHARS
for column in columns:
assert column["name"] in prompt
@@ -247,7 +248,7 @@ class TestBuildBoundedEnrichmentPrompt:
known_descriptions={},
columns_needing_description=["col_0", "col_1"],
business_context=huge_context,
- )
+ ).prompt
assert len(prompt) <= MAX_PROMPT_CHARS
# The 100k-char context is truncated to the cap (a few stray "x" elsewhere in the template are fine).
assert MAX_BUSINESS_CONTEXT_CHARS <= prompt.count("x") < MAX_BUSINESS_CONTEXT_CHARS + 100
@@ -268,7 +269,7 @@ class TestBuildBoundedEnrichmentPrompt:
known_descriptions={},
columns_needing_description=[c["name"] for c in columns],
business_context="",
- )
+ ).prompt
assert len(prompt) <= MAX_PROMPT_CHARS
# The first column survives; some tail columns are dropped to stay under budget.
assert columns[0]["name"] in prompt
@@ -295,7 +296,7 @@ class TestBuildBoundedEnrichmentPrompt:
known_descriptions={},
columns_needing_description=[str(c["name"]) for c in columns],
business_context="",
- )
+ ).prompt
assert len(prompt) <= MAX_PROMPT_CHARS
# The surviving column's FK stays; the dropped column's FK is gone.
assert "kept_target" in prompt
@@ -340,8 +341,8 @@ class TestExtractJsonObject:
],
)
def test_extracts_object_from_fenced_or_wrapped_replies(self, content):
- # The gateway's Anthropic route doesn't reliably honour json_object mode, so replies arrive
- # fenced or with prose — all must still yield the parsed object.
+ # A caller that asks for JSON in the prompt can get it fenced or with prose, and it must
+ # still parse.
parsed = _extract_json_object(content)
assert parsed == {"table_description": "t", "columns": {"a": "desc"}}
@@ -351,12 +352,14 @@ class TestExtractJsonObject:
class TestGenerateDescriptions:
- def _response(self, content: str | None) -> MagicMock:
- response = MagicMock()
- response.choices = [MagicMock()]
- response.choices[0].message.content = content
- response.usage = MagicMock(prompt_tokens=1, completion_tokens=0, total_tokens=1)
- return response
+ def _client(self, content: str | None, *, truncated: bool = False) -> MagicMock:
+ client = MagicMock()
+ client.complete.return_value = MagicMock(
+ text=content or "",
+ usage={"model": "m", "prompt_tokens": 1, "completion_tokens": 0, "total_tokens": 1},
+ truncated=truncated,
+ )
+ return client
def _call(self) -> tuple[dict, dict]:
return enrich._generate_descriptions(
@@ -375,19 +378,67 @@ class TestGenerateDescriptions:
@pytest.mark.parametrize("content", [None, "", " ", "not json", "```\nnope\n```"])
def test_raises_on_unparseable_response(self, content):
# An empty or non-JSON reply must surface as an error (→ "partial"), not silently persist nothing.
- client = MagicMock()
- client.chat.completions.create.return_value = self._response(content)
- with patch.object(enrich, "get_llm_client", return_value=client):
+ with patch.object(enrich, "build_enrichment_client", return_value=self._client(content)):
with pytest.raises(ValueError):
self._call()
+ def test_truncated_response_raises_the_truncation_error(self):
+ # A cut-off reply is its own failure class, so an undersized ceiling stays visible in analytics.
+ client = self._client('{"columns": ', truncated=True)
+ with patch.object(enrich, "build_enrichment_client", return_value=client):
+ with pytest.raises(TruncatedCompletionError):
+ self._call()
+
def test_parses_fenced_response(self):
- client = MagicMock()
- client.chat.completions.create.return_value = self._response('```json\n{"columns": {"a": "desc"}}\n```')
- with patch.object(enrich, "get_llm_client", return_value=client):
+ client = self._client('```json\n{"columns": {"a": "desc"}}\n```')
+ with patch.object(enrich, "build_enrichment_client", return_value=client):
parsed, _usage = self._call()
assert parsed == {"columns": {"a": "desc"}}
+ def test_the_bounded_ceiling_reaches_the_request(self):
+ """Pins the hand-off, not the sizing. The ceiling is computed in the shared helper and pinned
+ there; without this the `max_output_tokens=` argument below can be deleted on this surface
+ with the whole suite green, silently restoring the flat cap the sizing exists to replace."""
+ client = self._client('{"columns": {"a": "desc"}}')
+ with patch.object(enrich, "build_enrichment_client", return_value=client):
+ self._call()
+
+ sent = client.complete.call_args.kwargs["max_output_tokens"]
+ expected = enrich.build_bounded_enrichment_prompt(
+ source_name="Stripe",
+ table_name="t",
+ endpoint_name="Charge",
+ docs_url=None,
+ columns=[{"name": "a", "data_type": "String", "is_nullable": False}],
+ foreign_keys=[],
+ known_descriptions={},
+ columns_needing_description=["a"],
+ business_context="",
+ ).max_output_tokens
+ assert sent == expected
+ assert sent < MAX_OUTPUT_TOKENS, "a one-column table must not reserve the whole cap"
+
+ def test_a_deferred_column_is_reported_for_a_later_pass(self):
+ """Warehouse idempotency is per annotation row, so a deferred column is simply still
+ unannotated and the next sync asks for it. Pinned so the deferral stays observable."""
+ columns = [{"name": f"c{i:03d}" + "x" * 396, "data_type": "String", "is_nullable": False} for i in range(200)]
+ bounded = enrich.build_bounded_enrichment_prompt(
+ source_name="Stripe",
+ table_name="t",
+ endpoint_name="Charge",
+ docs_url=None,
+ columns=columns,
+ foreign_keys=[],
+ known_descriptions={},
+ columns_needing_description=[str(column["name"]) for column in columns],
+ business_context="",
+ )
+
+ assert bounded.deferred, "a 200-column table of 400-char names cannot fit one reply"
+ assert set(bounded.requested).isdisjoint(bounded.deferred)
+ assert len(bounded.requested) + len(bounded.deferred) == len(columns)
+ assert bounded.max_output_tokens <= MAX_OUTPUT_TOKENS
+
class TestCanonicalDescriptionsResolver:
def test_stripe_ships_canonical_descriptions(self):