: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): keep schema runs open for the session that drives them (#110141)
Alessandro Pogliaghie1c3c9164351
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex c2b6b4b1655c..9b34cb8f08a7 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -3443,7 +3443,7 @@ def set_task_run_output(run.output = _apply_caller_output(existing, output, merged)run.save(update_fields=["output", "updated_at"])_refresh_self_driving_quota_for_pr(run, existing.get("pr_url"))- if task.json_schema:+ if task.json_schema and not (run.state or {}).get("caller_ends_run"):signal_workflow_completion(run.id, TaskRun.Status.COMPLETED, None)run.publish_stream_state_event()_post_slack_update_for_pr(run)diff --git a/products/tasks/backend/logic/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.pyindex c53699577701..95da897fbdae 100644--- a/products/tasks/backend/logic/services/custom_prompt_internals.py+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py@@ -78,6 +78,9 @@ FAILED_PROGRESS_STATUS = "failed"# side-channels above._PROMPT_ECHO_UPDATES = frozenset({"user_message", "user_message_chunk"})+STRUCTURED_OUTPUT_TOOL_NAME = "StructuredOutput"+_TOOL_CALL_UPDATES = frozenset({"tool_call", "tool_call_update"})+@dataclass(frozen=True)class AgentError:@@ -275,9 +278,11 @@ async def create_task_and_trigger(posthog_mcp_scopes: PosthogMcpScopes = (context.posthog_mcp_scopes if context.posthog_mcp_scopes is not None else "full")- extra_run_state: dict[str, Any] | None = None+ extra_run_state: dict[str, Any] = {}if context.mcp_exclude_tools:- extra_run_state = {"mcp_exclude_tools": list(context.mcp_exclude_tools)}+ extra_run_state["mcp_exclude_tools"] = list(context.mcp_exclude_tools)+ if output_schema:+ extra_run_state["caller_ends_run"] = Truetask = await sync_to_async(Task.create_and_run)(team=team,title=title,@@ -918,7 +923,7 @@ def _check_logs(task_run, skip_lines: int = 0) -> TurnLogState:if text:trailing_parts.append(text)trailing_parts.reverse()- latest_text = "".join(trailing_parts) if trailing_parts else None+ latest_text = "".join(trailing_parts) if trailing_parts else _structured_output_text(parsed_updates)# A refused turn must not surface its partial text — the caller would mistake it for the# turn's real response.if refused:@@ -950,6 +955,20 @@ def _check_logs(task_run, skip_lines: int = 0) -> TurnLogState:)+def _structured_output_text(updates: list[dict]) -> str | None:+ for update in reversed(updates):+ if update.get("sessionUpdate") not in _TOOL_CALL_UPDATES:+ continue+ meta = update.get("_meta")+ claude_meta = meta.get("claudeCode") if isinstance(meta, dict) else None+ if not isinstance(claude_meta, dict) or claude_meta.get("toolName") != STRUCTURED_OUTPUT_TOOL_NAME:+ continue+ raw_input = update.get("rawInput")+ if isinstance(raw_input, dict) and raw_input:+ return json.dumps(raw_input)+ return None++def _is_failed_progress(notification: dict) -> bool:"""True for a `_posthog/progress` notification carrying the failed/cancelled status the workflow'sexception and cancel handlers emit before writing the terminal TaskRun status."""diff --git a/products/tasks/backend/tests/agent_log_fixtures.py b/products/tasks/backend/tests/agent_log_fixtures.pyindex 73d3c9db9b90..5942ae92db5f 100644--- a/products/tasks/backend/tests/agent_log_fixtures.py+++ b/products/tasks/backend/tests/agent_log_fixtures.py@@ -38,6 +38,25 @@ def _tool_call_line(name: str = "grep") -> str:)+def _structured_output_line(raw_input: dict) -> str:+ return json.dumps(+ {+ "notification": {+ "method": "session/update",+ "params": {+ "update": {+ "sessionUpdate": "tool_call_update",+ "_meta": {"claudeCode": {"toolName": "StructuredOutput"}},+ "toolCallId": "toolu_structured",+ "rawInput": raw_input,+ "title": "StructuredOutput",+ }+ },+ }+ }+ )++def _agent_message_chunk_line(text: str) -> str:# The agent sometimes streams its response as consecutive agent_message_chunk slices;# _check_logs concatenates them when reconstructing the turn's final message.diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex b1c9e0191a63..b53151ad61bf 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -7695,6 +7695,37 @@ class TestTaskRunAPI(BaseTaskAPITest):run.refresh_from_db()self.assertEqual(run.output, {"summary": "Final result"})+ @parameterized.expand(+ [+ ("agent_owned_run", {}, 1),+ ("caller_ended_run", {"caller_ends_run": True}, 0),+ ]+ )+ @patch("products.tasks.backend.facade.api.signal_workflow_completion")+ def test_set_output_completes_a_schema_run_unless_the_caller_ends_it(+ self, _name, run_state, expected_signals, mock_signal_workflow_completion+ ):+ task = self.create_task()+ task.json_schema = {+ "type": "object",+ "properties": {"summary": {"type": "string"}},+ "required": ["summary"],+ "additionalProperties": False,+ }+ task.save(update_fields=["json_schema"])+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS, state=run_state)++ response = self.client.patch(+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/set_output/",+ {"output": {"summary": "Final result"}},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(mock_signal_workflow_completion.call_count, expected_signals)+ run.refresh_from_db()+ self.assertEqual(run.output, {"summary": "Final result"})+@patch("products.tasks.backend.models.TaskRun.publish_stream_state_event")def test_set_output_publishes_stream_state_event(self, mock_publish_stream_state_event):task = self.create_task()diff --git a/products/tasks/backend/tests/test_multi_turn_session.py b/products/tasks/backend/tests/test_multi_turn_session.pyindex 41d9d8ef8085..61c2ed5846c5 100644--- a/products/tasks/backend/tests/test_multi_turn_session.py+++ b/products/tasks/backend/tests/test_multi_turn_session.py@@ -40,6 +40,7 @@ from products.tasks.backend.tests.agent_log_fixtures import (_cost_less_usage_update_line,_end_turn_line,_progress_line,+ _structured_output_line,_tool_call_line,_usage_update_line,_user_message_line,@@ -82,6 +83,21 @@ class TestPollForTurnEmptyEndTurn:assert exc_info.value.total_lines == len(turn_1) + len(turn_2_empty)assert exc_info.value.printed_lines >= 0+ @pytest.mark.asyncio+ async def test_structured_output_tool_call_is_the_turn_message(self):+ turn_1 = [_structured_output_line({"word": "alpha"}), _end_turn_line()]+ turn_2 = [_user_message_line("next"), _structured_output_line({"word": "beta", "count": 2}), _end_turn_line()]+ log = "\n".join(turn_1 + turn_2)++ with (+ patch("posthog.storage.object_storage.read", return_value=log),+ patch("asyncio.sleep", new=AsyncMock()),+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),+ ):+ turn = await poll_for_turn(FakeTaskRun(), skip_lines=len(turn_1))++ assert json.loads(turn.last_message) == {"word": "beta", "count": 2}+@pytest.mark.asyncioasync def test_text_before_end_turn_across_polls_is_not_empty(self):"""When agent_message arrives in one poll and end_turn in the next, poll_for_turn@@ -1466,6 +1482,18 @@ class TestCreateTaskAndTriggerForwardsContext:persisted = await sync_to_async(TaskRun.objects.get)(id=task_run.id)assert persisted.state.get("pending_user_message") == expected_pending_message+ @pytest.mark.asyncio+ @pytest.mark.parametrize(("output_schema", "expected_flag"), [({"type": "object"}, True), (None, None)])+ async def test_marks_a_schema_run_as_ended_by_the_caller(self, output_schema, expected_flag):+ team, user = await sync_to_async(self._setup_team_and_user)()+ context = CustomPromptSandboxContext(team_id=team.id, user_id=user.id)++ with patch("products.tasks.backend.temporal.client.execute_task_processing_workflow"):+ _, task_run = await create_task_and_trigger("prompt", context, output_schema=output_schema)++ persisted = await sync_to_async(TaskRun.objects.get)(id=task_run.id)+ assert persisted.state.get("caller_ends_run") is expected_flag+@pytest.mark.asyncio@pytest.mark.parametrize("model, runtime_adapter, reasoning_effort, initial_permission_mode",