:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(aio): bound batch summarization input to a cost-conscious ceiling (#91297)
posthog[bot]c429955b6134
diff --git a/posthog/temporal/ai_observability/trace_summarization/README.md b/posthog/temporal/ai_observability/trace_summarization/README.mdindex 3eb5686410b0..c59ebc9eaa3a 100644--- a/posthog/temporal/ai_observability/trace_summarization/README.md+++ b/posthog/temporal/ai_observability/trace_summarization/README.md@@ -154,6 +154,12 @@ Key constants in `constants.py`:Retry policies: `SAMPLE_RETRY_POLICY` (5 attempts with backoff), `FETCH_AND_FORMAT_RETRY_POLICY` (2 attempts), `SUMMARIZE_AND_SAVE_RETRY_POLICY` (2 attempts with backoff, `TextReprExpiredError` non-retryable), `COORDINATOR_CHILD_WORKFLOW_RETRY_POLICY` (1 attempt). All retry policies exclude `ValueError` and `TypeError` from retries.+The text representation handed to the model is capped by `batch_text_repr_budget` (see `products/ai_observability/backend/summarization/budget.py`).+The batch job runs unattended over every team's traces, so its context size drives a recurring bill.+The cap holds the input near a cost-conscious ceiling instead of the model's full context window, which never bounds a typical trace.+Oversized trace text is reduced by uniform line sampling before the LLM call.+Oversized generation text splits the budget between the input and output sections, so a large input never drops the output section.+Sampling keeps ClickHouse capacity errors retryable deliberately: each run covers a disjoint wall-clock window with no persisted cursor, so a run that gives up loses that hour of traces for that team permanently.Concurrency is bounded centrally by `CLICKHOUSE_LLM_ANALYTICS_MAX_CONCURRENT_QUERIES`, not by this workflow's fan-out, because trace clustering and eval reports draw on the same budget.diff --git a/posthog/temporal/ai_observability/trace_summarization/fetch_and_format.py b/posthog/temporal/ai_observability/trace_summarization/fetch_and_format.pyindex b1c19dc88304..c486b209c691 100644--- a/posthog/temporal/ai_observability/trace_summarization/fetch_and_format.py+++ b/posthog/temporal/ai_observability/trace_summarization/fetch_and_format.py@@ -9,6 +9,7 @@ from posthog.hogql import astfrom posthog.hogql.parser import parse_selectfrom posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.dataclasses import frozenfrom posthog.hogql_queries.ai.ai_table_resolver import query_ai_eventsfrom posthog.models.team import Teamfrom posthog.redis import get_async_client@@ -121,15 +122,22 @@ def _fetch_and_format_generation(# Query the dedicated table first; the resolver rewrites + re-runs against the# shared `events` table when ai_events returns zero rows (data beyond the- # retention window). Heavy columns (`input`, `output`) live only as native- # columns on ai_events, so only this path can recover them for recent rows.+ # retention window). Heavy columns (`input`, `output`, `output_choices`) live+ # only as native columns on ai_events, so only this path can recover them for+ # recent rows.+ # Chat-format SDK calls (most OpenAI/Anthropic) record the result in `$ai_output_choices`+ # and leave `$ai_output` empty. Read choices first, the same precedence the canonical+ # formatter uses (`format_output_messages`).query = parse_select("""SELECTmodel,provider,input,- output,+ coalesce(+ nullIf(output_choices, ''),+ output+ ) as output,input_tokens,output_tokens,latency@@ -171,25 +179,89 @@ def _fetch_and_format_generation("latency": row[6],}- text_repr = _format_generation_text_repr(generation_dict)-- if max_length and len(text_repr) > max_length:- text_repr = text_repr[:max_length] + "\n... [truncated]"+ text_repr = _format_generation_text_repr(generation_dict, max_length=max_length)return FetchResult(text_repr=text_repr, event_count=1)-def _format_generation_text_repr(generation_data: dict) -> str:- """Format a generation event into a text representation for LLM summarization."""- parts = []+GENERATION_SECTION_TRUNCATION_MARKER = "\n... [truncated] ...\n"+++def _render_generation_messages(content: object) -> str:+ """Render a generation's input or output messages into a text block.++ Returns an empty string when there is no content, so the caller drops the whole section.+ """+ if not content:+ return ""+ if isinstance(content, list):+ return "\n".join(f"[{msg.get('role', 'unknown')}]: {msg.get('content', '')}" for msg in content)+ return str(content)+++def _truncate_section(text: str, budget: int) -> str:+ """Truncate one section's text to at most `budget` characters, marking the cut.++ Keeps the head and the tail with the marker between them, because both ends matter:+ the head carries the system prompt and the tail carries the newest messages.+ """+ if budget <= 0:+ return ""+ if len(text) <= budget:+ return text+ keep = budget - len(GENERATION_SECTION_TRUNCATION_MARKER)+ if keep <= 0:+ return text[:budget]+ tail = keep // 2+ head = keep - tail+ return text[:head] + GENERATION_SECTION_TRUNCATION_MARKER + text[len(text) - tail :]+++@frozen+class _BudgetedSections:+ """A generation's input and output blocks after sharing the character budget."""++ input_block: str+ output_block: str+- parts.append("=== LLM Generation Event ===")- parts.append("")+def _split_section_budget(input_block: str, output_block: str, budget: int) -> _BudgetedSections:+ """Split `budget` characters between the input and output blocks.++ A block that already fits gives its slack to the other, so the full budget is used. When both+ are oversized, each keeps half. The output block is never dropped to fit a large input, because+ a summary that describes only the prompt and omits the model result is close to useless for+ clustering and search.+ """+ if len(input_block) + len(output_block) <= budget:+ return _BudgetedSections(input_block=input_block, output_block=output_block)+ half = budget // 2+ if len(input_block) <= half:+ return _BudgetedSections(+ input_block=input_block, output_block=_truncate_section(output_block, budget - len(input_block))+ )+ if len(output_block) <= half:+ return _BudgetedSections(+ input_block=_truncate_section(input_block, budget - len(output_block)), output_block=output_block+ )+ return _BudgetedSections(+ input_block=_truncate_section(input_block, half), output_block=_truncate_section(output_block, budget - half)+ )+++def _format_generation_text_repr(generation_data: dict, max_length: int | None = None) -> str:+ """Format a generation event into a text representation for LLM summarization.++ When `max_length` is set, the input and output sections share the budget so a large input+ cannot push the output section out entirely. Both sections stay represented, each truncated to+ its share.+ """+ header_parts = ["=== LLM Generation Event ===", ""]if generation_data.get("model"):- parts.append(f"Model: {generation_data['model']}")+ header_parts.append(f"Model: {generation_data['model']}")if generation_data.get("provider"):- parts.append(f"Provider: {generation_data['provider']}")+ header_parts.append(f"Provider: {generation_data['provider']}")input_tokens = generation_data.get("input_tokens")output_tokens = generation_data.get("output_tokens")@@ -199,38 +271,34 @@ def _format_generation_text_repr(generation_data: dict) -> str:tokens_str.append(f"input={input_tokens}")if output_tokens is not None:tokens_str.append(f"output={output_tokens}")- parts.append(f"Tokens: {', '.join(tokens_str)}")+ header_parts.append(f"Tokens: {', '.join(tokens_str)}")latency = generation_data.get("latency")if latency is not None:- parts.append(f"Latency: {latency:.2f}s")-- parts.append("")-- input_content = generation_data.get("input")- if input_content:- parts.append("--- Input ---")- if isinstance(input_content, list):- for msg in input_content:- role = msg.get("role", "unknown")- content = msg.get("content", "")- parts.append(f"[{role}]: {content}")- else:- parts.append(str(input_content))- parts.append("")-- output_content = generation_data.get("output")- if output_content:- parts.append("--- Output ---")- if isinstance(output_content, list):- for msg in output_content:- role = msg.get("role", "unknown")- content = msg.get("content", "")- parts.append(f"[{role}]: {content}")- else:- parts.append(str(output_content))-- return "\n".join(parts)+ header_parts.append(f"Latency: {latency:.2f}s")++ header_parts.append("")++ input_block = _render_generation_messages(generation_data.get("input"))+ output_block = _render_generation_messages(generation_data.get("output"))++ def assemble(in_block: str, out_block: str) -> str:+ parts = list(header_parts)+ if in_block:+ parts.extend(("--- Input ---", in_block, ""))+ if out_block:+ parts.extend(("--- Output ---", out_block))+ return "\n".join(parts)++ text_repr = assemble(input_block, output_block)+ if max_length is None or len(text_repr) <= max_length:+ return text_repr++ # `overhead` is the header, section markers, and blank lines, so the split budgets only the+ # two content blocks and the reassembled text stays within `max_length`.+ overhead = len(text_repr) - len(input_block) - len(output_block)+ sections = _split_section_budget(input_block, output_block, max(max_length - overhead, 0))+ return assemble(sections.input_block, sections.output_block)@temporalio.activity.defndiff --git a/posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format.py b/posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format.pyindex c7b5cc12e2e3..8f31e09e2544 100644--- a/posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format.py+++ b/posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format.py@@ -67,6 +67,32 @@ class TestFormatGenerationTextRepr:assert "Provider:" not in resultassert "Tokens:" not in result+ def test_oversized_input_keeps_output_section(self):+ generation_data = {+ "model": "gpt-4",+ "input": "x" * 5000,+ "output": "DISTINCTIVE_OUTPUT_MARKER",+ }++ result = _format_generation_text_repr(generation_data, max_length=1000)++ assert len(result) <= 1000+ assert "--- Output ---" in result+ assert "DISTINCTIVE_OUTPUT_MARKER" in result++ def test_truncated_input_keeps_head_and_tail(self):+ generation_data = {+ "input": "SYSTEM_PROMPT_HEAD " + "x" * 5000 + " NEWEST_MESSAGE_TAIL",+ "output": "short",+ }++ result = _format_generation_text_repr(generation_data, max_length=1000)++ assert len(result) <= 1000+ assert "SYSTEM_PROMPT_HEAD" in result+ assert "NEWEST_MESSAGE_TAIL" in result+ assert "[truncated]" in result+class TestFetchAndFormatTrace:@patch("posthog.temporal.ai_observability.trace_summarization.fetch_and_format.llm_trace_to_formatter_format")diff --git a/posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format_heavy_columns.py b/posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format_heavy_columns.pyindex 94e07995fff7..fced6dc9c5d2 100644--- a/posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format_heavy_columns.py+++ b/posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format_heavy_columns.py@@ -115,6 +115,18 @@ class TestFetchAndFormatGenerationHeavyColumns:return isinstance(tail, str) and "model" in tailassert "model" in select_aliases or any(_field_chain_tail_is_model(s) for s in select.select)+ # Chat-format SDKs record the result in `output_choices` and leave `output` empty,+ # so the projection must prefer `output_choices`. Preferring `output` would empty+ # most generation summaries.+ output_alias = next(s for s in select.select if isinstance(s, ast.Alias) and s.alias == "output")+ coalesce_call = output_alias.expr+ assert isinstance(coalesce_call, ast.Call) and coalesce_call.name == "coalesce"+ preferred = coalesce_call.args[0]+ assert isinstance(preferred, ast.Call) and preferred.name == "nullIf"+ preferred_field = preferred.args[0]+ assert isinstance(preferred_field, ast.Field) and preferred_field.chain[-1] == "output_choices"+ fallback_field = coalesce_call.args[1]+ assert isinstance(fallback_field, ast.Field) and fallback_field.chain[-1] == "output"# query_type is set so observability dashboards can group by it.assert kwargs["query_type"] == "GenerationForSummarization"# trace_id flows into the WHERE so the lookup hits thediff --git a/posthog/temporal/ai_observability/trace_summarization/workflow.py b/posthog/temporal/ai_observability/trace_summarization/workflow.pyindex 760e7630aa91..ee7b295e48ab 100644--- a/posthog/temporal/ai_observability/trace_summarization/workflow.py+++ b/posthog/temporal/ai_observability/trace_summarization/workflow.py@@ -61,7 +61,7 @@ from posthog.temporal.ai_observability.trace_summarization.sampling import samplfrom posthog.temporal.ai_observability.trace_summarization.summarize_and_save import summarize_and_save_activityfrom posthog.temporal.common.base import PostHogWorkflow-from products.ai_observability.backend.summarization.budget import text_repr_budget+from products.ai_observability.backend.summarization.budget import batch_text_repr_budgetfrom products.ai_observability.backend.summarization.models import OpenAIModel, SummarizationModelogger = structlog.get_logger(__name__)@@ -236,7 +236,7 @@ class BatchTraceSummarizationWorkflow(PostHogWorkflow):mode=inputs.mode,batch_run_id=batch_run_id,model=inputs.model,- max_length=text_repr_budget(inputs.model),+ max_length=batch_text_repr_budget(inputs.model),job_id=inputs.job_id,job_name=inputs.job_name,)diff --git a/products/ai_observability/backend/summarization/budget.py b/products/ai_observability/backend/summarization/budget.pyindex e1da87abccfe..a81f6336679e 100644--- a/products/ai_observability/backend/summarization/budget.py+++ b/products/ai_observability/backend/summarization/budget.py@@ -17,6 +17,14 @@ MODEL_CONTEXT_TOKENS: dict[str, int] = {# Held back from the window for the system prompt and the model's own response.RESERVED_TOKENS = 20_000+# Cost-conscious ceiling for unattended batch summarization, in characters.+# Batch runs on a schedule over every team's traces, so its context size drives a recurring bill,+# not a single user-triggered call. The model window (~1M tokens for nano) never bounds a typical+# trace, so unbounded batch inputs make the recurring unit cost spike. A trace summary does not improve past+# a few tens of thousands of tokens of context, so cap it there. Measured in characters like the+# rest of this module (~1.6 characters per token), this targets roughly 55K tokens of input.+BATCH_TEXT_REPR_MAX_CHARS = 90_000+def text_repr_budget(model: str | None = None) -> int:"""Characters of text representation the model accepts.@@ -29,6 +37,16 @@ def text_repr_budget(model: str | None = None) -> int:return window - RESERVED_TOKENS+def batch_text_repr_budget(model: str | None = None) -> int:+ """Characters of text representation a batch summarization accepts.++ Bounds the per-model window down to a cost-conscious ceiling. The batch job summarizes+ unattended on a schedule, so a large context inflates the recurring bill without a better+ summary. Never returns more than the model window allows.+ """+ return min(text_repr_budget(model), BATCH_TEXT_REPR_MAX_CHARS)++def bounded_text_repr(text: str, budget: int) -> str:"""Reduce `text` to `budget` characters, sampling whole lines where it can."""if len(text) <= budget:diff --git a/products/ai_observability/backend/summarization/tests/test_budget.py b/products/ai_observability/backend/summarization/tests/test_budget.pyindex 37ea3b508faa..f2a659f63a5d 100644--- a/products/ai_observability/backend/summarization/tests/test_budget.py+++ b/products/ai_observability/backend/summarization/tests/test_budget.py@@ -1,8 +1,10 @@from parameterized import parameterizedfrom products.ai_observability.backend.summarization.budget import (+ BATCH_TEXT_REPR_MAX_CHARS,MODEL_CONTEXT_TOKENS,RESERVED_TOKENS,+ batch_text_repr_budget,bounded_text_repr,text_repr_budget,)@@ -26,6 +28,14 @@ class TestTextReprBudget:assert text_repr_budget(OpenAIModel.GPT_4O) < text_repr_budget(OpenAIModel.GPT_4_1_MINI)+class TestBatchTextReprBudget:+ def test_wide_window_model_is_capped_below_its_full_budget(self):+ # The nano window is ~1M tokens, so its full budget never bounds a typical trace.+ # The batch cap must bring it down to the cost-conscious ceiling.+ assert batch_text_repr_budget(OpenAIModel.GPT_4_1_NANO) == BATCH_TEXT_REPR_MAX_CHARS+ assert BATCH_TEXT_REPR_MAX_CHARS < text_repr_budget(OpenAIModel.GPT_4_1_NANO)++class TestBoundedTextRepr:def test_text_within_budget_is_returned_unchanged(self):text = "L1: hello\nL2: world"