Skip to content

: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.

fix(tasks): reject truncated agent JSON instead of an inner fragment (#93477)

posthog[bot]1f239ca46ade
diff --git a/products/review_hog/backend/temporal/workflow.py b/products/review_hog/backend/temporal/workflow.py
index 6d16e410a46c..f5789d05ce23 100644
--- a/products/review_hog/backend/temporal/workflow.py
+++ b/products/review_hog/backend/temporal/workflow.py
@@ -114,6 +114,9 @@ _ONESHOT_RETRY = RetryPolicy(
initial_interval=timedelta(seconds=30),
backoff_coefficient=2.0,
maximum_interval=timedelta(minutes=4),
+ # Truncated sandbox output stays retryable: the error proves only an unclosed object, not the
+ # output limit — a killed sandbox or half-flushed log tail raises the same type and recovers on
+ # retry. Only the one-shot path can read stop_reason == "max_tokens" and fail fast on it.
)
diff --git a/products/tasks/backend/facade/agents.py b/products/tasks/backend/facade/agents.py
index 296b75c42cc5..332ab2d7543a 100644
--- a/products/tasks/backend/facade/agents.py
+++ b/products/tasks/backend/facade/agents.py
@@ -12,6 +12,7 @@ from products.tasks.backend.logic.services.custom_prompt_internals import (
CustomPromptSandboxContext,
EmptyAgentTurnError,
OutputFn,
+ TruncatedAgentOutputError,
TurnPollResult,
TurnPollTimeout,
create_task_and_trigger,
@@ -29,6 +30,7 @@ __all__ = [
"LocalSkillsCache",
"MultiTurnSession",
"OutputFn",
+ "TruncatedAgentOutputError",
"TurnPollResult",
"TurnPollTimeout",
"create_task_and_trigger",
diff --git a/products/tasks/backend/logic/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.py
index 50f44608d450..d8421cc15cd0 100644
--- a/products/tasks/backend/logic/services/custom_prompt_internals.py
+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py
@@ -984,6 +984,41 @@ def _extract_text(update: dict) -> str | None:
return None
+class TruncatedAgentOutputError(ValueError):
+ """The end-turn text stops inside a JSON object, so no complete object can be read from it.
+
+ A `ValueError` subclass, because every caller already treats extraction failures as one.
+ """
+
+ def __init__(self, label: str):
+ super().__init__(
+ f"Output truncated in {label}: end-turn text stops inside a JSON object, "
+ "so only a fragment of the reply is present"
+ )
+
+
+def _open_object_depth(text: str) -> int:
+ """Count the `{` in `text` that never close, ignoring braces inside string literals."""
+ depth = 0
+ in_string = False
+ escaped = False
+ for char in text:
+ if in_string:
+ if escaped:
+ escaped = False
+ elif char == "\\":
+ escaped = True
+ elif char == '"':
+ in_string = False
+ elif char == '"':
+ in_string = True
+ elif char == "{":
+ depth += 1
+ elif char == "}":
+ depth = max(depth - 1, 0)
+ return depth
+
+
def extract_json_from_text(text: str | None, label: str) -> Any:
"""Extract JSON from text that might contain markdown formatting or surrounding commentary."""
if text is None:
@@ -1007,21 +1042,26 @@ def extract_json_from_text(text: str | None, label: str) -> Any:
except json.JSONDecodeError:
pass
- # 3. Bare JSON object in surrounding text — try each { from the left paired with the last }
- last_brace = text.rfind("}")
- if last_brace != -1:
- start = 0
- while True:
- brace_pos = text.find("{", start)
- if brace_pos == -1 or brace_pos >= last_brace:
- break
- try:
- return json.loads(text[brace_pos : last_brace + 1])
- except json.JSONDecodeError:
- start = brace_pos + 1
+ # 3. Bare JSON object in surrounding text — decode from each { from the left, stopping at the
+ # end of that object, so trailing commentary does not have to be balanced.
+ decoder = json.JSONDecoder()
+ start = 0
+ while (brace_pos := text.find("{", start)) != -1:
+ try:
+ value, _ = decoder.raw_decode(text, brace_pos)
+ except json.JSONDecodeError as e:
+ # A decode that ran to the end of the text is a valid object the reply was cut off inside
+ # — a truncation. Returning a nested object from it would hand the caller a fragment, and
+ # the schema error that follows names a missing field instead of the truncation. A decode
+ # that fails well before the end is just a stray brace in prose, so skip past it.
+ if e.pos >= len(text.rstrip()):
+ raise TruncatedAgentOutputError(label) from e
+ start = brace_pos + 1
+ continue
+ return value
# 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
+ # callers (and operators reading the failure) can tell empty / truncated / fenced / prose apart
# instead of seeing a bare "Expecting value: line 1 column 1 (char 0)".
stripped = text.strip()
try:
@@ -1029,6 +1069,8 @@ def extract_json_from_text(text: str | None, label: str) -> Any:
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 _open_object_depth(text) > 0:
+ raise TruncatedAgentOutputError(label) 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"
diff --git a/products/tasks/backend/tests/test_extract_json_from_text.py b/products/tasks/backend/tests/test_extract_json_from_text.py
index 8706d9edbfb5..ae1f97745793 100644
--- a/products/tasks/backend/tests/test_extract_json_from_text.py
+++ b/products/tasks/backend/tests/test_extract_json_from_text.py
@@ -20,6 +20,8 @@ class TestExtractJsonFromText:
("text_above_and_below_bare_json", f"Here is your answer:\n{JSON_STR}\nHope that helps!"),
("text_above_and_below_generic_block", f"Here is your answer:\n```\n{JSON_STR}\n```\nHope that helps!"),
("text_above_and_below_json_block", f"Here is your answer:\n```json\n{JSON_STR}\n```\nHope that helps!"),
+ ("brace_in_text_below_bare_json", f"{JSON_STR}\nReplace {{name}} before you send it."),
+ ("unmatched_brace_in_text_above_bare_json", f"The reply must start with {{ — here it is:\n{JSON_STR}"),
]
)
def test_extracts_json(self, _name, text):
@@ -39,6 +41,10 @@ class TestExtractJsonFromText:
("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"),
+ # A reply cut off mid-object holds inner objects that parse on their own. Returning one
+ # gives the caller a fragment, and the schema error that follows blames a missing field.
+ ("truncated_with_whole_inner_object", '{"duplicates": [{"id": "1-3-3"}', "Output truncated"),
+ ("truncated_mid_value", '{"duplicates": [{"id": "1-3', "Output truncated"),
]
)
def test_classifies_unparseable_text(self, _name, text, expected_message):