From e423ba3b72d7a9fe56c3cc11b186b609560fd4c6 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Sun, 8 Nov 2026 23:08:23 -0600 Subject: [PATCH] fix(claimant): fail closed on HTTP errors in supervision recovery (#7367) supervision_step session GET: read the HTTP status via curl -w - only a 404 is a genuinely gone session; 401/403/5xx, transport failure, or a 200 with no session object is unknown state and the binding is left alone. Previously an error body was parsed as session-gone regardless of status. Recovery DELETE: add curl -f so an HTTP error (e.g. 401, rc 22) no longer satisfies the returncode==0 gate for the recovery bind - a failed delete records the failure and never binds, closing the duplicate-execution shape #7367 forbids. Tests: stub harness now appends the -w status line and models delete rc; new tests pin that a 401 session GET leaves the binding alone and a 401 DELETE never binds. Oracle: an HTTP error is unknown state, never absence. test_claimant 12/12, test_poll 50/50 on the laptop. --- pm-stack/opencode-claimant/claimant.py | 70 ++++++++++++++------- pm-stack/opencode-claimant/test_claimant.py | 60 +++++++++++++++--- 2 files changed, 101 insertions(+), 29 deletions(-) diff --git a/pm-stack/opencode-claimant/claimant.py b/pm-stack/opencode-claimant/claimant.py index 7344c94064..9bf8608262 100755 --- a/pm-stack/opencode-claimant/claimant.py +++ b/pm-stack/opencode-claimant/claimant.py @@ -227,35 +227,56 @@ def supervision_step(mode: str) -> List[Dict]: session_id = prog.get("session_id") or task.get("session_id") if lane == "opencode" and session_id: - # Check if session exists and is progressing + # Check if session exists and is progressing. + # The HTTP status is the evidence (#7367 residual): + # curl -s prints an error body with exit 0 for a + # 401 just as for a 404, so an error body alone + # cannot tell "session gone" from "we could not + # look". Only a 404 is a genuinely gone session; + # any other failure is UNKNOWN state and the + # binding is left alone. try: session_response = subprocess.run( - ["curl", "-s", "-m", "5", *_auth_header_args(), + ["curl", "-s", "-m", "5", "-w", "\n%{http_code}", + *_auth_header_args(), f"{OPENCODE_URL}/api/session/{session_id}"], capture_output=True, text=True ) - if session_response.returncode == 0: - session = json.loads(session_response.stdout) + if session_response.returncode != 0: + # Transport failure - unknown state. + continue + body, _, status = session_response.stdout.rpartition("\n") + status = status.strip() + if not status.isdigit(): + # No status line: cannot verify - unknown. + continue + if status == "404": + # Genuinely gone from the server. + session = None + elif status != "200": + # 401/403/5xx: an error, not an absence - + # leave the binding alone. + continue + else: + session = json.loads(body) if isinstance(session, dict) and "data" in session: session = session["data"] if not isinstance(session, dict) or not session.get("id"): - # Error body, not a session object: - # the session is gone from the server. - session = None - else: - # Check for terminal state - has_terminal = any( - marker in str(session.get("outcome", "") or "") or - marker in str((session.get("time") or {}).get("idle", "") or "") - for marker in ["idle", "outcome", "completed", "failed"] - ) - - if not has_terminal: - # Session exists and is active - nothing to do - continue - # else: Session gone from server or error + # A 200 with no session object is not + # evidence of absence - unknown state. + continue + # Check for terminal state + has_terminal = any( + marker in str(session.get("outcome", "") or "") or + marker in str((session.get("time") or {}).get("idle", "") or "") + for marker in ["idle", "outcome", "completed", "failed"] + ) + + if not has_terminal: + # Session exists and is active - nothing to do + continue except Exception: # Could not verify session - leave bound continue @@ -294,9 +315,13 @@ def supervision_step(mode: str) -> List[Dict]: session_id = candidate["session_id"] try: - # Delete the zero-message session + # Delete the zero-message session. -f makes curl fail + # on HTTP errors (#7367 residual): without it a 401 exits + # 0 and the recovery bind below would proceed while the + # session still exists - the duplicate-execution shape + # #7367 forbids. The bind is gated on a verified delete. delete_result = subprocess.run( - ["curl", "-s", "-m", "5", "-X", "DELETE", *_auth_header_args(), + ["curl", "-s", "-f", "-m", "5", "-X", "DELETE", *_auth_header_args(), f"{OPENCODE_URL}/api/session/{session_id}"], capture_output=True, text=True @@ -323,7 +348,8 @@ def supervision_step(mode: str) -> List[Dict]: else: print(f"Failed to recover task {task_id}: {bind_result.stderr}") else: - print(f"Failed to delete session {session_id} for task {task_id}") + print(f"Failed to delete session {session_id} for task {task_id} " + f"(curl rc {delete_result.returncode}); recovery bind NOT attempted") except Exception as e: print(f"Error during recovery of task {task_id}: {e}") diff --git a/pm-stack/opencode-claimant/test_claimant.py b/pm-stack/opencode-claimant/test_claimant.py index 8fea69831d..7909915135 100644 --- a/pm-stack/opencode-claimant/test_claimant.py +++ b/pm-stack/opencode-claimant/test_claimant.py @@ -18,7 +18,11 @@ changes before launch, and main() writes those skips into the fires.jsonl entry; - supervision_step recovers a bound task whose session is gone from - the server (error body, zero messages) via delete + recovery bind. + the server (404, zero messages) via delete + recovery bind; +- supervision_step leaves a binding alone when the session GET is an + HTTP error (401: unknown state, not "gone"), and a recovery DELETE + that fails with an HTTP error (curl -f rc 22) never leads to a + recovery bind (#7367 residual). Negative control (#6865 acceptance): this suite fails against the pre-fix claimant.py (65beb42c1a, unimported requests/subprocess) and @@ -50,15 +54,20 @@ def __init__(self, returncode=0, stdout="", stderr=""): def make_fake_run(binds, *, session_get="gone", messages="[]", - prompt_rc=0, prompts=None): + prompt_rc=0, prompts=None, delete_rc=0, deletes=None): """Build a subprocess.run stub dispatching on argv shape. binds: list collecting every repo-queue bind argv. - session_get: "gone" -> the session GET returns an error body - (what curl -s prints for a 404); "active" -> a live session. + session_get: "gone" -> the session GET returns a 404 error body; + "active" -> a live session (200); "unauthorized" -> a 401 error + body (curl -s still exits 0 without -f). The claimant's GET + carries -w, so the stub appends the matching status line. prompt_rc: return code for the prompt POST (curl -f fails on HTTP errors, so 1 models a rejected prompt send). prompts: optional list collecting every prompt POST argv. + delete_rc: return code for the recovery DELETE; 22 models + curl -f failing on an HTTP error such as 401. + deletes: optional list collecting every DELETE argv. """ def fake_run(cmd, **kwargs): @@ -68,7 +77,9 @@ def fake_run(cmd, **kwargs): binds.append(cmd) return Result(0, "{}") if argv[0] == "curl" and "-X" in argv and "DELETE" in argv: - return Result(0, "") + if deletes is not None: + deletes.append(cmd) + return Result(delete_rc, "") if argv[0] == "curl" and joined.rstrip().endswith("/messages"): return Result(0, messages) if argv[0] == "curl" and joined.rstrip().endswith("/prompt"): @@ -82,11 +93,15 @@ def fake_run(cmd, **kwargs): })) if argv[0] == "curl" and "/api/session/" in joined: if session_get == "gone": - return Result(0, json.dumps({"error": "session not found"})) + return Result(0, json.dumps( + {"error": "session not found"}) + "\n404") + if session_get == "unauthorized": + return Result(0, json.dumps( + {"error": "unauthorized"}) + "\n401") return Result(0, json.dumps({ "id": "ses_gone", "time": {"created": 1, "updated": 2}, - })) + }) + "\n200") return Result(0, "") return fake_run @@ -243,6 +258,37 @@ def test_active_session_is_left_bound(self): self.assertEqual(recovered, []) self.assertEqual(binds, []) + def test_session_get_http_error_leaves_binding_alone(self): + # #7367 residual: a 401 error body is UNKNOWN state, not a + # gone session - no recovery candidate, no delete, no bind. + binds = [] + deletes = [] + with stub_claimed_rows([BOUND_ROW]), \ + patch.object(claimant.subprocess, "run", + make_fake_run(binds, session_get="unauthorized", + deletes=deletes)): + recovered = claimant.supervision_step("live") + self.assertEqual(recovered, []) + self.assertEqual(deletes, []) + self.assertEqual(binds, []) + + def test_delete_http_error_never_binds(self): + # #7367 residual acceptance: a simulated 401 on the recovery + # DELETE (curl -f exits 22) must not lead to a bind, even + # though the session really is gone with zero messages. + binds = [] + deletes = [] + with stub_claimed_rows([BOUND_ROW]), \ + patch.object(claimant.subprocess, "run", + make_fake_run(binds, delete_rc=22, + deletes=deletes)): + recovered = claimant.supervision_step("live") + self.assertEqual(len(recovered), 1) + self.assertEqual(len(deletes), 1) + delete_argv = [str(part) for part in deletes[0]] + self.assertIn("-f", delete_argv) + self.assertEqual(binds, []) + def test_shadow_mode_recovers_nothing(self): with patch.object(claimant.subprocess, "run", make_fake_run([])): self.assertEqual(claimant.supervision_step("shadow"), [])