: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(signals): fall back to raw text when scout end-turn JSON parse fails (#64409)
Andrew Maguirea3cc69f0b002
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.pyindex 7cd8faac6313..9955725494eb 100644--- a/products/signals/backend/scout_harness/runner.py+++ b/products/signals/backend/scout_harness/runner.py@@ -338,6 +338,11 @@ async def _spawn_and_run(# ACTIVITY_SLACK_S) cancels the activity. Default budget (MAX_POLL_SECONDS) exceeds the# ceiling and would let the activity die before salvage could return the written summary.max_poll_seconds=DEFAULT_MAX_RUNTIME_S,+ # The close-out is free-text markdown — if the agent ends with prose or malformed JSON+ # instead of a SignalScoutRunSummary object, keep the raw text as the summary rather than+ # failing the whole run. A failed run never finalizes, so its scan-position close-out is+ # lost and the next run inherits a doubled scan delta.+ fallback_from_text=lambda text: SignalScoutRunSummary(summary=text),)try:# Persist the agent's end-of-turn close-out so non-emitting runs leave adiff --git a/products/tasks/backend/services/custom_prompt_internals.py b/products/tasks/backend/services/custom_prompt_internals.pyindex c31af65ba427..279d5a0472cf 100644--- a/products/tasks/backend/services/custom_prompt_internals.py+++ b/products/tasks/backend/services/custom_prompt_internals.py@@ -736,5 +736,19 @@ def extract_json_from_text(text: str | None, label: str) -> Any:except json.JSONDecodeError:start = brace_pos + 1- # 4. Last resort — try the whole text as-is- return json.loads(text)+ # 4. Last resort — try the whole text as-is, then surface a classified error so+ # callers (and operators reading the failure) can tell empty / fenced / prose apart+ # instead of seeing a bare "Expecting value: line 1 column 1 (char 0)".+ stripped = text.strip()+ try:+ return json.loads(stripped)+ except json.JSONDecodeError as e:+ if not stripped:+ raise ValueError(f"No JSON in {label}: end-turn text was empty or whitespace-only") from e+ if "```" in text:+ raise ValueError(+ f"No valid JSON in {label}: text has a code fence but its contents did not parse as JSON"+ ) from e+ raise ValueError(+ f"No JSON in {label}: end-turn text was prose with no JSON object (starts with {stripped[:60]!r})"+ ) from ediff --git a/products/tasks/backend/services/custom_prompt_multi_turn_runner.py b/products/tasks/backend/services/custom_prompt_multi_turn_runner.pyindex 2984e7349ca0..c63c4b9c8037 100644--- a/products/tasks/backend/services/custom_prompt_multi_turn_runner.py+++ b/products/tasks/backend/services/custom_prompt_multi_turn_runner.py@@ -65,6 +65,7 @@ class MultiTurnSession:internal: bool = False,on_task_run_created: Callable[[TaskRun], Awaitable[None]] | None = None,max_poll_seconds: int | None = None,+ fallback_from_text: Callable[[str], _ModelT] | None = None,) -> tuple[MultiTurnSession, _ModelT]:"""Start a multi-turn sandbox session and wait for the first structured response.@@ -75,6 +76,14 @@ class MultiTurnSession:can resolve the run by id instead of 404ing on a not-yet-created row.`max_poll_seconds` caps each turn's poll budget — see the field docstring.++ `fallback_from_text`, if given, salvages a turn whose text the agent *did*+ produce but which failed to parse/validate against `model` (empty, prose, or+ malformed JSON). Instead of failing the whole run, the callback builds a+ `model` instance from the raw end-turn text so the caller still gets a result+ to persist. Single-turn callers (e.g. the Signals scout, whose summary is a+ free-text markdown close-out) use this so an unparseable end-turn no longer+ discards the entire run and its scan-position close-out."""session, last_message = await cls.start_raw(prompt=prompt,@@ -93,6 +102,31 @@ class MultiTurnSession:try:parsed = cls._parse_and_validate(last_message, model, label="initial turn")except (Exception, asyncio.CancelledError) as e:+ # Salvage path: the agent produced text but it didn't parse/validate. Rather+ # than discarding the whole run, build the model from the raw text so the caller+ # can still persist a (degraded) result. Only for real parse failures — never for+ # a Temporal cancellation (CancelledError), which must propagate and fail the run.+ if (+ fallback_from_text is not None+ and last_message is not None+ and not isinstance(e, asyncio.CancelledError)+ ):+ logger.warning(+ "multi_turn: end-turn did not validate against %s for run=%s — salvaging raw text (%s)",+ model.__name__,+ session.task_run.id,+ e,+ )+ try:+ salvaged = fallback_from_text(last_message)+ except Exception:+ # A raising fallback (e.g. a stricter model that also rejects the raw text)+ # must not escape before teardown — the caller never received the session,+ # so its own finally is unreachable and the run would wedge in IN_PROGRESS.+ # Fall through to end the run as failed on the original parse error.+ logger.exception("multi_turn: fallback_from_text raised for run=%s", session.task_run.id)+ else:+ return session, salvaged# `start()` is about to raise so the caller never receives the session to run its# own teardown. End it here so a first-turn parse failure (or a Temporal timeout,# which raises CancelledError — a BaseException) doesn't leave the run wedged indiff --git a/products/tasks/backend/tests/test_extract_json_from_text.py b/products/tasks/backend/tests/test_extract_json_from_text.pyindex 438c209eb597..fd8c8a57c268 100644--- a/products/tasks/backend/tests/test_extract_json_from_text.py+++ b/products/tasks/backend/tests/test_extract_json_from_text.py@@ -32,3 +32,26 @@ class TestExtractJsonFromText:def test_invalid_json_raises(self):with pytest.raises(Exception):extract_json_from_text("not json at all", label="test")++ @parameterized.expand(+ [+ ("empty_string", "", "empty or whitespace-only"),+ ("whitespace_only", " \n\t ", "empty or whitespace-only"),+ ("prose_only", "I checked everything and found nothing worth surfacing.", "prose with no JSON object"),+ ("fenced_invalid", "```json\nnot: valid json\n```", "code fence but its contents did not parse"),+ ]+ )+ def test_classifies_unparseable_text(self, _name, text, expected_message):+ with pytest.raises(ValueError, match=expected_message):+ extract_json_from_text(text, label="initial turn")++ @parameterized.expand(+ [+ ("bare_array", "[1, 2, 3]", [1, 2, 3]),+ ("array_with_whitespace", " [1, 2, 3] ", [1, 2, 3]),+ ]+ )+ def test_still_parses_non_object_json(self, _name, text, expected):+ # The last-resort path must keep parsing valid top-level JSON that isn't an object+ # (arrays, scalars) — only genuinely unparseable text should raise.+ assert extract_json_from_text(text, label="test") == expecteddiff --git a/products/tasks/backend/tests/test_multi_turn_session.py b/products/tasks/backend/tests/test_multi_turn_session.pyindex 0eeae1e0c785..f220f151b94b 100644--- a/products/tasks/backend/tests/test_multi_turn_session.py+++ b/products/tasks/backend/tests/test_multi_turn_session.py@@ -1,4 +1,5 @@import json+import asynciofrom pathlib import Pathimport pytest@@ -1311,3 +1312,98 @@ class TestCreateTaskAndTriggerForwardsContext:await create_task_and_trigger("prompt", context, ai_stage=ai_stage)assert mock_create.call_args.kwargs["ai_stage"] == expected+++class TestMultiTurnSessionStartFallback:+ """start() salvages an end-turn the agent produced but that didn't validate against the+ model (empty, prose, or malformed JSON) via fallback_from_text, instead of failing the+ whole run. Without a fallback — or on a cancellation — it still fails and ends the run."""++ def _fake_session(self) -> MultiTurnSession:+ session = MultiTurnSession(+ task=object(), # type: ignore[arg-type]+ task_run=FakeTaskRun(), # type: ignore[arg-type]+ _workflow_handle=AsyncMock(),+ )+ session.end = AsyncMock() # type: ignore[method-assign] # ty: ignore[invalid-assignment]+ return session++ @pytest.mark.asyncio+ async def test_salvages_unparseable_text_with_fallback(self):+ # _Resp requires a JSON object with `value`; prose can't validate, so the fallback+ # builds the model from the raw close-out text instead of failing the run.+ session = self._fake_session()+ prose = "No anomalies this run. Scanned 12 commits, remembered the scan marker."++ with patch.object(MultiTurnSession, "start_raw", new=AsyncMock(return_value=(session, prose))):+ returned_session, parsed = await MultiTurnSession.start(+ prompt="x",+ context=MagicMock(),+ model=_Resp,+ fallback_from_text=lambda text: _Resp(value=text),+ )++ assert returned_session is session+ assert parsed == _Resp(value=prose)+ # A salvaged run is NOT ended as failed — the caller persists the result and ends normally.+ session.end.assert_not_awaited() # type: ignore[attr-defined]++ @pytest.mark.asyncio+ async def test_fails_and_ends_run_without_fallback(self):+ session = self._fake_session()++ with patch.object(MultiTurnSession, "start_raw", new=AsyncMock(return_value=(session, "prose only"))):+ with pytest.raises(ValueError):+ await MultiTurnSession.start(prompt="x", context=MagicMock(), model=_Resp)++ session.end.assert_awaited_once() # type: ignore[attr-defined]+ assert session.end.await_args.kwargs.get("status") == "failed" # type: ignore[attr-defined]++ @pytest.mark.asyncio+ async def test_valid_json_parses_without_invoking_fallback(self):+ session = self._fake_session()+ fallback = MagicMock()++ with patch.object(+ MultiTurnSession, "start_raw", new=AsyncMock(return_value=(session, json.dumps({"value": "ok"})))+ ):+ _, parsed = await MultiTurnSession.start(+ prompt="x", context=MagicMock(), model=_Resp, fallback_from_text=fallback+ )++ assert parsed == _Resp(value="ok")+ fallback.assert_not_called()+ session.end.assert_not_awaited() # type: ignore[attr-defined]++ @pytest.mark.asyncio+ async def test_raising_fallback_ends_run_instead_of_escaping(self):+ # A fallback that itself raises (e.g. a stricter model that also rejects the raw text)+ # must not escape start() before teardown — the run is ended as failed, not left wedged.+ session = self._fake_session()++ def boom(_text: str) -> _Resp:+ raise ValueError("stricter model rejects raw text too")++ with patch.object(MultiTurnSession, "start_raw", new=AsyncMock(return_value=(session, "prose only"))):+ with pytest.raises(ValueError):+ await MultiTurnSession.start(prompt="x", context=MagicMock(), model=_Resp, fallback_from_text=boom)++ session.end.assert_awaited_once() # type: ignore[attr-defined]+ assert session.end.await_args.kwargs.get("status") == "failed" # type: ignore[attr-defined]++ @pytest.mark.asyncio+ async def test_cancellation_never_salvages(self):+ # A Temporal cancellation must propagate and fail the run even when a fallback is set —+ # salvaging a cancelled turn would mask a genuine timeout as a degraded success.+ session = self._fake_session()+ fallback = MagicMock()++ with (+ patch.object(MultiTurnSession, "start_raw", new=AsyncMock(return_value=(session, "some text"))),+ patch.object(MultiTurnSession, "_parse_and_validate", side_effect=asyncio.CancelledError()),+ ):+ with pytest.raises(asyncio.CancelledError):+ await MultiTurnSession.start(prompt="x", context=MagicMock(), model=_Resp, fallback_from_text=fallback)++ fallback.assert_not_called()+ session.end.assert_awaited_once() # type: ignore[attr-defined]