: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): detect the end of pi turns in the turn poller (#130068)
Georgiy Tarasov621e5f47b5a5
diff --git a/products/tasks/backend/logic/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.pyindex a380a55752d2..88eae2fb8c2e 100644--- a/products/tasks/backend/logic/services/custom_prompt_internals.py+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py@@ -92,6 +92,9 @@ _PROMPT_ECHO_UPDATES = frozenset({"user_message", "user_message_chunk"})STRUCTURED_OUTPUT_TOOL_NAME = "StructuredOutput"_TOOL_CALL_UPDATES = frozenset({"tool_call", "tool_call_update"})+# Pi reports the normal end of a turn as "stop". ACP adapters report the same state as "end_turn".+_PI_END_TURN_STOP_REASON = "stop"+@dataclass(frozen=True)class AgentError:@@ -1089,10 +1092,57 @@ def _is_subagent_update(update: dict[str, object]) -> bool:return False+def _pi_event(entry: dict) -> dict | None:+ """The conversation event of a log entry that a Pi run wrote in its native format."""+ event = entry.get("event") if entry.get("type") == "pi_event" else None+ return event if isinstance(event, dict) else None+++def _pi_turn_text(lines: list[str]) -> str | None:+ """The last assistant text of the Pi turn that ends `lines`.++ Pi logs one line for each streamed text delta, so a turn's text can span several polls and+ the lines of one poll can hold only its tail. This reads back through the whole log for that+ reason. Each delta carries its own whitespace, so this joins them unstripped: `_extract_text`+ strips each entry, which deletes the spaces between words.++ Pi writes a compaction summary as one assistant chunk directly after the completed `compacting`+ status, with the same timestamp. That chunk is context for the model and not the answer, so this+ drops it. Text from before a compaction is the answer only when no text follows the compaction.+ """+ parts: list[str] = []+ earliest_chunk_timestamp: object = None+ turn_closed = False+ for line in reversed(lines):+ try:+ event = _pi_event(json.loads(line))+ except json.JSONDecodeError:+ continue+ if event is None:+ continue+ event_type = event.get("type")+ if event_type == "assistant_message_chunk":+ content = event.get("content")+ if isinstance(content, dict) and isinstance(content.get("text"), str):+ parts.append(content["text"])+ earliest_chunk_timestamp = event.get("timestamp")+ elif event_type == "runtime_status" and event.get("status") == "compacting":+ if parts and event.get("isComplete") and earliest_chunk_timestamp == event.get("timestamp"):+ parts.pop()+ if parts:+ break+ elif parts or event_type == "user_message" or (event_type == "turn_completed" and turn_closed):+ break+ elif event_type == "turn_completed":+ turn_closed = True+ return "".join(reversed(parts)).strip() or None++def _check_logs(task_run, skip_lines: int = 0) -> TurnLogState:"""Parse S3 logs. When skip_lines > 0, only lines after that offset are inspected for end_turnand agent messages. This avoids re-parsing the entire log on every poll cycle.+ The end of a Pi turn is the exception: its text comes from the whole log (see `_pi_turn_text`).`refused` flags a provider refusal (stopReason "refusal") — a terminal turnstate: without it the poll loop would wait out its whole budget on a turn that already died."""@@ -1120,6 +1170,7 @@ def _check_logs(task_run, skip_lines: int = 0) -> TurnLogState:)lines_to_parse = all_lines[skip_lines:]agent_finished = False+ pi_turn_ended = Falserefused = False# Collect all parsed session updates so we can walk backwards at the end.parsed_updates: list[dict] = []@@ -1131,6 +1182,12 @@ def _check_logs(task_run, skip_lines: int = 0) -> TurnLogState:entry = json.loads(line)except json.JSONDecodeError:continue+ pi_event = _pi_event(entry)+ if pi_event is not None:+ if pi_event.get("type") == "turn_completed" and pi_event.get("stopReason") == _PI_END_TURN_STOP_REASON:+ agent_finished = True+ pi_turn_ended = True+ continuenotification = entry.get("notification")if not isinstance(notification, dict):continue@@ -1179,6 +1236,8 @@ def _check_logs(task_run, skip_lines: int = 0) -> TurnLogState:trailing_parts.append(text)trailing_parts.reverse()latest_text = "".join(trailing_parts) if trailing_parts else _structured_output_text(parsed_updates)+ if pi_turn_ended:+ latest_text = _pi_turn_text(all_lines)# A refused turn must not surface its partial text — the caller would mistake it for the# turn's real response.if refused:diff --git a/products/tasks/backend/tests/agent_log_fixtures.py b/products/tasks/backend/tests/agent_log_fixtures.pyindex bd99b3f58f0f..681132819632 100644--- a/products/tasks/backend/tests/agent_log_fixtures.py+++ b/products/tasks/backend/tests/agent_log_fixtures.py@@ -79,6 +79,28 @@ def _end_turn_line() -> str:return json.dumps({"notification": {"result": {"stopReason": "end_turn"}}})+def _pi_event_line(event: dict) -> str:+ return json.dumps({"type": "pi_event", "event": event})+++def _pi_text_line(text: str, timestamp: int = 1) -> str:+ return _pi_event_line(+ {"type": "assistant_message_chunk", "timestamp": timestamp, "content": {"type": "text", "text": text}}+ )+++def _pi_compaction_lines(summary: str | None, timestamp: int = 5) -> list[str]:+ lines = [+ _pi_event_line({"type": "runtime_status", "timestamp": timestamp - 1, "status": "compacting"}),+ _pi_event_line({"type": "runtime_status", "timestamp": timestamp, "status": "compacting", "isComplete": True}),+ ]+ return [*lines, _pi_text_line(summary, timestamp=timestamp)] if summary else lines+++def _pi_turn_completed_line(stop_reason: str = "stop") -> str:+ return _pi_event_line({"type": "turn_completed", "stopReason": stop_reason})++def _refusal_line() -> str:return json.dumps({"notification": {"result": {"stopReason": "refusal"}}})diff --git a/products/tasks/backend/tests/test_multi_turn_session.py b/products/tasks/backend/tests/test_multi_turn_session.pyindex 69f0b71bce05..564036fa4e50 100644--- a/products/tasks/backend/tests/test_multi_turn_session.py+++ b/products/tasks/backend/tests/test_multi_turn_session.py@@ -51,6 +51,10 @@ from products.tasks.backend.tests.agent_log_fixtures import (_console_line,_cost_less_usage_update_line,_end_turn_line,+ _pi_compaction_lines,+ _pi_event_line,+ _pi_text_line,+ _pi_turn_completed_line,_progress_line,_structured_output_line,_tool_call_line,@@ -957,6 +961,12 @@ class TestPollForTurnTimeoutDiagnosis:# mid-run stall.("prompt_echo_only", lambda: _user_message_line("prompt"), "no_turn_output"),("worked_then_silent", lambda: _agent_message_line("still working"), "stalled_after_output"),+ # Only Pi's "stop" ends a turn normally, so a failed turn must not return its partial text as the answer.+ (+ "pi_turn_ended_with_error",+ lambda: "\n".join([_pi_text_line("partial"), _pi_turn_completed_line("error")]),+ "stalled_after_output",+ ),])@pytest.mark.asyncio@@ -1002,6 +1012,133 @@ class TestPollForTurnTimeoutDiagnosis:assert exc_info.value.turn_relevant_lines == 3+class TestPollForTurnPiLog:+ _FIRST_TURN = [_pi_text_line("first answer"), _pi_turn_completed_line()]+ _TOOL_CALL = [+ _pi_event_line({"type": "tool_call_started", "toolCall": {"id": "call-1"}}),+ _pi_event_line({"type": "tool_call_updated", "toolCall": {"id": "call-1", "status": "completed"}}),+ ]++ @staticmethod+ async def _poll(polls: list[list[str]], skip_lines: int = 0) -> TurnPollResult:+ logs = iter("\n".join(lines) for lines in polls)+ fake_task_run = FakeTaskRun()+ with (+ patch("posthog.storage.object_storage.read", side_effect=lambda *_args, **_kwargs: next(logs)),+ patch("asyncio.sleep", new=AsyncMock()),+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),+ patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake_task_run),+ ):+ return await poll_for_turn(fake_task_run, skip_lines=skip_lines)++ @parameterized.expand(+ [+ (+ "keeps_whitespace_between_deltas",+ [[_pi_text_line("two"), _pi_text_line(" words"), _pi_text_line("\n"), _pi_turn_completed_line()]],+ 0,+ "two words",+ ),+ (+ "text_spans_polls",+ [+ [_pi_text_line("start of")],+ [_pi_text_line("start of"), _pi_text_line(" the answer"), _pi_turn_completed_line()],+ ],+ 0,+ "start of the answer",+ ),+ (+ "turn_end_arrives_alone",+ [[_pi_text_line("the answer")], [_pi_text_line("the answer"), _pi_turn_completed_line()]],+ 0,+ "the answer",+ ),+ (+ "side_channel_lines_after_turn_end",+ [[_pi_text_line("the answer"), _pi_turn_completed_line(), _console_line("agentsh network events")]],+ 0,+ "the answer",+ ),+ (+ "text_before_a_tool_call_is_not_the_answer",+ [[_pi_text_line("checking"), *_TOOL_CALL, _pi_text_line("the answer"), _pi_turn_completed_line()]],+ 0,+ "the answer",+ ),+ (+ "compaction_summary_after_the_answer_is_not_the_answer",+ [[_pi_text_line("the answer"), *_pi_compaction_lines("internal summary"), _pi_turn_completed_line()]],+ 0,+ "the answer",+ ),+ (+ "compaction_summary_before_the_answer_is_not_part_of_it",+ [+ [+ _pi_text_line("earlier text"),+ *_pi_compaction_lines("internal summary"),+ _pi_text_line("the answer", timestamp=9),+ _pi_turn_completed_line(),+ ]+ ],+ 0,+ "the answer",+ ),+ (+ "compaction_without_a_summary_keeps_the_whole_answer",+ [+ [+ *_pi_compaction_lines(None),+ _pi_text_line("the", timestamp=9),+ _pi_text_line(" answer", timestamp=9),+ _pi_turn_completed_line(),+ ]+ ],+ 0,+ "the answer",+ ),+ (+ "earlier_turn_is_not_the_answer",+ [+ [+ *_FIRST_TURN,+ _pi_event_line({"type": "user_message"}),+ _pi_text_line("the answer"),+ _pi_turn_completed_line(),+ ]+ ],+ len(_FIRST_TURN),+ "the answer",+ ),+ ]+ )+ @pytest.mark.asyncio+ async def test_stop_returns_the_final_message(+ self, _name: str, polls: list[list[str]], skip_lines: int, expected: str+ ):+ turn = await self._poll(polls, skip_lines=skip_lines)++ assert turn.last_message == expected+ assert turn.total_lines == len(polls[-1])++ @parameterized.expand(+ [+ ("after_prompt_echo", [_pi_event_line({"type": "user_message"}), _pi_turn_completed_line()]),+ ("without_prompt_echo", [_pi_turn_completed_line()]),+ ("only_a_compaction_summary", [*_pi_compaction_lines("internal summary"), _pi_turn_completed_line()]),+ (+ "after_tool_call_only",+ [_pi_event_line({"type": "user_message"}), *_TOOL_CALL, _pi_turn_completed_line()],+ ),+ ]+ )+ @pytest.mark.asyncio+ async def test_turn_without_text_is_empty_and_does_not_reuse_earlier_text(self, _name: str, turn: list[str]):+ with pytest.raises(EmptyAgentTurnError):+ await self._poll([[*self._FIRST_TURN, *turn]], skip_lines=len(self._FIRST_TURN))++class TestPollForTurnTerminalDrain:"""Terminal-status drain must recover an agent_message from *this* turn only.