: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(tasks): faster analysis reap and enriched insight events (#87804)
Shy Alter17e546c27a37
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex 30400ff3e24f..7439b5983b00 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -29,6 +29,9 @@ TASK_ANALYSIS_FEATURE_FLAG = "posthog-code-task-analysis"ANALYSIS_TARGET_TASK_ID_STATE_KEY = "analysis_target_task_id"ANALYSIS_TARGET_RUN_ID_STATE_KEY = "analysis_target_run_id"+ANALYSIS_TARGET_REPOSITORY_STATE_KEY = "analysis_target_repository"+ANALYSIS_TARGET_IMAGE_ID_STATE_KEY = "analysis_target_custom_image_id"+ANALYSIS_TARGET_IMAGE_NAME_STATE_KEY = "analysis_target_custom_image_name"TASK_ANALYSIS_INSIGHTS_STATE_KEY = "task_analysis_insights"# Run-state key the telemetry flag decision is stamped under at dispatch (temporal/client.py).# Consumers read the stamp, so the decision stays stable for the run's whole lifetime.diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 23ae43764b8c..649bf30ec1aa 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -64,6 +64,9 @@ from products.posthog_ai.backend.task_ownership import detach_conversations_for_from products.tasks.backend.constants import (AGENT_OTEL_TELEMETRY_STATE_KEY,AGENT_PEER_MESSAGING_FEATURE_FLAG,+ ANALYSIS_TARGET_IMAGE_ID_STATE_KEY,+ ANALYSIS_TARGET_IMAGE_NAME_STATE_KEY,+ ANALYSIS_TARGET_REPOSITORY_STATE_KEY,ANALYSIS_TARGET_RUN_ID_STATE_KEY,ANALYSIS_TARGET_TASK_ID_STATE_KEY,CI_STATUSES as CI_STATUSES, # re-exported for presentation@@ -2142,6 +2145,12 @@ _PROTECTED_RUN_STATE_KEYS = frozenset(TASK_ANALYSIS_INSIGHTS_STATE_KEY,ANALYSIS_TARGET_TASK_ID_STATE_KEY,ANALYSIS_TARGET_RUN_ID_STATE_KEY,+ # Server-stamped at analysis creation (task_analysis._target_context_state) and read back+ # at insight-report time to attribute the captured event to a repository and sandbox+ # image. A PATCHable value would let the sandbox agent forge that attribution.+ ANALYSIS_TARGET_REPOSITORY_STATE_KEY,+ ANALYSIS_TARGET_IMAGE_ID_STATE_KEY,+ ANALYSIS_TARGET_IMAGE_NAME_STATE_KEY,# Credential grant decided at Task.create_and_run time by server-owned callers (the scout# runner); a PATCHable key would let any task controller mint a GitHub token onto a# queued repo-less run.diff --git a/products/tasks/backend/logic/services/task_analysis.py b/products/tasks/backend/logic/services/task_analysis.pyindex 5b9a6d97e34a..0448de6397ab 100644--- a/products/tasks/backend/logic/services/task_analysis.py+++ b/products/tasks/backend/logic/services/task_analysis.py@@ -16,6 +16,9 @@ from posthog.models.team import Teamfrom posthog.storage import object_storagefrom products.tasks.backend.constants import (+ ANALYSIS_TARGET_IMAGE_ID_STATE_KEY,+ ANALYSIS_TARGET_IMAGE_NAME_STATE_KEY,+ ANALYSIS_TARGET_REPOSITORY_STATE_KEY,ANALYSIS_TARGET_RUN_ID_STATE_KEY,ANALYSIS_TARGET_TASK_ID_STATE_KEY,TASK_ANALYSIS_INSIGHTS_STATE_KEY,@@ -27,12 +30,12 @@ from products.tasks.backend.logic.services.staged_artifacts import (build_task_run_artifact_storage_path,tag_task_artifact,)-from products.tasks.backend.models import Task, TaskRun+from products.tasks.backend.models import SandboxCustomImage, Task, TaskRunlogger = structlog.get_logger(__name__)TASK_ANALYSIS_MODEL = "gpt-5.6-luna"-TASK_ANALYSIS_INACTIVITY_TIMEOUT_SECONDS = 600+TASK_ANALYSIS_INACTIVITY_TIMEOUT_SECONDS = 180TASK_ANALYSIS_RUNTIME_ADAPTER = "codex"TASK_ANALYSIS_REASONING_EFFORT = "high"RUN_LOG_ARTIFACT_NAME = "run-log.jsonl"@@ -186,6 +189,26 @@ def _write_analysis_artifact(*, run: TaskRun, artifact_id: str, log_keys: list[sreturn storage_path+def _target_context_state(target_task: Task, target_run: TaskRun) -> dict[str, Any]:+ """Grouping keys copied from the target at creation, so insight events can be sliced+ by repository and sandbox image without joining other datasets."""+ context: dict[str, Any] = {}+ if target_task.repository:+ context[ANALYSIS_TARGET_REPOSITORY_STATE_KEY] = target_task.repository+ target_state = target_run.state if isinstance(target_run.state, dict) else {}+ image_id = target_state.get("custom_image_id")+ if isinstance(image_id, str) and image_id:+ context[ANALYSIS_TARGET_IMAGE_ID_STATE_KEY] = image_id+ image = SandboxCustomImage.get_accessible_for_task(+ image_id=image_id,+ team_id=target_run.team_id,+ task_created_by_id=target_task.created_by_id,+ )+ if image is not None:+ context[ANALYSIS_TARGET_IMAGE_NAME_STATE_KEY] = image.name+ return context++def create_task_analysis(*, team: Team, user_id: int, target_task: Task, target_run: TaskRun) -> tuple[Task, bool]:"""Create (or return the existing) analysis task for ``target_run``; returns ``(task, created)``."""from products.tasks.backend.logic.services.workflow_dispatch import ( # noqa: PLC0415 — temporal client stays off the module import path@@ -222,6 +245,7 @@ def create_task_analysis(*, team: Team, user_id: int, target_task: Task, target_ANALYSIS_TARGET_RUN_ID_STATE_KEY: str(target_run.id),"pending_user_artifact_ids": [artifact_id],"reasoning_effort": TASK_ANALYSIS_REASONING_EFFORT,+ **_target_context_state(target_task, target_run),}origin_key = _analysis_origin_key(str(target_run.id), attempt)@@ -342,6 +366,7 @@ def _capture_insight_event(run: TaskRun, insight: dict[str, Any], index: int) ->"wasted_tool_calls": wasted.get("tool_calls"),"wasted_seconds": wasted.get("seconds"),"wasted_tokens": wasted.get("tokens"),+ "wasted_output_bytes": wasted.get("output_bytes"),"recurrence": insight.get("recurrence"),"confidence_basis": insight.get("confidence_basis"),"suggested_fix_change": fix.get("change"),@@ -349,5 +374,9 @@ def _capture_insight_event(run: TaskRun, insight: dict[str, Any], index: int) ->"evidence_count": len(evidence) if isinstance(evidence, list) else 0,"analysis_target_task_id": state.get(ANALYSIS_TARGET_TASK_ID_STATE_KEY),"analysis_target_run_id": state.get(ANALYSIS_TARGET_RUN_ID_STATE_KEY),+ ANALYSIS_TARGET_REPOSITORY_STATE_KEY: state.get(ANALYSIS_TARGET_REPOSITORY_STATE_KEY),+ ANALYSIS_TARGET_IMAGE_ID_STATE_KEY: state.get(ANALYSIS_TARGET_IMAGE_ID_STATE_KEY),+ ANALYSIS_TARGET_IMAGE_NAME_STATE_KEY: state.get(ANALYSIS_TARGET_IMAGE_NAME_STATE_KEY),+ "repository": state.get(ANALYSIS_TARGET_REPOSITORY_STATE_KEY),},)diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex eee48cb68569..e88ac42f7b26 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -1660,6 +1660,9 @@ class TaskAnalysisWastedEffortSerializer(serializers.Serializer):min_value=1, required=False, help_text="Wall-clock seconds across the wasted span.")tokens = serializers.IntegerField(min_value=1, required=False, help_text="Token delta across the wasted span.")+ output_bytes = serializers.IntegerField(+ min_value=1, required=False, help_text="Sum of tool-output sizes across the wasted span."+ )class TaskAnalysisSuggestedFixSerializer(serializers.Serializer):diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 9aa71cae03c0..50d3ecea084f 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -5371,6 +5371,9 @@ class TestTaskRunAPI(BaseTaskAPITest):"model": "claude-sonnet-5","reasoning_effort": "low","loop_terminal_bookkeeping_complete": True,+ "analysis_target_repository": "posthog/posthog",+ "analysis_target_custom_image_id": "img-real",+ "analysis_target_custom_image_name": "real-image",},)@@ -5425,6 +5428,11 @@ class TestTaskRunAPI(BaseTaskAPITest):"model": "claude-opus-4-8","reasoning_effort": "high","loop_terminal_bookkeeping_complete": False,+ # server-stamped analysis insight attribution; a forged value would+ # misattribute the captured insight event to another repository / image+ "analysis_target_repository": "attacker/attacker",+ "analysis_target_custom_image_id": "img-attacker",+ "analysis_target_custom_image_name": "attacker-image","scratch": "ok",}},@@ -5461,6 +5469,9 @@ class TestTaskRunAPI(BaseTaskAPITest):assert run.state["model"] == "claude-sonnet-5"assert run.state["reasoning_effort"] == "low"assert run.state["loop_terminal_bookkeeping_complete"] is True+ assert run.state["analysis_target_repository"] == "posthog/posthog" # cannot forge attribution+ assert run.state["analysis_target_custom_image_id"] == "img-real"+ assert run.state["analysis_target_custom_image_name"] == "real-image"assert run.state["scratch"] == "ok" # non-protected keys still merge# Nor can a caller remove a protected key to force a fallback or unguarded path.@@ -5487,6 +5498,9 @@ class TestTaskRunAPI(BaseTaskAPITest):"model","reasoning_effort","loop_terminal_bookkeeping_complete",+ "analysis_target_repository",+ "analysis_target_custom_image_id",+ "analysis_target_custom_image_name","scratch",],},@@ -5515,6 +5529,9 @@ class TestTaskRunAPI(BaseTaskAPITest):assert run.state["model"] == "claude-sonnet-5" # protected key survives removalassert run.state["reasoning_effort"] == "low" # protected key survives removalassert run.state["loop_terminal_bookkeeping_complete"] is True+ assert run.state["analysis_target_repository"] == "posthog/posthog" # protected key survives removal+ assert run.state["analysis_target_custom_image_id"] == "img-real"+ assert run.state["analysis_target_custom_image_name"] == "real-image"assert "scratch" not in run.state # non-protected key removed@patch("products.tasks.backend.facade.api.signal_workflow_completion")@@ -13642,6 +13659,38 @@ class TestTaskRunAnalyzeAPI(BaseTaskAPITest):self.assertTrue(response.json()["created"])self.assertEqual(Task.objects.filter(origin_product=Task.OriginProduct.TASK_ANALYSIS).count(), 1)+ def test_analyze_copies_target_repository_and_image_into_run_state(self):+ image = _make_custom_image(team=self.team, user=self.user, name="PostHog Stack")+ self.target_task.repository = "posthog/posthog"+ self.target_task.save(update_fields=["repository"])+ self.target_run.state = {"custom_image_id": str(image.id)}+ self.target_run.save(update_fields=["state"])++ read_p, write_p, tag_p, dispatch_p = self._patch_boundaries()+ with read_p, write_p, tag_p, dispatch_p:+ response = self._analyze()++ run = Task.objects.get(id=response.json()["analysis_task_id"]).latest_run+ assert run is not None+ self.assertEqual(run.state["analysis_target_repository"], "posthog/posthog")+ self.assertEqual(run.state["analysis_target_custom_image_id"], str(image.id))+ self.assertEqual(run.state["analysis_target_custom_image_name"], "PostHog Stack")++ def test_analyze_does_not_copy_name_of_another_users_private_image(self):+ other_user = User.objects.create_user(email="[email protected]", first_name="Other", password="password")+ private_image = _make_custom_image(team=self.team, user=other_user, name="their-private", private=True)+ self.target_run.state = {"custom_image_id": str(private_image.id)}+ self.target_run.save(update_fields=["state"])++ read_p, write_p, tag_p, dispatch_p = self._patch_boundaries()+ with read_p, write_p, tag_p, dispatch_p:+ response = self._analyze()++ run = Task.objects.get(id=response.json()["analysis_task_id"]).latest_run+ assert run is not None+ self.assertEqual(run.state["analysis_target_custom_image_id"], str(private_image.id))+ self.assertNotIn("analysis_target_custom_image_name", run.state)+def test_analyze_is_idempotent_per_run(self):read_p, write_p, tag_p, dispatch_p = self._patch_boundaries()with read_p, write_p, tag_p, dispatch_p:@@ -13924,7 +13973,11 @@ class TestTaskAnalysisInsightReporting(BaseTaskAPITest):task=self.analysis_task,team=self.team,status=TaskRun.Status.IN_PROGRESS,- state={"analysis_target_run_id": str(uuid.uuid4())},+ state={+ "analysis_target_run_id": str(uuid.uuid4()),+ "analysis_target_repository": "posthog/posthog",+ "analysis_target_custom_image_name": "PostHog Stack",+ },)self.agent_client = self._sandbox_oauth_client(self.analysis_task.id)self.sandbox_application = OAuthApplication.objects.get(client_id=ARRAY_APP_CLIENT_ID_DEV)@@ -13959,7 +14012,7 @@ class TestTaskAnalysisInsightReporting(BaseTaskAPITest):{"quote": "docker compose up -d postgres", "evidence_type": "command_output"},],"category": "environment_failure",- "wasted_effort": {"tool_calls": 3, "seconds": 45},+ "wasted_effort": {"tool_calls": 3, "seconds": 45, "output_bytes": 54000},"recurrence": "every_run_in_this_repo","confidence_basis": "directly_observed","suggested_fix": {@@ -13987,7 +14040,11 @@ class TestTaskAnalysisInsightReporting(BaseTaskAPITest):props = events[0]["properties"]self.assertEqual(props["category"], "environment_failure")self.assertEqual(props["wasted_tool_calls"], 3)+ self.assertEqual(props["wasted_output_bytes"], 54000)self.assertEqual(props["insight_index"], 0)+ self.assertEqual(props["repository"], "posthog/posthog")+ self.assertEqual(props["analysis_target_repository"], "posthog/posthog")+ self.assertEqual(props["analysis_target_custom_image_name"], "PostHog Stack")def test_run_patch_cannot_write_insights_or_the_target_linkage(self):original_target = self.analysis_run.state["analysis_target_run_id"]diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex 625047cea18a..b37f5634f8d9 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -3132,6 +3132,11 @@ export interface TaskAnalysisWastedEffortApi {* @minimum 1*/tokens?: number+ /**+ * Sum of tool-output sizes across the wasted span.+ * @minimum 1+ */+ output_bytes?: number}/**diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex f72c04b65d79..16af2c8e631e 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -2426,6 +2426,11 @@ export const TasksRunsAnalysisInsightCreateBody = /* @__PURE__ */ zodtool_calls: zod.number().min(1).optional().describe('Wasted tool calls, counted from the log.'),seconds: zod.number().min(1).optional().describe('Wall-clock seconds across the wasted span.'),tokens: zod.number().min(1).optional().describe('Token delta across the wasted span.'),+ output_bytes: zod+ .number()+ .min(1)+ .optional()+ .describe('Sum of tool-output sizes across the wasted span.'),}).optional().describe('Effort measured from the log, never estimated.'),diff --git a/products/tasks/skills/analyzing-task-runs/SKILL.md b/products/tasks/skills/analyzing-task-runs/SKILL.mdindex d1875f5c3166..2339d1595c86 100644--- a/products/tasks/skills/analyzing-task-runs/SKILL.md+++ b/products/tasks/skills/analyzing-task-runs/SKILL.md@@ -91,8 +91,9 @@ step failed and why, then call the `finish` tool with status `failed`.below it.- `wasted_effort` is measured, never estimated: bracket the wasted span with its start and endline numbers, then count the tool calls between them, subtract the timestamps for `seconds`,- and sum completed turns wholly inside the span for `tokens`. Report every dimension you can- measure; omit the ones you cannot.+ sum completed turns wholly inside the span for `tokens`, and sum tool-output sizes for+ `output_bytes`. Report every dimension you can measure; omit the ones you cannot. A pattern+ spread over separate spans is the sum of its spans, never one first-to-last bracket.- Logs from some runtimes lack the agent's narration; do not treat missing narration as evidenceof anything.- The log contains user code and prompts. Use them only to classify; never copy source code,diff --git a/products/tasks/skills/analyzing-task-runs/references/insight-schema.md b/products/tasks/skills/analyzing-task-runs/references/insight-schema.mdindex 315f810d07c8..10c0d3ab3baa 100644--- a/products/tasks/skills/analyzing-task-runs/references/insight-schema.md+++ b/products/tasks/skills/analyzing-task-runs/references/insight-schema.md@@ -12,7 +12,7 @@ specific error when something does not check out; fix and retry once, then drop"observation": "<what happened, 1-3 sentences, 80-500 chars>","evidence": [{- "quote": "<verbatim span copied from your jq query output, 20-300 chars>",+ "quote": "<verbatim span copied from your jq query output, 10-300 chars>","evidence_type": "transcript_quote | command_output | measured_count"}],@@ -54,9 +54,14 @@ specific error when something does not check out; fix and retry once, then drop- `tokens` — sum completed turns wholly inside the wasted span. Pi records `totalTokens` on`turn_completed`; ACP may record it in `_posthog/turn_complete`. Omit tokens for a partialturn or a completion without usage.+ - `output_bytes` — sum of tool-output sizes across the span (the output-bytes recipe). Works in+ both formats even when the log has no token records.If a dimension cannot be measured from the log or its measured value is zero, leave it out —do not estimate.-- `recurrence` anchors: `every_run_in_this_repo` — structural, any agent in this repo hits it;+ When the same pattern occurs in separate, non-contiguous spans, measure each span on its own and+ report the sum — never bracket from the first occurrence to the last, because that counts the+ unrelated work in between as waste.+- `recurrence` anchors: `every_run_in_this_repo` — structural to the repo or its sandbox image, any agent there hits it;`runs_touching_this_area` — conditional on the task area; `one_off` — specific to this run.- `confidence_basis`: `directly_observed` — visible in the transcript; `inferred` — plausible butnot directly evidenced. Never report a numeric confidence.diff --git a/products/tasks/skills/analyzing-task-runs/references/log-schema.md b/products/tasks/skills/analyzing-task-runs/references/log-schema.mdindex c8bccce0e78a..ebdf38dd895b 100644--- a/products/tasks/skills/analyzing-task-runs/references/log-schema.md+++ b/products/tasks/skills/analyzing-task-runs/references/log-schema.md@@ -153,6 +153,23 @@ turns, or a completion has no usage, omit `tokens`:sed -n '<start>,<end>p' <log> | jq -rs 'def token_total: if type == "number" then . elif type == "object" then (.totalTokens // ((.inputTokens // 0) + (.outputTokens // 0) + (.cachedReadTokens // 0) + (.cachedWriteTokens // 0))) else empty end; [.[] | if .type == "pi_event" and .event.type == "turn_completed" then .event.totalTokens elif .notification.method == "_posthog/turn_complete" then (.notification.params.usage | token_total) else empty end | select(type == "number" and . > 0)] | if length > 0 then add else "insufficient completed-turn token records in span" end'```+Tool-output bytes across the span — works in both formats, even when the log has no token+records. Pi:++```sh+sed -n '<start>,<end>p' <log> | jq -rs '[.[] | select(.event.type=="tool_call_updated") | (.event.toolCall.rawOutput | tostring | length)] | add // "no tool outputs in span"'+```++ACP:++```sh+sed -n '<start>,<end>p' <log> | jq -rs '[.[] | select(.notification.params.update.sessionUpdate=="tool_call_update") | (.notification.params.update.rawOutput | tostring | length)] | add // "no tool outputs in span"'+```++When the same pattern occurs in separate, non-contiguous spans, measure each span with these+recipes and report the sum. Never bracket from the first occurrence to the last — the work in+between is not waste.+### Token-measurement examplesPi records `totalTokens` with each completed turn. These two complete turns fall inside a measureddiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 9d4db3d5b4fc..f23a3a73341a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -80157,6 +80157,11 @@ export namespace Schemas {* @minimum 1*/tokens?: number;+ /**+ * Sum of tool-output sizes across the wasted span.+ * @minimum 1+ */+ output_bytes?: number;}export interface TaskArtifact {