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): recover repo selection from an unreadable end turn (#105059)

posthog[bot]eb3a93fb674b
diff --git a/products/tasks/backend/logic/repo_selection/agent.py b/products/tasks/backend/logic/repo_selection/agent.py
index 3f94d044e6e8..6fa400032f6f 100644
--- a/products/tasks/backend/logic/repo_selection/agent.py
+++ b/products/tasks/backend/logic/repo_selection/agent.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import re
import json
import logging
from collections.abc import Callable, Iterable, Mapping
@@ -519,6 +520,41 @@ context and repo names alone.
</jsonschema>"""
+def _names_repository(text: str, repo: str) -> bool:
+ # A longer name that starts with `repo` (`acme/api-client` for `acme/api`) is another repository.
+ # A dot that ends a sentence also ends the name, but a dot before a word (`acme/api.js`) does not.
+ return re.search(rf"(?<![\w.-]){re.escape(repo)}(?![\w-]|\.\w)", text, re.IGNORECASE) is not None
+
+
+def _salvage_repo_selection(text: str, candidate_repos: list[str]) -> RepoSelectionResult:
+ """Read a selection out of an end turn that did not validate against `RepoSelectionResult`.
+
+ A failure here costs the caller its automatic selection, so a reply that names exactly one
+ candidate is still worth keeping. Two or more named candidates leave the conclusion ambiguous:
+ raise instead, because the runner then fails the turn the way it did before this salvage, and
+ the caller keeps its own fallback. Never answer "no repository" from here — callers read that
+ as a decision the agent made.
+
+ A reply that got as far as its `repository` field has stated its choice, so only that value
+ counts. Its `reason` must cite the repositories the agent checked, so a cut-off
+ `{"repository": null, "reason": "checked acme/b...` names a candidate the agent rejected.
+ """
+ stated = re.findall(r'"repository"\s*:\s*(?:null|"([^"]*)")', text)
+ if stated:
+ # The answer comes last, after any tool call or error object that also holds the key.
+ choice = stated[-1].strip().lower()
+ named = {choice} if choice in candidate_repos else set()
+ else:
+ named = {repo for repo in candidate_repos if _names_repository(text, repo)}
+ if len(named) != 1:
+ raise ValueError(f"End-turn text names {len(named)} candidate repositories, so no selection can be read")
+ repository = named.pop()
+ return RepoSelectionResult(
+ repository=repository,
+ reason=f"The agent's answer was not readable, but its reply named only {repository}.",
+ )
+
+
# Tells a pinned pick from an agent's pick when reading a stored `repo_selection` artefact.
PINNED_REPOSITORY_REASON = "The request names this repository as its source."
@@ -672,6 +708,9 @@ async def select_repository(
signal_report_id=signal_report_id,
ai_stage="repo_selection",
internal=True,
+ # An unreadable end turn used to fail the whole selection, and the caller then dropped the
+ # user into a manual repository picker. Read the pick out of the raw reply instead.
+ fallback_from_text=lambda text: _salvage_repo_selection(text, candidate_repos),
)
# Track repo discovery execution (for example, for Slack)
if on_research_session is not None:
diff --git a/products/tasks/backend/logic/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.py
index 1dacc14d0a35..c53699577701 100644
--- a/products/tasks/backend/logic/services/custom_prompt_internals.py
+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py
@@ -4,7 +4,7 @@ import re
import json
import asyncio
import logging
-from collections.abc import Callable
+from collections.abc import Callable, Collection
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
@@ -1080,62 +1080,84 @@ def _open_object_depth(text: str) -> int:
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:
- raise ValueError(f"Text to extract JSON from ({label}) is None")
+def _collect_json_values(text: str) -> tuple[list[Any], bool]:
+ """Read every JSON value `text` holds, in the order the extractor prefers them.
- # 1. ```json ... ``` fenced code block (non-greedy to stop at first closing fence)
- match = re.search(r"```json\s*(.*?)\s*```", text, re.DOTALL)
- if match:
- candidate = match.group(1).strip()
- try:
- return json.loads(candidate)
- except json.JSONDecodeError:
- pass
+ The second element reports a truncation: a decode that runs to the end of the text is a valid
+ object the reply was cut off inside. The scan stops there, so a fragment never joins the list.
+ """
+ values: list[Any] = []
- # 2. ``` ... ``` generic code block that happens to contain JSON
- match = re.search(r"```\s*(.*?)\s*```", text, re.DOTALL)
- if match:
- candidate = match.group(1).strip()
- try:
- return json.loads(candidate)
- except json.JSONDecodeError:
- pass
+ # 1. ```json ... ``` fenced code blocks (non-greedy to stop at each closing fence)
+ # 2. ``` ... ``` generic code blocks that happen to contain JSON
+ for pattern in (r"```json\s*(.*?)\s*```", r"```\s*(.*?)\s*```"):
+ for match in re.finditer(pattern, text, re.DOTALL):
+ try:
+ values.append(json.loads(match.group(1).strip()))
+ except json.JSONDecodeError:
+ continue
- # 3. Bare JSON object in surrounding text — decode from each { from the left, stopping at the
+ # 3. Bare JSON objects 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)
+ value, end_pos = 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
+ # Returning a nested object from a truncated reply 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
+ # that fails well before the end is just a stray brace in prose, so skip past it. The decoder
+ # reports a string that runs off the end of the text at its opening quote, not at the end.
+ if e.pos >= len(text.rstrip()) or e.msg.startswith("Unterminated string"):
+ return values, True
start = brace_pos + 1
continue
- return value
+ values.append(value)
+ start = end_pos
- # 4. Last resort — try the whole text as-is, then surface a classified error so
- # 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()
+ # 4. The whole text as-is, which also covers valid top-level JSON that is not an object.
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 _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"
- ) from e
- raise ValueError(
- f"No JSON in {label}: end-turn text was prose with no JSON object (starts with {stripped[:60]!r})"
- ) from e
+ values.append(json.loads(text.strip()))
+ except json.JSONDecodeError:
+ pass
+ return values, False
+
+
+def extract_json_from_text(text: str | None, label: str, required_keys: Collection[str] | None = None) -> Any:
+ """Extract JSON from text that might contain markdown formatting or surrounding commentary.
+
+ `required_keys` names the fields the caller needs. An agent turn often holds several JSON
+ objects — a tool call, a tool error envelope, a sample query — before the answer, so the last
+ object that carries every required key wins over the first object in the text.
+ """
+ if text is None:
+ raise ValueError(f"Text to extract JSON from ({label}) is None")
+
+ values, truncated = _collect_json_values(text)
+ if required_keys:
+ # The answer comes last, so a cut-off object at the end is the answer and an earlier match is not.
+ if truncated:
+ raise TruncatedAgentOutputError(label)
+ for value in reversed(values):
+ if isinstance(value, dict) and all(key in value for key in required_keys):
+ return value
+ elif values:
+ # Without keys the first value is the answer, so a cut-off object after it does not matter.
+ return values[0]
+ if truncated:
+ raise TruncatedAgentOutputError(label)
+ if values:
+ return values[0]
+
+ # Last resort — surface a classified error so 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()
+ if not stripped:
+ raise ValueError(f"No JSON in {label}: end-turn text was empty or whitespace-only")
+ if _open_object_depth(text) > 0:
+ raise TruncatedAgentOutputError(label)
+ if "```" in text:
+ raise ValueError(f"No valid JSON in {label}: text has a code fence but its contents did not parse as JSON")
+ raise ValueError(f"No JSON in {label}: end-turn text was prose with no JSON object (starts with {stripped[:60]!r})")
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.py
index 7b822c699c8f..52b9874424a6 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
@@ -34,6 +34,16 @@ _EMPTY_TURN_RETRY_NUDGE = "\n\nPlease respond now with the JSON object matching
_ModelT = TypeVar("_ModelT", bound=BaseModel)
+def _required_model_keys(model: type[BaseModel]) -> set[str]:
+ """Names a `model` instance cannot be built without, so the extractor can spot the answer object.
+
+ A model whose fields all have defaults validates any stray object as an empty answer, so its
+ declared names mark the answer instead.
+ """
+ keys = {field.alias or name: field.is_required() for name, field in model.model_fields.items()}
+ return {key for key, required in keys.items() if required} or set(keys)
+
+
# Mutable: per-turn log offsets (`log_lines_seen`, `printed_lines`) are updated in place.
@dataclass(frozen=False)
class MultiTurnSession:
@@ -354,7 +364,7 @@ class MultiTurnSession:
@staticmethod
def _parse_and_validate(text: str, model: type[_ModelT], label: str) -> _ModelT:
"""Extract JSON from agent text and validate against a Pydantic model."""
- json_data = extract_json_from_text(text=text, label=label)
+ json_data = extract_json_from_text(text=text, label=label, required_keys=_required_model_keys(model))
return model.model_validate(json_data)
async def end(self, *, status: str = "completed", error: str | None = None) -> None:
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 ae1f97745793..352d993c1326 100644
--- a/products/tasks/backend/tests/test_extract_json_from_text.py
+++ b/products/tasks/backend/tests/test_extract_json_from_text.py
@@ -22,6 +22,8 @@ class TestExtractJsonFromText:
("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}"),
+ ("cut_off_object_after_bare_json", f'{JSON_STR}\nNext: {{"step": [1, 2'),
+ ("cut_off_object_after_json_block", f"```json\n{JSON_STR}\n```\nthen {{"),
]
)
def test_extracts_json(self, _name, text):
@@ -45,11 +47,17 @@ class TestExtractJsonFromText:
# 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"),
+ (
+ "truncated_answer_after_a_matching_sample",
+ 'Sample: {"answer": 1}\nFinal:\n{"answer": "hel',
+ "Output truncated",
+ {"answer"},
+ ),
]
)
- def test_classifies_unparseable_text(self, _name, text, expected_message):
+ def test_classifies_unparseable_text(self, _name, text, expected_message, required_keys=None):
with pytest.raises(ValueError, match=expected_message):
- extract_json_from_text(text, label="initial turn")
+ extract_json_from_text(text, label="initial turn", required_keys=required_keys)
@parameterized.expand(
[
@@ -61,3 +69,28 @@ class TestExtractJsonFromText:
# 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") == expected
+
+ @parameterized.expand(
+ [
+ (
+ "error_envelope_before_answer",
+ f'{{"type": "error", "message": "query failed"}}\n{JSON_STR}',
+ ),
+ (
+ "tool_call_and_sample_payload_before_answer",
+ f'{{"tool": "execute-sql"}}\nSample: {{"answer": 1, "other": 2}}\nFinal:\n{JSON_STR}',
+ ),
+ ("answer_in_fence_after_envelope", f'{{"error": "boom"}}\n```json\n{JSON_STR}\n```'),
+ ]
+ )
+ def test_required_keys_pick_the_answer_over_an_earlier_object(self, _name, text):
+ # An agent turn holds tool calls and error envelopes before its answer, and the first
+ # object used to win — the caller then failed schema validation on an error-shaped dict.
+ assert extract_json_from_text(text, label="test", required_keys={"answer"}) == EXPECTED
+
+ def test_required_keys_absent_everywhere_keep_the_first_object(self):
+ text = f'{{"type": "error", "message": "query failed"}}\n{JSON_STR}'
+ assert extract_json_from_text(text, label="test", required_keys={"repository"}) == {
+ "type": "error",
+ "message": "query failed",
+ }
diff --git a/products/tasks/backend/tests/test_multi_turn_session.py b/products/tasks/backend/tests/test_multi_turn_session.py
index 56b8c94b1c00..eae3cfcc9dc4 100644
--- a/products/tasks/backend/tests/test_multi_turn_session.py
+++ b/products/tasks/backend/tests/test_multi_turn_session.py
@@ -9,7 +9,7 @@ from django.db import OperationalError
from asgiref.sync import sync_to_async
from parameterized import parameterized
-from pydantic import BaseModel
+from pydantic import BaseModel, Field
from posthog.models import Integration, Organization, Team
from posthog.models.user import User
@@ -52,6 +52,10 @@ class _Resp(BaseModel):
value: str
+class _DefaultedResp(BaseModel):
+ values: list[str] = Field(default_factory=list)
+
+
class TestPollForTurnEmptyEndTurn:
@pytest.mark.asyncio
async def test_raises_empty_agent_turn_error_with_offsets(self):
@@ -1505,6 +1509,21 @@ class TestCreateTaskAndTriggerForwardsContext:
) == (model, runtime_adapter, reasoning_effort, initial_permission_mode)
+ [
+ ("required_field", '{"value": "ok"}', _Resp, _Resp(value="ok")),
+ # Every field has a default, so the envelope would validate as an empty answer.
+ ("all_fields_defaulted", '{"values": ["ok"]}', _DefaultedResp, _DefaultedResp(values=["ok"])),
+ ]
+)
+def test_parse_and_validate_reads_past_an_earlier_object(_name, answer, model, expected):
+ # A turn that ran a tool holds the tool's envelope before the answer. The first object used to
+ # win, so validation failed on the envelope instead of reading the answer at the end.
+ text = f'{{"type": "error", "message": "query failed"}}\nHere is the answer:\n{answer}'
+
+ assert MultiTurnSession._parse_and_validate(text, model, label="initial turn") == 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
diff --git a/products/tasks/backend/tests/test_repo_selection_prompt.py b/products/tasks/backend/tests/test_repo_selection_prompt.py
index 975883d2cbf1..d63d2073822c 100644
--- a/products/tasks/backend/tests/test_repo_selection_prompt.py
+++ b/products/tasks/backend/tests/test_repo_selection_prompt.py
@@ -2,6 +2,7 @@ import pytest
from unittest.mock import AsyncMock, MagicMock, patch
from asgiref.sync import async_to_sync
+from parameterized import parameterized
from posthog.models.repo_routing_rule import RepoRoutingRule
@@ -9,6 +10,7 @@ from products.tasks.backend.logic.repo_selection.agent import (
PINNED_REPOSITORY_REASON,
_build_repo_selection_prompt,
_routing_rules_block,
+ _salvage_repo_selection,
select_repository,
)
from products.tasks.backend.logic.repo_selection.types import RepoSelectionResult
@@ -123,6 +125,88 @@ def test_select_repository_renders_team_rules_and_visibility_into_prompt() -> No
assert "2. `acme/b` (visibility unknown)" in prompt
+ [
+ ("names_one_candidate", "I checked both trees. The subject is Acme/B.", ["acme/a", "acme/b"], "acme/b"),
+ (
+ "names_one_candidate_in_broken_json",
+ '{"repository": "acme/b", "reason":',
+ ["acme/a", "acme/b"],
+ "acme/b",
+ ),
+ (
+ "names_a_candidate_that_extends_another",
+ "The subject is acme/api-client.",
+ ["acme/api", "acme/api-client"],
+ "acme/api-client",
+ ),
+ ("names_a_candidate_at_sentence_end", "The subject is acme/api.", ["acme/api", "acme/api-client"], "acme/api"),
+ (
+ "states_a_candidate_and_rejects_another",
+ '{"repository": "Acme/A", "reason": "acme/b does not own this',
+ ["acme/a", "acme/b"],
+ "acme/a",
+ ),
+ ]
+)
+def test_salvage_reads_a_lone_named_candidate(_name, text, candidates, expected) -> None:
+ assert _salvage_repo_selection(text, candidates).repository == expected
+
+
+ [
+ ("names_two_candidates", "Both acme/a and acme/b match the request.", ["acme/a", "acme/b"]),
+ ("names_no_candidate", "None of the connected repositories own this.", ["acme/a", "acme/b"]),
+ ("names_a_non_candidate_that_extends_one", "The subject is acme/api-client.", ["acme/api", "acme/web"]),
+ (
+ "states_no_repository_and_cites_one",
+ '{"repository": null, "reason": "I checked acme/b and it does not own this',
+ ["acme/a", "acme/b"],
+ ),
+ (
+ "states_a_non_candidate_and_cites_one",
+ '{"repository": "acme/c", "reason": "acme/b is close, but',
+ ["acme/a", "acme/b"],
+ ),
+ ]
+)
+def test_salvage_raises_when_the_reply_is_ambiguous(_name, text, candidates) -> None:
+ # Answering "no repository" here would read as a decision the agent made, and guessing between
+ # two would open work against the wrong repository. Raising keeps the caller's own fallback.
+ with pytest.raises(ValueError):
+ _salvage_repo_selection(text, candidates)
+
+
+def test_select_repository_salvages_an_unreadable_end_turn() -> None:
+ # An end turn that does not validate used to fail the whole selection, and the Slack caller
+ # then dropped the user into a manual repository picker.
+ session = MagicMock()
+ session.end = AsyncMock()
+ github = MagicMock()
+ github.list_all_cached_repositories.return_value = [{"full_name": "acme/a"}, {"full_name": "acme/b"}]
+
+ async def start(**kwargs):
+ return session, kwargs["fallback_from_text"]("After checking the trees, acme/b owns this.")
+
+ with (
+ patch(f"{_AGENT}.GitHubRepositoryFullCache") as cache,
+ patch(f"{_AGENT}._list_eligible_full_names", return_value={"acme/a", "acme/b"}),
+ patch(f"{_AGENT}._routing_rules_block", return_value=None),
+ patch(f"{_AGENT}.MultiTurnSession.start", AsyncMock(side_effect=start)),
+ ):
+ cache.return_value.sync_full_cache = AsyncMock()
+ selected = async_to_sync(select_repository)(
+ 1,
+ 1,
+ "which repo?",
+ origin_product=Task.OriginProduct.SLACK,
+ github=github,
+ candidate_repos=["acme/a", "acme/b"],
+ )
+
+ assert selected.repository == "acme/b"
+
+
@pytest.mark.parametrize(
"pinned,expected_repository",
[("Acme/B", "acme/b"), (" acme/b ", "acme/b"), ("acme/gone", None)],