: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 the summarization text repr to the model context window (#87736)
Carlos Marchal53d841824d7c
diff --git a/ee/hogai/tools/read_data/tool.py b/ee/hogai/tools/read_data/tool.pyindex bb0aec49cfbe..39f41f26bd72 100644--- a/ee/hogai/tools/read_data/tool.py+++ b/ee/hogai/tools/read_data/tool.py@@ -29,6 +29,7 @@ from posthog.hogql.database.schema.table_descriptions import TableDescriptionsfrom posthog.models import Team, Userfrom posthog.sync import database_sync_to_async+from products.ai_observability.backend.summarization.budget import text_repr_budgetfrom products.ai_observability.backend.summarization.llm.call import summarizefrom products.ai_observability.backend.summarization.llm.schema import SummarizationResponsefrom products.ai_observability.backend.summarization.utils import get_summary_cache_key@@ -939,7 +940,11 @@ class ReadDataTool(HogQLDatabaseMixin, MaxTool):text_repr, _was_sampled = format_trace_text_repr(trace_dict,hierarchy,- options={"include_markers": False, "include_line_numbers": True},+ options={+ "include_markers": False,+ "include_line_numbers": True,+ "max_length": text_repr_budget(),+ },)if len(text_repr) <= self.TRACE_SUMMARIZATION_THRESHOLD:diff --git a/posthog/temporal/ai_observability/trace_summarization/constants.py b/posthog/temporal/ai_observability/trace_summarization/constants.pyindex ad725af64faa..06b95a0c024c 100644--- a/posthog/temporal/ai_observability/trace_summarization/constants.py+++ b/posthog/temporal/ai_observability/trace_summarization/constants.py@@ -17,11 +17,6 @@ DEFAULT_WINDOW_MINUTES = 60 # Process traces from last N minutes (matches schedDEFAULT_WINDOW_OFFSET_MINUTES = 30 # Offset window into the past so traces have time to fully completeDEFAULT_MODEL = OpenAIModel.GPT_4_1_NANO-# Max text representation length (in characters)-# GPT-4.1-nano has 1M token context. At typical 2.5:1 char/token ratio,-# 2M chars = ~800K tokens, leaving room for system prompt and output.-MAX_TEXT_REPR_LENGTH = 2_000_000-# Max estimated raw trace size (in characters) before formatting.# Traces exceeding this are skipped — formatting huge traces is CPU-intensive# and can block the worker for 10+ minutes. Estimated cheaply fromdiff --git a/posthog/temporal/ai_observability/trace_summarization/workflow.py b/posthog/temporal/ai_observability/trace_summarization/workflow.pyindex 56bafd045cde..ca4d63c79e78 100644--- a/posthog/temporal/ai_observability/trace_summarization/workflow.py+++ b/posthog/temporal/ai_observability/trace_summarization/workflow.py@@ -30,7 +30,6 @@ from posthog.temporal.ai_observability.trace_summarization.constants import (FETCH_AND_FORMAT_RETRY_POLICY,FETCH_AND_FORMAT_SCHEDULE_TO_CLOSE_TIMEOUT,FETCH_AND_FORMAT_START_TO_CLOSE_TIMEOUT,- MAX_TEXT_REPR_LENGTH,SAMPLE_HEARTBEAT_TIMEOUT,SAMPLE_SCHEDULE_TO_CLOSE_TIMEOUT,SAMPLE_TIMEOUT_SECONDS,@@ -62,6 +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_budgetfrom products.ai_observability.backend.summarization.models import 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=MAX_TEXT_REPR_LENGTH,+ max_length=text_repr_budget(inputs.model),job_id=inputs.job_id,job_name=inputs.job_name,)diff --git a/products/ai_observability/backend/api/summarization.py b/products/ai_observability/backend/api/summarization.pyindex 8536177d8d34..1d687527289f 100644--- a/products/ai_observability/backend/api/summarization.py+++ b/products/ai_observability/backend/api/summarization.py@@ -50,6 +50,7 @@ from posthog.rate_limit import ()from products.ai_observability.backend.api.metrics import llma_track_latency+from products.ai_observability.backend.summarization.budget import bounded_text_repr, text_repr_budgetfrom products.ai_observability.backend.summarization.llm import summarizefrom products.ai_observability.backend.summarization.models import SummarizationModefrom products.ai_observability.backend.summarization.utils import get_summary_cache_key@@ -410,7 +411,7 @@ class AIObservabilitySummarizationViewSet(TeamAndOrgViewSetMixin, viewsets.Generreturn dict(zip(HEAVY_COLUMN_NAMES, result.results[0]))- def _generate_text_repr(self, summarize_type: str, entity_data: dict) -> str:+ def _generate_text_repr(self, summarize_type: str, entity_data: dict, model: str | None = None) -> str:"""Generate line-numbered text representation for summarization.Args:@@ -420,11 +421,13 @@ class AIObservabilitySummarizationViewSet(TeamAndOrgViewSetMixin, viewsets.GenerReturns:Line-numbered text representation"""+ budget = text_repr_budget(model)options: FormatterOptions = {"include_line_numbers": True,"truncated": False,"include_markers": False,"collapsed": False,+ "max_length": budget,}if summarize_type == "trace":@@ -434,8 +437,9 @@ class AIObservabilitySummarizationViewSet(TeamAndOrgViewSetMixin, viewsets.Generoptions=options,)return text- else: # event- return format_event_text_repr(event=entity_data["event"], options=options)++ # format_event_text_repr ignores max_length, so the budget has to be applied to its result.+ return bounded_text_repr(format_event_text_repr(event=entity_data["event"], options=options), budget)def _build_summary_response(self, summary, text_repr: str, summarize_type: str) -> dict:"""Build the API response dict from summary and text representation.@@ -610,7 +614,7 @@ The response includes the structured summary, the text representation, and metadif entity_data is None:raise exceptions.ValidationError("No trace or event data was provided for summarization.")- text_repr = self._generate_text_repr(summarize_type, entity_data)+ text_repr = self._generate_text_repr(summarize_type, entity_data, model)start_time = time.time()user_distinct_id = getattr(request.user, "distinct_id", None)diff --git a/products/ai_observability/backend/api/test/test_summarization.py b/products/ai_observability/backend/api/test/test_summarization.pyindex 95a0958d8ec8..81bd2d3d3ce1 100644--- a/products/ai_observability/backend/api/test/test_summarization.py+++ b/products/ai_observability/backend/api/test/test_summarization.py@@ -23,6 +23,28 @@ from products.ai_observability.backend.summarization.llm.schema import (SummaryBullet,)+TEST_TEXT_REPR_BUDGET = 4000+++def _oversized_payload(summarize_type: str, one_long_line: bool) -> dict[str, Any]:+ # A single long line cannot be sampled line-wise, which is the shape that escapes a naive bound.+ ai_input: Any = (+ "x" * (TEST_TEXT_REPR_BUDGET * 4)+ if one_long_line+ else [{"role": "user", "content": f"turn {i} " + "detail " * 40} for i in range(200)]+ )+ event = {+ "id": "gen-oversized",+ "event": "$ai_generation",+ "properties": {"$ai_input": ai_input},+ }+ if summarize_type == "event":+ return {"event": event}+ return {+ "trace": {"id": "trace-oversized", "properties": {"$ai_span_name": "oversized"}},+ "hierarchy": [{"event": event, "children": []}],+ }+class TestSummarizationAPI(APIBaseTest):"""Test summarization API endpoints."""@@ -146,6 +168,46 @@ class TestSummarizationAPI(APIBaseTest):self.assertIn("title", data["summary"])self.assertEqual(data["summary"]["title"], "Multi-step Trace Execution")+ @parameterized.expand(+ [+ ("event_many_lines", "event", False),+ ("event_one_long_line", "event", True),+ ("trace_many_lines", "trace", False),+ ("trace_one_long_line", "trace", True),+ ]+ )+ @patch(+ "products.ai_observability.backend.api.summarization.text_repr_budget",+ return_value=TEST_TEXT_REPR_BUDGET,+ )+ @patch("products.ai_observability.backend.api.summarization.summarize")+ def test_oversized_entity_is_bounded_before_the_model_call(+ self, _name, summarize_type, one_long_line, mock_summarize, _mock_budget+ ):+ self.organization.is_ai_data_processing_approved = True+ self.organization.save()+ mock_summarize.return_value = SummarizationResponse(+ title="Bounded",+ flow_diagram="Start",+ summary_bullets=[SummaryBullet(text="Bounded", line_refs="L1")],+ interesting_notes=[],+ )++ response = self.client.post(+ f"/api/environments/{self.team.id}/llm_analytics/summarization/",+ {+ "summarize_type": summarize_type,+ "mode": "minimal",+ "force_refresh": True,+ "data": _oversized_payload(summarize_type, one_long_line),+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ text_repr = mock_summarize.call_args.kwargs["text_repr"]+ self.assertLessEqual(len(text_repr), TEST_TEXT_REPR_BUDGET)+def test_missing_summarize_type(self):"""Should return 400 for missing summarize_type."""self.organization.is_ai_data_processing_approved = Truediff --git a/products/ai_observability/backend/summarization/budget.py b/products/ai_observability/backend/summarization/budget.pynew file mode 100644index 000000000000..e1da87abccfe--- /dev/null+++ b/products/ai_observability/backend/summarization/budget.py@@ -0,0 +1,37 @@+"""Size limits for the text representation handed to a summarization model."""++from ..text_repr.formatters import reduce_by_uniform_sampling+from .constants import DEFAULT_MODEL_OPENAI+from .models import OpenAIModel++# Input context window per model, in tokens. A model missing from here takes the smallest window,+# so an unrecognized `model` on a request cannot buy itself a budget the provider will not accept.+MODEL_CONTEXT_TOKENS: dict[str, int] = {+ OpenAIModel.GPT_4_1_NANO: 1_047_576,+ OpenAIModel.GPT_4_1_MINI: 1_047_576,+ OpenAIModel.GPT_4O_MINI: 128_000,+ OpenAIModel.GPT_4O: 128_000,+ OpenAIModel.GPT_5_MINI: 400_000,+}++# Held back from the window for the system prompt and the model's own response.+RESERVED_TOKENS = 20_000+++def text_repr_budget(model: str | None = None) -> int:+ """Characters of text representation the model accepts.++ Spends one character per token, which is far more pessimistic than the ~1.6 that line-numbered+ trace text actually costs. The margin is deliberate: the ratio worsens with non-ASCII content+ and base64, and overshooting the window fails the request outright rather than degrading.+ """+ window = MODEL_CONTEXT_TOKENS.get(model or DEFAULT_MODEL_OPENAI, min(MODEL_CONTEXT_TOKENS.values()))+ return window - RESERVED_TOKENS+++def bounded_text_repr(text: str, budget: int) -> str:+ """Reduce `text` to `budget` characters, sampling whole lines where it can."""+ if len(text) <= budget:+ return text+ bounded, _ = reduce_by_uniform_sampling(text, budget)+ return boundeddiff --git a/products/ai_observability/backend/summarization/tests/test_budget.py b/products/ai_observability/backend/summarization/tests/test_budget.pynew file mode 100644index 000000000000..37ea3b508faa--- /dev/null+++ b/products/ai_observability/backend/summarization/tests/test_budget.py@@ -0,0 +1,41 @@+from parameterized import parameterized++from products.ai_observability.backend.summarization.budget import (+ MODEL_CONTEXT_TOKENS,+ RESERVED_TOKENS,+ bounded_text_repr,+ text_repr_budget,+)+from products.ai_observability.backend.summarization.constants import DEFAULT_MODEL_OPENAI+from products.ai_observability.backend.summarization.models import OpenAIModel+++class TestTextReprBudget:+ @parameterized.expand([(model,) for model in OpenAIModel])+ def test_every_supported_model_has_a_budget_inside_its_window(self, model: OpenAIModel):+ assert text_repr_budget(model) < MODEL_CONTEXT_TOKENS[model]++ def test_unrecognized_model_gets_no_more_than_the_smallest_window(self):+ assert text_repr_budget("gpt-9-imaginary") <= min(MODEL_CONTEXT_TOKENS.values()) - RESERVED_TOKENS++ @parameterized.expand([("empty", ""), ("none", None)])+ def test_unspecified_model_gets_the_default_model_budget(self, _name, model):+ assert text_repr_budget(model) == text_repr_budget(DEFAULT_MODEL_OPENAI)++ def test_a_narrow_window_model_gets_a_smaller_budget_than_a_wide_one(self):+ assert text_repr_budget(OpenAIModel.GPT_4O) < text_repr_budget(OpenAIModel.GPT_4_1_MINI)+++class TestBoundedTextRepr:+ def test_text_within_budget_is_returned_unchanged(self):+ text = "L1: hello\nL2: world"+ assert bounded_text_repr(text, budget=1000) == text++ @parameterized.expand(+ [+ ("one_long_line", "L1: " + "x" * 5000),+ ("many_lines", "\n".join(f"L{i}: {'x' * 100}" for i in range(200))),+ ]+ )+ def test_oversized_text_is_reduced_to_the_budget(self, _name, text):+ assert len(bounded_text_repr(text, budget=500)) <= 500diff --git a/products/ai_observability/backend/text_repr/formatters/message_formatter.py b/products/ai_observability/backend/text_repr/formatters/message_formatter.pyindex 551aa9b0722e..7262be50b4e2 100644--- a/products/ai_observability/backend/text_repr/formatters/message_formatter.py+++ b/products/ai_observability/backend/text_repr/formatters/message_formatter.py@@ -101,14 +101,16 @@ def reduce_by_uniform_sampling(lines = text.split("\n")total_lines = len(lines)+ # Sampling drops whole lines, so text that is oversized but has too few lines to sample (one+ # huge payload on a single line, for example) can only be cut mid-line.if total_lines <= preserve_header_lines:- return text, False+ return text[:max_length], Trueheader_lines = lines[:preserve_header_lines]body_lines = lines[preserve_header_lines:]if not body_lines:- return text, False+ return text[:max_length], Truesample_header_template_size = len(SAMPLED_VIEW_HEADER.format(percent=100, total=total_lines)) + 1@@ -117,13 +119,13 @@ def reduce_by_uniform_sampling(available_for_body = max_length - header_sizeif available_for_body <= 0:- return text, False+ return text[:max_length], Trueavg_line_length = sum(len(line) + 1 for line in body_lines) / len(body_lines)target_body_lines = int(available_for_body / avg_line_length)if target_body_lines >= len(body_lines):- return text, False+ return text[:max_length], Truetarget_body_lines = max(target_body_lines, 1)@@ -581,7 +583,8 @@ def format_messages_array(messages: list[Any], options: FormatterOptions | Noneif not isinstance(msg, dict):continue- role = msg.get("role") or msg.get("type") or "unknown"+ # SDKs record non-string roles, which crash `.upper()`.+ role = str(msg.get("role") or msg.get("type") or "unknown")content = msg.get("content", "")tool_calls = msg.get("tool_calls", [])diff --git a/products/ai_observability/backend/text_repr/formatters/test/test_message_formatter.py b/products/ai_observability/backend/text_repr/formatters/test/test_message_formatter.pyindex fa38c625ec24..a43bb9995656 100644--- a/products/ai_observability/backend/text_repr/formatters/test/test_message_formatter.py+++ b/products/ai_observability/backend/text_repr/formatters/test/test_message_formatter.py@@ -375,6 +375,19 @@ class TestFormatInputMessages:truncation_marker_found = any("TRUNCATED" in line for line in lines)assert truncation_marker_found+ @parameterized.expand(+ [+ ("dict", {"name": "user"}),+ ("list", ["user"]),+ ]+ )+ def test_non_string_role_still_renders_the_message(self, _name, role):+ messages = [{"role": role, "content": "Hello"}]++ result = "\n".join(format_input_messages(messages))++ assert "Hello" in result+class TestFormatOutputMessages:"""Test output message section formatting."""diff --git a/products/ai_observability/backend/text_repr/formatters/test/test_tool_formatter.py b/products/ai_observability/backend/text_repr/formatters/test/test_tool_formatter.pyindex ec6fd945dbbf..0a6849fd7de8 100644--- a/products/ai_observability/backend/text_repr/formatters/test/test_tool_formatter.py+++ b/products/ai_observability/backend/text_repr/formatters/test/test_tool_formatter.py@@ -4,6 +4,8 @@ Tests for tool_formatter.py - available tools section formatting.Tests cover array and dictionary formats, multiple provider formats, and edge cases."""+from parameterized import parameterized+from ..tool_formatter import format_tools@@ -319,3 +321,16 @@ class TestEdgeCases:# Should be collapsed with threshold=2 (3 > 2)assert "<<<TOOLS_EXPANDABLE|" in resultassert "AVAILABLE TOOLS: 3" in result++ @parameterized.expand(+ [+ ("list", ["query", "limit"]),+ ("string", "query"),+ ]+ )+ def test_unusable_properties_schema_still_renders_the_tool(self, _name, properties):+ tools = [{"name": "search", "description": "Search things.", "input_schema": {"properties": properties}}]++ result = "\n".join(format_tools(tools))++ assert "search()" in resultdiff --git a/products/ai_observability/backend/text_repr/formatters/test/test_uniform_sampling.py b/products/ai_observability/backend/text_repr/formatters/test/test_uniform_sampling.pyindex 37fe29d7bbd3..53e353f0670a 100644--- a/products/ai_observability/backend/text_repr/formatters/test/test_uniform_sampling.py+++ b/products/ai_observability/backend/text_repr/formatters/test/test_uniform_sampling.py@@ -97,9 +97,19 @@ class TestReduceByUniformSampling:result, _ = reduce_by_uniform_sampling(text, max_length=1000)assert len(result) <= 1000- def test_text_with_only_header_lines_unchanged(self):- text = _create_numbered_text(PRESERVE_HEADER_LINES, line_content_length=20)+ @pytest.mark.parametrize(+ "num_lines",+ [1, PRESERVE_HEADER_LINES - 1, PRESERVE_HEADER_LINES],+ )+ def test_oversized_text_with_too_few_lines_to_sample_is_truncated(self, num_lines: int):+ text = _create_numbered_text(num_lines, line_content_length=200)result, was_sampled = reduce_by_uniform_sampling(text, max_length=100)+ assert len(result) == 100+ assert was_sampled is True++ def test_text_with_only_header_lines_within_max_length_unchanged(self):+ text = _create_numbered_text(PRESERVE_HEADER_LINES, line_content_length=20)+ result, was_sampled = reduce_by_uniform_sampling(text, max_length=10000)assert result == textassert was_sampled is Falsediff --git a/products/ai_observability/backend/text_repr/formatters/tool_formatter.py b/products/ai_observability/backend/text_repr/formatters/tool_formatter.pyindex 1c73b34a2991..8729bbe5f725 100644--- a/products/ai_observability/backend/text_repr/formatters/tool_formatter.py+++ b/products/ai_observability/backend/text_repr/formatters/tool_formatter.py@@ -78,7 +78,8 @@ def _format_tools_list(tools_list: list[Any]) -> str:# Build function signature from schemasignature = f"{name}("- if schema and isinstance(schema, dict) and "properties" in schema:+ # SDKs record non-object `properties`, which crashes `.items()` below.+ if isinstance(schema, dict) and isinstance(schema.get("properties"), dict):properties = schema["properties"]required = schema.get("required", [])params: list[str] = []