: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): recover explicit repository decisions after retry (#128140)
Georgiy Tarasov64a782306edc
diff --git a/products/tasks/backend/logic/repo_selection/agent.py b/products/tasks/backend/logic/repo_selection/agent.pyindex f93fea52736d..9fcacb2d31ce 100644--- a/products/tasks/backend/logic/repo_selection/agent.py+++ b/products/tasks/backend/logic/repo_selection/agent.py@@ -87,6 +87,14 @@ class RepoSelectionUsageLimitError(Exception):super().__init__(message)+# Sent once when the agent ends its first turn with prose, often a progress note about a cache+# query it started, instead of the selection JSON.+REPO_SELECTION_JSON_RETRY_PROMPT = (+ "Your last reply did not contain the JSON object the task asks for. "+ "If a cache query or another step is still running, wait for it and finish your checks first. "+ "Then reply with only that JSON object, matching the schema above. Do not add prose or code fences."+)+# The agent prints a refused model call as `API Error: <status> <body>`. The gateway answers a# team with no credits left with a 402._USAGE_LIMIT_REPLY = re.compile(r"\s*API Error: 402\b")@@ -592,38 +600,17 @@ 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()+ """Recover an explicit leading JSON selection, never a repository mentioned in prose."""+ if len(re.findall(r'"repository"\s*:', text)) != 1:+ raise ValueError("End-turn text contains missing or competing repository decisions")+ stated = re.match(r'\s*(?:```(?:json)?\s*)?\{\s*"repository"\s*:\s*"([^"\\]*)"', text)+ choice = stated.group(1).strip().lower() if stated else None+ if choice not in candidate_repos:+ raise ValueError("End-turn text does not explicitly select a candidate repository")return RepoSelectionResult(- repository=repository,- reason=f"The agent's answer was not readable, but its reply named only {repository}.",+ repository=choice,+ reason="The agent explicitly selected this repository, but its full JSON answer was not readable.",)@@ -793,9 +780,8 @@ async def select_repository(spend_signal_id=spend_signal_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=_salvage,+ json_retry_prompt=REPO_SELECTION_JSON_RETRY_PROMPT,)except Exception as e:if usage_limit_reply is not 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 d7d974584de8..0288718c5fd3 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@@ -172,9 +172,9 @@ class MultiTurnSession:e,)salvageable = False- retry_message = await session.send_followup_raw(json_retry_prompt, label="initial turn json retry")+ last_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")+ parsed = cls._parse_and_validate(last_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 callerdiff --git a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.pyindex ca4d8bcc438f..0884c4dacf2a 100644--- a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py@@ -774,6 +774,11 @@ def _refresh_sandbox_github(if actor_user is None:return None+ # Read-only runs use a team installation grant, not the message actor's identity.+ # The periodic credential refresh rotates that grant without widening its permissions.+ if (state or {}).get("github_read_access") is True:+ return None+run_id = str(task_run.id)task = task_run.task# A run that started before its actor connected GitHub is bot-authored, and the agent maydiff --git a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.pyindex cfc7cf5e2ae9..c2c66370a683 100644--- a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py+++ b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py@@ -527,18 +527,26 @@ class TestSandboxGithubIdentityGate:mock_apply.assert_called_once()assert mock_apply.call_args.args[2] == "ghu_reconnected"- def test_bot_authorship_skips(- self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear, mock_upgrade+ @pytest.mark.parametrize(+ "authorship,state",+ [+ (PrAuthorshipMode.BOT, None),+ (PrAuthorshipMode.USER, {"github_read_access": True}),+ (PrAuthorshipMode.BOT, {"github_read_access": True}),+ ],+ )+ def test_shared_installation_credentials_skip_actor_rebinding(+ self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear, mock_upgrade, authorship, state):- # BOT runs share a single installation token, so every actor is already- # the same GitHub identity — nothing to rebind.- mock_authorship.return_value = PrAuthorshipMode.BOT+ mock_authorship.return_value = authorshipmark_sandbox_github_identity(_GATE_SANDBOX_ID, 99)- assert _refresh_sandbox_github(_make_task_run_mock(), MagicMock(id=42), None) is None+ assert _refresh_sandbox_github(_make_task_run_mock(), MagicMock(id=42), state) is Nonemock_get_token.assert_not_called()mock_apply.assert_not_called()mock_clear.assert_not_called()+ if state:+ mock_upgrade.assert_not_called()def test_transition_with_access_rebinds(self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear, mock_upgradediff --git a/products/tasks/backend/tests/test_multi_turn_session.py b/products/tasks/backend/tests/test_multi_turn_session.pyindex f65c4e81c971..69f0b71bce05 100644--- a/products/tasks/backend/tests/test_multi_turn_session.py+++ b/products/tasks/backend/tests/test_multi_turn_session.py@@ -2108,11 +2108,13 @@ class TestMultiTurnSessionStartFallback:return session@pytest.mark.asyncio- async def test_salvages_unparseable_text_with_fallback(self):+ @pytest.mark.parametrize("retry_reply", [None, "Updated conclusion from the second turn."])+ async def test_salvages_unparseable_text_with_fallback(self, retry_reply: str | None):# _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."+ session.send_followup_raw = AsyncMock(return_value=retry_reply) # type: ignore[method-assign]with patch.object(MultiTurnSession, "start_raw", new=AsyncMock(return_value=(session, prose))):returned_session, parsed = await MultiTurnSession.start(@@ -2120,10 +2122,11 @@ class TestMultiTurnSessionStartFallback:context=MagicMock(),model=_Resp,fallback_from_text=lambda text: _Resp(value=text),+ json_retry_prompt="Return JSON" if retry_reply is not None else None,)assert returned_session is session- assert parsed == _Resp(value=prose)+ assert parsed == _Resp(value=retry_reply if retry_reply is not None else 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]diff --git a/products/tasks/backend/tests/test_repo_selection_prompt.py b/products/tasks/backend/tests/test_repo_selection_prompt.pyindex 43d0941f814c..f3f9b6392cd5 100644--- a/products/tasks/backend/tests/test_repo_selection_prompt.py+++ b/products/tasks/backend/tests/test_repo_selection_prompt.py@@ -131,7 +131,7 @@ def test_select_repository_renders_team_rules_and_visibility_into_prompt() -> No@parameterized.expand([- ("names_one_candidate", "I checked both trees. The subject is Acme/B.", ["acme/a", "acme/b"], "acme/b"),+ ("fenced_selection", '```json\n{"repository": "acme/b", "reason":', ["acme/a", "acme/b"], "acme/b"),("names_one_candidate_in_broken_json",'{"repository": "acme/b", "reason":',@@ -140,11 +140,11 @@ def test_select_repository_renders_team_rules_and_visibility_into_prompt() -> No),("names_a_candidate_that_extends_another",- "The subject is acme/api-client.",+ '{"repository": "acme/api-client", "reason":',["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"),+ ("explicit_selection", '{"repository": "acme/api", "reason":', ["acme/api", "acme/api-client"], "acme/api"),("states_a_candidate_and_rejects_another",'{"repository": "Acme/A", "reason": "acme/b does not own this',@@ -153,12 +153,15 @@ def test_select_repository_renders_team_rules_and_visibility_into_prompt() -> No),])-def test_salvage_reads_a_lone_named_candidate(_name, text, candidates, expected) -> None:+def test_salvage_reads_an_explicit_candidate(_name, text, candidates, expected) -> None:assert _salvage_repo_selection(text, candidates).repository == expected@parameterized.expand([+ ("progress_mentions_candidate", "Waiting for the acme/a cache query.", ["acme/a", "acme/b"]),+ ("rejects_only_candidate", "acme/a is unrelated to this request.", ["acme/a", "acme/b"]),+ ("quotes_example", 'For example: {"repository": "acme/a"}', ["acme/a", "acme/b"]),("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"]),@@ -190,7 +193,7 @@ def test_select_repository_salvages_an_unreadable_end_turn() -> None: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.")+ return session, kwargs["fallback_from_text"]('{"repository": "acme/b", "reason":')with (patch(f"{_AGENT}.GitHubRepositoryFullCache") as cache,@@ -212,6 +215,65 @@ def test_select_repository_salvages_an_unreadable_end_turn() -> None:assert selected.repository == "acme/b"+ [+ ("retry_answers", '{"repository": "acme/b", "reason": "Owns the checkout path."}', "acme/b", None),+ ("retry_still_progress", "Still waiting on the query.", None, ValueError),+ (+ "retry_corrects_to_null",+ '{"repository": "acme/a", "reason": "First choice"}\n{"repository": null, "reason":',+ None,+ ValueError,+ ),+ (+ "retry_corrects_to_another_candidate",+ '{"repository": "acme/a", "reason": "First choice"}\n{"repository": "acme/b", "reason":',+ None,+ ValueError,+ ),+ ("retry_rejects_mentioned_candidate", "acme/a does not own this.", None, ValueError),+ ("retry_usage_limit", "API Error: 402 No credits remaining.", None, RepoSelectionUsageLimitError),+ ("retry_answers_off_list", '{"repository": "acme/zzz", "reason": "Guess."}', None, RepoSelectionRejectedError),+ ]+)+def test_select_repository_asks_again_after_a_progress_note(+ _name: str, retry_reply: str, expected: str | None, error: type[Exception] | None+) -> None:+ session = MagicMock()+ session.end = AsyncMock()+ session.send_followup_raw = AsyncMock(return_value=retry_reply)+ github = MagicMock()+ github.list_all_cached_repositories.return_value = [{"full_name": "acme/a"}, {"full_name": "acme/b"}]+ progress_note = "I've started a query on the repository cache and will report back."++ 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_raw", AsyncMock(return_value=(session, progress_note))),+ ):+ cache.return_value.sync_full_cache = AsyncMock()++ def run() -> RepoSelectionResult:+ return async_to_sync(select_repository)(+ 1,+ 1,+ "which repo?",+ origin_product=Task.OriginProduct.SLACK,+ priority=Priority.NORMAL,+ github=github,+ candidate_repos=["acme/a", "acme/b"],+ )++ if error is None:+ assert run().repository == expected+ else:+ with pytest.raises(error):+ run()++ session.send_followup_raw.assert_awaited_once()++def test_select_repository_reports_a_usage_limit_refusal() -> None:github = MagicMock()github.list_all_cached_repositories.return_value = [{"full_name": "acme/a"}, {"full_name": "acme/b"}]