: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 session summarize-all input to the batch ceiling (#110996)
posthog[bot]7d93ed5be711
diff --git a/products/ai_observability/backend/api/summarization.py b/products/ai_observability/backend/api/summarization.pyindex 616651c10dd8..d3e0bc357dff 100644--- a/products/ai_observability/backend/api/summarization.py+++ b/products/ai_observability/backend/api/summarization.py@@ -54,7 +54,11 @@ from products.access_control.backend.facade.api import (split_restricted_property_names,)from products.ai_observability.backend.api.metrics import llma_track_latency-from products.ai_observability.backend.summarization.budget import bounded_text_repr, text_repr_budget+from products.ai_observability.backend.summarization.budget import (+ batch_text_repr_budget,+ bounded_text_repr,+ text_repr_budget,+)from products.ai_observability.backend.summarization.llm import summarizefrom products.ai_observability.backend.summarization.models import SummarizationModefrom products.ai_observability.backend.summarization.utils import (@@ -77,6 +81,10 @@ logger = structlog.get_logger(__name__)SUMMARIZABLE_EVENT_TYPES = ["$ai_generation", "$ai_span", "$ai_embedding", "$ai_evaluation"]+def _compact_cache_key(cache_key: str) -> str:+ return f"{cache_key}:compact"++# Request/Response Serializersclass SummarizeRequestSerializer(serializers.Serializer):summarize_type = serializers.ChoiceField(@@ -99,6 +107,12 @@ class SummarizeRequestSerializer(serializers.Serializer):required=False,help_text="Force regenerate summary, bypassing cache",)+ compact_context = serializers.BooleanField(+ default=False,+ required=False,+ help_text="Bound the input to a cost-conscious size instead of the full model context window. "+ "Use it when you summarize many traces at once and need only a short result such as the title.",+ )model = serializers.CharField(default=None,required=False,@@ -272,6 +286,24 @@ class AIObservabilitySummarizationViewSet(TeamAndOrgViewSetMixin, viewsets.Gener),)+ @staticmethod+ def _get_cached_summary(cache_key: str, compact_context: bool) -> dict | None:+ """Read a cached summary. A full-context summary also serves a compact request, but not the opposite."""+ if compact_context:+ compact_result = cache.get(_compact_cache_key(cache_key))+ if compact_result is not None:+ return compact_result+ return cache.get(cache_key)++ @staticmethod+ def _cache_summary(cache_key: str, result: dict, compact_context: bool) -> None:+ if compact_context:+ cache.set(_compact_cache_key(cache_key), result, timeout=3600)+ return+ cache.set(cache_key, result, timeout=3600)+ # A compact request reads the compact entry first, so an older one would hide this newer summary.+ cache.delete(_compact_cache_key(cache_key))+def _extract_entity_id(self, summarize_type: str, data: dict) -> tuple[str, dict]:"""Extract entity ID and validated entity data based on summarize type.@@ -433,17 +465,22 @@ class AIObservabilitySummarizationViewSet(TeamAndOrgViewSetMixin, viewsets.Generreturn dict(zip(HEAVY_COLUMN_NAMES, result.results[0]))- def _generate_text_repr(self, summarize_type: str, entity_data: dict, model: str | None = None) -> str:+ def _generate_text_repr(+ self, summarize_type: str, entity_data: dict, model: str | None = None, compact_context: bool = False+ ) -> str:"""Generate line-numbered text representation for summarization.Args:summarize_type: 'trace' or 'event'entity_data: Dict containing trace/event data+ compact_context: Bound the text to the batch ceiling instead of the model windowReturns:Line-numbered text representation"""- budget = text_repr_budget(model)+ # Each trace of an agent session can repeat the full conversation, so a fan-out over a session+ # at the model window pays for a huge trace on every call.+ budget = batch_text_repr_budget(model) if compact_context else text_repr_budget(model)options: FormatterOptions = {"include_line_numbers": True,"truncated": False,@@ -607,6 +644,7 @@ The response includes the structured summary, the text representation, and metadsummarize_type = serializer.validated_data["summarize_type"]mode = serializer.validated_data["mode"]force_refresh = serializer.validated_data["force_refresh"]+ compact_context = serializer.validated_data["compact_context"]model = serializer.validated_data.get("model")# Treat empty string as None for modelif model == "":@@ -644,7 +682,7 @@ The response includes the structured summary, the text representation, and metadcache_key = self._get_cache_key(summarize_type, entity_id, mode, model)if not force_refresh:- cached_result = cache.get(cache_key)+ cached_result = self._get_cached_summary(cache_key, compact_context)if cached_result is not None:logger.info("Returning cached summary",@@ -663,7 +701,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, model)+ text_repr = self._generate_text_repr(summarize_type, entity_data, model, compact_context)start_time = time.time()user_distinct_id = getattr(request.user, "distinct_id", None)@@ -679,7 +717,7 @@ The response includes the structured summary, the text representation, and metadresult = self._build_summary_response(summary, text_repr, summarize_type)- cache.set(cache_key, result, timeout=3600)+ self._cache_summary(cache_key, result, compact_context)logger.info("Generated and cached new summary",summarize_type=summarize_type,@@ -699,6 +737,7 @@ The response includes the structured summary, the text representation, and metad"mode": mode,"text_repr_length": len(text_repr),"force_refresh": force_refresh,+ "compact_context": compact_context,"duration_seconds": duration_seconds,},team=self.team,@@ -766,8 +805,9 @@ with their titles.summaries = []for trace_id in trace_ids:- cache_key = self._get_cache_key("trace", trace_id, mode, model)- cached_result = cache.get(cache_key)+ cached_result = self._get_cached_summary(+ self._get_cache_key("trace", trace_id, mode, model), compact_context=True+ )if cached_result is not None:summary_data = cached_result.get("summary", {})title = summary_data.get("title", "Untitled trace")diff --git a/products/ai_observability/backend/api/test/test_summarization.py b/products/ai_observability/backend/api/test/test_summarization.pyindex 81aadaab1fa6..f75e5c905341 100644--- a/products/ai_observability/backend/api/test/test_summarization.py+++ b/products/ai_observability/backend/api/test/test_summarization.py@@ -214,6 +214,71 @@ class TestSummarizationAPI(APIBaseTest):text_repr = mock_summarize.call_args.kwargs["text_repr"]self.assertLessEqual(len(text_repr), TEST_TEXT_REPR_BUDGET)+ @parameterized.expand([("full_context", False, TEST_TEXT_REPR_BUDGET), ("compact_context", True, 1000)])+ @patch(+ "products.ai_observability.backend.api.summarization.batch_text_repr_budget",+ return_value=1000,+ )+ @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_compact_context_bounds_the_input_and_caches_separately(+ self, _name, compact_context, expected_budget, mock_summarize, _mock_budget, _mock_batch_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=[],+ )+ url = f"/api/environments/{self.team.id}/llm_analytics/summarization/"+ request = {+ "summarize_type": "trace",+ "mode": "minimal",+ "compact_context": compact_context,+ "data": _oversized_payload("trace", one_long_line=False),+ }++ self.assertEqual(self.client.post(url, request, format="json").status_code, status.HTTP_200_OK)+ text_repr = mock_summarize.call_args.kwargs["text_repr"]+ self.assertLessEqual(len(text_repr), expected_budget)+ self.assertEqual(len(text_repr) > 1000, not compact_context)++ titles = self.client.post(url + "batch_check/", {"trace_ids": ["trace-oversized"]}, format="json")+ self.assertEqual([s["trace_id"] for s in titles.data["summaries"]], ["trace-oversized"])++ # A full-context request must not get the summary of the bounded input from the cache.+ self.client.post(url, {**request, "compact_context": False}, format="json")+ self.assertEqual(mock_summarize.call_count, 2 if compact_context else 1)++ @parameterized.expand([("compact_refresh", True), ("full_refresh", False)])+ @patch("products.ai_observability.backend.api.summarization.summarize")+ def test_session_titles_follow_the_latest_refresh(self, _name, refresh_is_compact, mock_summarize):+ self.organization.is_ai_data_processing_approved = True+ self.organization.save()+ url = f"/api/environments/{self.team.id}/llm_analytics/summarization/"+ request = {"summarize_type": "trace", "mode": "minimal", "data": _oversized_payload("trace", False)}++ def summarize_as(title: str, **overrides: bool) -> None:+ mock_summarize.return_value = SummarizationResponse(+ title=title,+ flow_diagram="Start",+ summary_bullets=[SummaryBullet(text=title, line_refs="L1")],+ interesting_notes=[],+ )+ response = self.client.post(url, {**request, **overrides}, format="json")+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ summarize_as("Stale", compact_context=not refresh_is_compact)+ summarize_as("Refreshed", compact_context=refresh_is_compact, force_refresh=True)++ titles = self.client.post(url + "batch_check/", {"trace_ids": ["trace-oversized"]}, format="json")+ self.assertEqual([s["title"] for s in titles.data["summaries"]], ["Refreshed"])+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/frontend/aiObservabilitySessionDataLogic.test.ts b/products/ai_observability/frontend/aiObservabilitySessionDataLogic.test.tsindex debbfd749def..156a081b29f4 100644--- a/products/ai_observability/frontend/aiObservabilitySessionDataLogic.test.ts+++ b/products/ai_observability/frontend/aiObservabilitySessionDataLogic.test.ts@@ -157,6 +157,7 @@ describe('aiObservabilitySessionDataLogic', () => {expect(summarizationCreate.mock.calls[0][1]).toEqual({mode: 'minimal',+ compact_context: true,force_refresh: false,trace_id: 'trace-1',date_from: '2025-12-31T00:00:00.000Z',diff --git a/products/ai_observability/frontend/aiObservabilitySessionDataLogic.ts b/products/ai_observability/frontend/aiObservabilitySessionDataLogic.tsindex e67e12eb4155..ce3b0b55a3ee 100644--- a/products/ai_observability/frontend/aiObservabilitySessionDataLogic.ts+++ b/products/ai_observability/frontend/aiObservabilitySessionDataLogic.ts@@ -571,6 +571,8 @@ export const aiObservabilitySessionDataLogic = kea<aiObservabilitySessionDataLogconst data = await llmAnalyticsSummarizationCreate(String(teamId), {mode: 'minimal',force_refresh: forceRefresh,+ // The session list shows only the title, so a bounded input is enough.+ compact_context: true,trace_id: traceId,...getSummarizationLookupDateRange(trace?.createdAt),})diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.tsindex d5ffb7051c7b..d43f7072d6fa 100644--- a/products/ai_observability/frontend/generated/api.schemas.ts+++ b/products/ai_observability/frontend/generated/api.schemas.ts@@ -3815,6 +3815,8 @@ export interface SummarizeRequestApi {data?: unknown/** Force regenerate summary, bypassing cache */force_refresh?: boolean+ /** Bound the input to a cost-conscious size instead of the full model context window. Use it when you summarize many traces at once and need only a short result such as the title. */+ compact_context?: boolean/*** LLM model to use (defaults based on provider)* @nullablediff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.tsindex d42dddd360ee..03cf9a96f274 100644--- a/products/ai_observability/frontend/generated/api.zod.ts+++ b/products/ai_observability/frontend/generated/api.zod.ts@@ -2617,6 +2617,7 @@ export const LlmAnalyticsScoreDefinitionsNewVersionCreateBody = /* @__PURE__ */*/export const llmAnalyticsSummarizationCreateBodyModeDefault = `minimal`export const llmAnalyticsSummarizationCreateBodyForceRefreshDefault = false+export const llmAnalyticsSummarizationCreateBodyCompactContextDefault = falseexport const LlmAnalyticsSummarizationCreateBody = /* @__PURE__ */ zod.object({summarize_type: zod@@ -2643,6 +2644,12 @@ export const LlmAnalyticsSummarizationCreateBody = /* @__PURE__ */ zod.object({.boolean().default(llmAnalyticsSummarizationCreateBodyForceRefreshDefault).describe('Force regenerate summary, bypassing cache'),+ compact_context: zod+ .boolean()+ .default(llmAnalyticsSummarizationCreateBodyCompactContextDefault)+ .describe(+ 'Bound the input to a cost-conscious size instead of the full model context window. Use it when you summarize many traces at once and need only a short result such as the title.'+ ),model: zod.string().nullish().describe('LLM model to use (defaults based on provider)'),trace_id: zod.string()diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d198e9276eb6..f4ace22b060e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -101504,6 +101504,8 @@ export namespace Schemas {data?: unknown;/** Force regenerate summary, bypassing cache */force_refresh?: boolean;+ /** Bound the input to a cost-conscious size instead of the full model context window. Use it when you summarize many traces at once and need only a short result such as the title. */+ compact_context?: boolean;/*** LLM model to use (defaults based on provider)* @nullablediff --git a/services/mcp/src/generated/ai_observability/api.ts b/services/mcp/src/generated/ai_observability/api.tsindex 01a0c0c4cb3a..47a11e837bb0 100644--- a/services/mcp/src/generated/ai_observability/api.ts+++ b/services/mcp/src/generated/ai_observability/api.ts@@ -2410,6 +2410,7 @@ export const LlmAnalyticsSummarizationCreateParams = () => zod.object({export const llmAnalyticsSummarizationCreateBodyModeDefault = `minimal`export const llmAnalyticsSummarizationCreateBodyForceRefreshDefault = false+export const llmAnalyticsSummarizationCreateBodyCompactContextDefault = falseexport const LlmAnalyticsSummarizationCreateBody = () => zod.object({summarize_type: zod@@ -2436,6 +2437,12 @@ export const LlmAnalyticsSummarizationCreateBody = () => zod.object({.boolean().default(llmAnalyticsSummarizationCreateBodyForceRefreshDefault).describe('Force regenerate summary, bypassing cache'),+ compact_context: zod+ .boolean()+ .default(llmAnalyticsSummarizationCreateBodyCompactContextDefault)+ .describe(+ 'Bound the input to a cost-conscious size instead of the full model context window. Use it when you summarize many traces at once and need only a short result such as the title.'+ ),model: zod.string().nullish().describe('LLM model to use (defaults based on provider)'),trace_id: zod.string()diff --git a/services/mcp/src/tools/generated/ai_observability.ts b/services/mcp/src/tools/generated/ai_observability.tsindex 46ed68aacc58..c1ef4115404a 100644--- a/services/mcp/src/tools/generated/ai_observability.ts+++ b/services/mcp/src/tools/generated/ai_observability.ts@@ -2259,6 +2259,9 @@ const llmaSummarizationCreate = (): ToolBase<if (params.force_refresh !== undefined) {body['force_refresh'] = params.force_refresh}+ if (params.compact_context !== undefined) {+ body['compact_context'] = params.compact_context+ }if (params.model !== undefined) {body['model'] = params.model}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-summarization-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-summarization-create.jsonindex 5c115bc3ea9a..1767d949cf32 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-summarization-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-summarization-create.json@@ -1,6 +1,11 @@{"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {+ "compact_context": {+ "default": false,+ "description": "Bound the input to a cost-conscious size instead of the full model context window. Use it when you summarize many traces at once and need only a short result such as the title.",+ "type": "boolean"+ },"data": {"description": "Data to summarize. For traces: {trace, hierarchy}. For events: {event}. Not required when using trace_id or generation_id."},