: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(review_hog): ask once for json when a sandbox turn ends in prose (#110047)
posthog[bot]25ae7d056c3f
diff --git a/products/review_hog/backend/reviewer/sandbox/executor.py b/products/review_hog/backend/reviewer/sandbox/executor.pyindex 846078534b33..b0219a65d9e0 100644--- a/products/review_hog/backend/reviewer/sandbox/executor.py+++ b/products/review_hog/backend/reviewer/sandbox/executor.py@@ -11,6 +11,12 @@ _ModelT = TypeVar("_ModelT", bound=BaseModel)logger = logging.getLogger(__name__)+# Sent once when the agent ends its first turn with prose instead of the JSON the step needs.+JSON_RETRY_PROMPT = (+ "Your last reply did not contain the JSON object the task asks for. "+ "Reply now with only that JSON object, matching the schema above. Do not add prose or code fences."+)+async def _run_prompt(prompt: str,@@ -45,6 +51,7 @@ async def _run_prompt(origin_product=TaskOriginProduct.REVIEW_HOG,internal=True,ai_stage=step_name or None,+ json_retry_prompt=JSON_RETRY_PROMPT,)except Exception:logger.exception("Sandbox execution failed")@@ -161,6 +168,7 @@ async def start_sandbox_session(origin_product=TaskOriginProduct.REVIEW_HOG,internal=True,ai_stage=step_name or None,+ json_retry_prompt=JSON_RETRY_PROMPT,)except Exception:logger.exception("Sandbox session start failed")diff --git a/products/review_hog/backend/reviewer/tests/test_executor.py b/products/review_hog/backend/reviewer/tests/test_executor.pyindex 8bd590b89c29..72f47f3d1cfa 100644--- a/products/review_hog/backend/reviewer/tests/test_executor.py+++ b/products/review_hog/backend/reviewer/tests/test_executor.py@@ -7,6 +7,7 @@ from parameterized import parameterizedfrom pydantic import BaseModelfrom products.review_hog.backend.reviewer.sandbox.executor import (+ JSON_RETRY_PROMPT,end_sandbox_session,run_sandbox_review,start_sandbox_session,@@ -55,6 +56,8 @@ class TestRunSandboxReview:assert call_kwargs["origin_product"] == TaskOriginProduct.REVIEW_HOGassert call_kwargs["internal"] is Trueassert call_kwargs["ai_stage"] == "split"+ # Without the retry prompt a prose first turn fails the whole activity and reruns the review.+ assert call_kwargs["json_retry_prompt"] == JSON_RETRY_PROMPT@pytest.mark.asyncioasync def test_context_built_from_explicit_identity(self) -> None:diff --git a/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py b/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.pyindex 52b9874424a6..122c6e04901a 100644--- a/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py+++ b/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py@@ -83,6 +83,7 @@ class MultiTurnSession:on_task_run_created: Callable[[TaskRun], Awaitable[None]] | None = None,max_poll_seconds: int | None = None,fallback_from_text: Callable[[str], _ModelT] | None = None,+ json_retry_prompt: str | None = None,workflow_id_prefix: str | None = None,mcp_builtin_agent_key: MCPBuiltInAgentKey | None = None,mcp_credential_owner_id: int | None = None,@@ -106,6 +107,11 @@ class MultiTurnSession:to persist. Single-turn callers (e.g. the Signals scout, whose summary is afree-text markdown close-out) use this so an unparseable end-turn no longerdiscards the entire run and its scan-position close-out.++ `json_retry_prompt`, if given, is sent once as a follow-up turn on the same+ session when the first turn does not parse/validate against `model`. The agent+ keeps its context, so it can restate its answer as JSON without a new sandbox+ run. `fallback_from_text` applies only if the retry turn fails too."""session, last_message = await cls.start_raw(prompt=prompt,@@ -127,8 +133,24 @@ class MultiTurnSession:mcp_gateway_server_ids=mcp_gateway_server_ids,output_schema=output_schema,)+ # A retry turn that fails to run is not a parse failure, so it must never reach the salvage path.+ salvageable = Truetry:- parsed = cls._parse_and_validate(last_message, model, label="initial turn")+ try:+ parsed = cls._parse_and_validate(last_message, model, label="initial turn")+ except Exception as e:+ if json_retry_prompt is None:+ raise+ logger.warning(+ "multi_turn: end-turn did not validate against %s for run=%s, asking for JSON once (%s)",+ model.__name__,+ session.task_run.id,+ e,+ )+ salvageable = False+ retry_message = await session.send_followup_raw(json_retry_prompt, label="initial turn json retry")+ salvageable = True+ parsed = cls._parse_and_validate(retry_message, model, label="initial turn json retry")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@@ -136,6 +158,7 @@ class MultiTurnSession:# a Temporal cancellation (CancelledError), which must propagate and fail the run.if (fallback_from_text is not None+ and salvageableand last_message is not Noneand not isinstance(e, asyncio.CancelledError)):diff --git a/products/tasks/backend/tests/test_multi_turn_session.py b/products/tasks/backend/tests/test_multi_turn_session.pyindex eae3cfcc9dc4..41d9d8ef8085 100644--- a/products/tasks/backend/tests/test_multi_turn_session.py+++ b/products/tasks/backend/tests/test_multi_turn_session.py@@ -1618,6 +1618,52 @@ class TestMultiTurnSessionStartFallback:fallback.assert_not_called()session.end.assert_awaited_once() # type: ignore[attr-defined]+ @parameterized.expand(+ [+ ("retry_recovers", json.dumps({"value": "ok"}), _Resp(value="ok")),+ ("retry_still_prose", "still prose", None),+ ]+ )+ @pytest.mark.asyncio+ async def test_json_retry_prompt_asks_once_on_the_same_session(self, _name, retry_reply, expected):+ session = self._fake_session()+ followup_mock = AsyncMock(return_value=retry_reply)+ session.send_followup_raw = followup_mock # type: ignore[method-assign]++ with patch.object(MultiTurnSession, "start_raw", new=AsyncMock(return_value=(session, "prose only"))):+ if expected is None:+ with pytest.raises(ValueError):+ await MultiTurnSession.start(prompt="x", context=MagicMock(), model=_Resp, json_retry_prompt="JSON")+ else:+ _, parsed = await MultiTurnSession.start(+ prompt="x", context=MagicMock(), model=_Resp, json_retry_prompt="JSON"+ )+ assert parsed == expected++ followup_mock.assert_awaited_once()+ assert followup_mock.await_args is not None+ assert followup_mock.await_args.args[0] == "JSON"+ if expected is None:+ assert session.end.await_args.kwargs.get("status") == "failed" # type: ignore[attr-defined]+ else:+ session.end.assert_not_awaited() # type: ignore[attr-defined]++ @pytest.mark.asyncio+ async def test_failed_json_retry_turn_never_salvages(self):+ # A retry turn that times out is an execution failure, so the fallback must not turn it into a result.+ session = self._fake_session()+ session.send_followup_raw = AsyncMock(side_effect=RuntimeError("poll timed out")) # type: ignore[method-assign]+ fallback = MagicMock()++ with patch.object(MultiTurnSession, "start_raw", new=AsyncMock(return_value=(session, "prose only"))):+ with pytest.raises(RuntimeError):+ await MultiTurnSession.start(+ prompt="x", context=MagicMock(), model=_Resp, json_retry_prompt="JSON", fallback_from_text=fallback+ )++ fallback.assert_not_called()+ assert session.end.await_args.kwargs.get("status") == "failed" # type: ignore[attr-defined]+class TestPollForTurnConnectionDrop:"""poll_for_turn runs for many minutes while the activity's pooled DB connection sits idle;