Repository navigation
fix(coordination): settle read and journal-bound request uncertainty automatically - #24
Merged
Merged
Conversation
…automatically An unconfirmed GET left a permanent host-wide request marker that blocked every Core action until an operator removed it (bach#818 on 2026-11-30: GET /user ended unconfirmed, nothing was sent). A read cannot have had an effect, and a write sent by actions.apply already keeps its effect uncertainty durably in the action journal. For both, only the rate/abuse state is unknown, so the marker now becomes a persisted 60 s cooldown (same minimum as unreadable rate metadata) and is removed only after the cooldown is read back. The sender settles directly after the unconfirmed reply; otherwise the next holder of the transport lock does, so a dead process cannot leave a permanent HOLD either. Unbound writes and markers written by older Core versions keep the operator HOLD unchanged (negative control). The unknown-write journal for pr.merge is now resolvable by target readback in both directions: merged at the exact head (merge commit via the fixed GraphQL readback, since REST 2026-03-10 omits merge_commit_sha, which made the previous reconciliation unreachable) or merged: false, which clears the journal without repeating the write. A transport failure while reading the identity in pr.merge, pr.review, pr.close and git.push_branch now reports "identity ... unreadable (...)" instead of claiming a foreign account. Ticket: T-20261130-841353723 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01THB2EzGbmyMB2S1P43LDZb
Contributor
Author
Zweitprüfung (unabhängige Instanz): stehtGeprüft: Head Sicherheitszweck von t567
Adversariale Proben (Fake-Runner, kein Netz) – 17/17 grün am Head
Die Invarianten P1b, P5 und P7 sind auch gegen Tests
Kleinere Punkte (kein Blocker, Folgepunkte)
Probe-Datei (pytest, PYTHONPATH=src;tests, PROBE_SRC=src)"""Adversarial review probes for githubbot-core PR #24 (fake transport only, no network)."""
import json
import os
import subprocess
import sys
from pathlib import Path
import pytest
from githubbot_core.actions import Action, apply
from githubbot_core.coordination import Coordinator
from githubbot_core.transport import GhCliTransport
from test_coordination import reply, merge_world
from test_typed_actions import REPO, SHA, OTHER, config, merge_action, pull
SRC = os.environ["PROBE_SRC"]
MARKER = "github-com-request.json"
CFG = {
"permissions": {"ceiling": ["issue.comment"], "enabled": ["issue.comment"], "write_owners": ["example-org"]},
"multi_bot": {"merge_account": "example-bot"},
}
COMMENT = Action("issue.comment", {"repo": "example-org/repo", "number": 1, "body": "synthetic"})
def comment_world(post="timeout"):
calls = []
def run(cmd, **kw):
marker_path = None
calls.append(cmd)
if "--method" in cmd and cmd[cmd.index("--method") + 1] != "GET":
if post == "timeout":
raise subprocess.TimeoutExpired("synthetic-gh", 1)
return reply(body='{"id": 1}')
return reply(body=json.dumps({"login": "example-bot"} if cmd[-1] == "user" else {"full_name": "example-org/repo"}))
return calls, run
def writes(calls):
return [c for c in calls if "--method" in c and c[c.index("--method") + 1] != "GET"]
# P1: who sets read? Record marker content at the moment each command is sent.
def test_p1_read_flag_only_on_reads_and_writes_are_bound(tmp_path):
c = Coordinator(tmp_path / "p1", clock=lambda: 1000)
seen = []
state = {"put": "ok", "pull": {**pull(), "number": 7}}
_, inner = merge_world(state)
def run(cmd, **kw):
seen.append((cmd, json.loads((c.root / MARKER).read_text())))
return inner(cmd, **kw)
t = GhCliTransport(runner=run, coordinator=c)
assert apply([merge_action()], t, config())["receipts"][0]["status"] == "applied"
for cmd, marker in seen:
method = cmd[cmd.index("--method") + 1] if "--method" in cmd else "GET"
if method == "GET" or "graphql" in cmd:
assert marker.get("read") is True and "action" not in marker, (cmd, marker)
else:
assert "read" not in marker and marker.get("action") == c.action_key(merge_action().action_id), (cmd, marker)
assert any("PUT" in cmd for cmd, _ in seen)
# P1b: a write outside apply (no journal) stays operator HOLD forever.
def test_p1b_unjournaled_write_timeout_never_auto_settles(tmp_path):
now = [1000]
c = Coordinator(tmp_path / "p1b", clock=lambda: now[0])
calls, run = comment_world()
t = GhCliTransport(runner=run, coordinator=c)
assert "outcome unconfirmed" in t.request("POST", "repos/example-org/repo/issues/1/comments", {"body": "x"})[1]
marker = c.load("github-com-request")
assert set(marker) == {"schema", "id", "status"}
for now[0] in (1061, 10**7):
assert t.get("user")[1] == "GitHub coordination HOLD; no request sent"
assert len(calls) == 1 and c.load("github-com-request") == marker
CRASH = r"""
import os,sys,json
from pathlib import Path
from githubbot_core import actions
from githubbot_core.coordination import Coordinator
from githubbot_core.transport import GhCliTransport
from types import SimpleNamespace
root, mode = Path(sys.argv[1]), sys.argv[2]
if mode == 'after-journal':
Coordinator.bind_request = lambda self, *a: os._exit(25)
def run(cmd, **kw):
if '--method' in cmd:
os._exit(26) # dies while the bound write is in flight
body = {'login':'example-bot'} if cmd[-1]=='user' else {'full_name':'example-org/repo'}
return SimpleNamespace(returncode=0, stdout='HTTP/2.0 200 OK\r\n\r\n'+json.dumps(body), stderr='')
cfg={'permissions':{'ceiling':['issue.comment'],'enabled':['issue.comment'],'write_owners':['example-org']},'multi_bot':{'merge_account':'example-bot'}}
actions.apply([actions.Action('issue.comment',{'repo':'example-org/repo','number':1,'body':'synthetic'})],GhCliTransport(runner=run,coordinator=Coordinator(root)),cfg)
"""
def crash(root, mode, code):
p = subprocess.run([sys.executable, "-B", "-X", "utf8", "-c", CRASH, str(root), mode], capture_output=True,
text=True, env={**os.environ, "PYTHONPATH": SRC}, timeout=60)
assert p.returncode == code, p.stderr
# P2: death between journal write and marker binding -> unbound write marker -> permanent HOLD.
def test_p2_death_between_journal_and_bind_stays_operator_hold(tmp_path):
root = tmp_path / "p2"
crash(root, "after-journal", 25)
c0 = Coordinator(root)
assert c0.load(c0.action_key(COMMENT.action_id))["status"] == "inflight"
marker = c0.load("github-com-request")
assert set(marker) == {"schema", "id", "status"}
for offset in (0, 61, 10**6):
c = Coordinator(root, clock=lambda o=offset: 2 * 10**9 + o)
calls, run = comment_world(post="ok")
t = GhCliTransport(runner=run, coordinator=c)
assert t.get("user")[1] == "GitHub coordination HOLD; no request sent"
apply([COMMENT], t, CFG)
assert calls == []
assert Coordinator(root).load("github-com-request") == marker
# P2b: death while the bound write is in flight -> next holder settles; after cooldown the same
# action is reconciled only (comment has no readback -> stays HOLD), never re-POSTed.
def test_p2b_death_during_bound_write_settles_but_never_repeats(tmp_path):
root = tmp_path / "p2b"
crash(root, "in-flight", 26)
c0 = Coordinator(root)
key = c0.action_key(COMMENT.action_id)
assert c0.load("github-com-request")["action"] == key
now = [2 * 10**9]
c = Coordinator(root, clock=lambda: now[0])
calls, run = comment_world(post="ok")
t = GhCliTransport(runner=run, coordinator=c)
r = apply([COMMENT], t, CFG)["receipts"][0]
assert r["status"] in {"denied", "failed"} and calls == []
assert not (root / MARKER).exists() and c.load("github-com-rate")["not_before"] == now[0] + 60
now[0] += 61
r = apply([COMMENT], t, CFG)["receipts"][0]
assert r["status"] == "failed" and "unknown write HOLD" in r["detail"]
assert writes(calls) == [] and c.load(key)["status"] == "inflight"
# another plan containing the same action is refused as well
other = Action("issue.comment", {"repo": "example-org/repo", "number": 2, "body": "synthetic"})
rs = apply([COMMENT, other], t, CFG)["receipts"]
assert rs[0]["status"] == "failed"
assert not [w for w in writes(calls) if "repos/example-org/repo/issues/1/comments" in w]
assert c.load(key)["status"] == "inflight"
# a fresh read is allowed again (bounded resolver)
assert t.get("user")[1] is None
RACE = r"""
import sys,json,time
from pathlib import Path
from types import SimpleNamespace
from githubbot_core.coordination import Coordinator
from githubbot_core.transport import GhCliTransport
root=Path(sys.argv[1])
while not (root/'go').exists(): time.sleep(.005)
calls=[]
def run(*a,**kw):
calls.append(1); return SimpleNamespace(returncode=0, stdout='HTTP/2.0 200 OK\r\n\r\n{}', stderr='')
res=GhCliTransport(runner=run,coordinator=Coordinator(root,timeout=10)).get('user')
print(json.dumps({'calls':len(calls),'error':res[1]}))
"""
# P3: two fresh processes race to settle a dead reader's marker.
@pytest.mark.parametrize("bound", [False, True])
def test_p3_two_processes_race_for_settlement(tmp_path, bound):
root = tmp_path / ("p3b" if bound else "p3r")
c = Coordinator(root)
c.prepare()
marker = {"schema": "githubbot-core.request/v1", "id": "c" * 32, "status": "inflight"}
if bound:
key = c.action_key("x")
c.save(key, {"schema": "githubbot-core.intent/v1", "id": "x", "plan": "0" * 64, "status": "unknown"})
marker["action"] = key
else:
marker["read"] = True
c.save("github-com-request", marker)
kids = [subprocess.Popen([sys.executable, "-B", "-X", "utf8", "-c", RACE, str(root)], stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=True, env={**os.environ, "PYTHONPATH": SRC}) for _ in range(2)]
(root / "go").write_text("go")
out = []
for k in kids:
o, e = k.communicate(timeout=60)
assert k.returncode == 0, e
out.append(json.loads(o))
assert all(x["calls"] == 0 and x["error"] for x in out), out
assert not (root / MARKER).exists()
if bound:
assert c.load(key)["status"] == "unknown" # effect uncertainty untouched
# P4: merged:true at a foreign head (REST or GraphQL) never confirms, never clears.
@pytest.mark.parametrize("where", ["rest", "graphql", "merged-missing"])
def test_p4_foreign_head_or_missing_merged_keeps_unknown(tmp_path, where):
now = [1000]
c = Coordinator(tmp_path / where, clock=lambda: now[0])
state = {"put": "timeout", "pull": {**pull(), "number": 7}}
calls, run = merge_world(state)
t = GhCliTransport(runner=run, coordinator=c)
a = merge_action()
key = c.action_key(a.action_id)
assert apply([a], t, config())["receipts"][0]["status"] == "failed"
now[0] = 1061
if where == "rest":
state["pull"] = {**state["pull"], "merged": True, "state": "closed", "head": {"sha": OTHER}}
elif where == "graphql":
state["pull"] = {**state["pull"], "merged": True, "state": "closed"}
def gql(cmd, _run=run, **kw):
if "graphql" in cmd:
calls.append(cmd)
node = {"state": "MERGED", "headRefOid": OTHER, "mergeCommit": {"oid": OTHER}}
return reply(body=json.dumps({"data": {"node": node}}))
return _run(cmd, **kw)
t = GhCliTransport(runner=gql, coordinator=c)
else:
p = dict(state["pull"])
p.pop("merged")
state["pull"] = p
r = apply([a], t, config())["receipts"][0]
assert r["status"] == "failed" and "unknown write HOLD" in r["detail"]
assert c.load(key)["status"] == "unknown"
assert len([x for x in calls if "PUT" in x]) == 1
# P5: broken marker JSON / broken journal JSON / invalid read value / both flags -> operator HOLD.
@pytest.mark.parametrize("variant", ["broken-marker", "broken-journal", "read-false", "read-string", "both", "dangling"])
def test_p5_corrupt_state_fails_closed(tmp_path, variant):
c = Coordinator(tmp_path / variant, clock=lambda: 10**9)
c.prepare()
base = {"schema": "githubbot-core.request/v1", "id": "d" * 32, "status": "inflight"}
key = c.action_key("y")
if variant == "broken-marker":
(c.root / MARKER).write_text("{", encoding="utf-8")
else:
extra = {"read-false": {"read": False}, "read-string": {"read": "true"},
"both": {"read": True, "action": key}, "broken-journal": {"action": key},
"dangling": {"action": key}}[variant]
c.save("github-com-request", {**base, **extra})
if variant == "broken-journal":
(c.root / (key + ".json")).write_text("{", encoding="utf-8")
before = (c.root / MARKER).read_text()
calls = []
t = GhCliTransport(runner=lambda *a, **kw: calls.append(1) or reply(), coordinator=c)
assert t.get("user")[1] == "GitHub coordination HOLD; no request sent" and not calls
assert (c.root / MARKER).read_text() == before
# P6: clock moves backwards around settlement.
def test_p6_clock_backwards_fails_closed(tmp_path):
now = [1000]
c = Coordinator(tmp_path / "p6", clock=lambda: now[0])
calls = []
def run(*a, **kw):
calls.append(1)
if len(calls) == 1:
raise subprocess.TimeoutExpired("synthetic-gh", 1)
return reply()
t = GhCliTransport(runner=run, coordinator=c)
t.get("user")
assert c.load("github-com-rate")["not_before"] == 1060
now[0] = 500
assert t.get("user")[1] and len(calls) == 1
# stale settleable marker met while the clock is behind 'observed'
c.save("github-com-request", {"schema": "githubbot-core.request/v1", "id": "e" * 32, "status": "inflight", "read": True})
assert t.get("user")[1] and len(calls) == 1
now[0] = 1061
assert t.get("user")[1] is None and len(calls) == 2
# P7: legacy marker (no read) never expires, and explicit offline recovery still works.
def test_p7_legacy_marker_never_expires_and_recovery_still_works(tmp_path):
now = [1000]
c = Coordinator(tmp_path / "p7", clock=lambda: now[0])
c.prepare()
c.save("github-com-request", {"schema": "githubbot-core.request/v1", "id": "f" * 32, "status": "inflight"})
calls = []
t = GhCliTransport(runner=lambda *a, **kw: calls.append(1) or reply(), coordinator=c)
for now[0] in (1000, 10**8):
assert t.get("user")[1] and not calls
c.settle_request_as_policy_hold("f" * 32)
assert c.load("github-com-rate")["policy_hold"] is True and not (c.root / MARKER).exists()
assert t.get("user")[1] and not calls🤖 Generated with Claude Code |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
On 2026-11-30 a
pr.mergeapply for ellmos-ai/bach#818 ended aGET /userunconfirmed (likely transient; the same call had succeeded twice shortly before). Two faults followed:exec_mergereported the transport failure as "identity is not the configured merge account", a wrong diagnosis.github-com-request.json(statusinflight) stayed behind. Since then every Core action on that host answers "request uncertainty HOLD; operator inspection required", although nothing was written (no write intent, PR still OPEN). Only an operator can clear it.Intent of the HOLD (design t567 / T-20261112-567319331)
The marker before every request, GET included, is deliberate (
docs/TRANSPORT_COORDINATION.md, "Durable request uncertainty"; commits d737d35/31e1b7f; t567 handofftransport-uncertainty-followup: "marker before every supported GH request ... no TTL/automatic retry/unblock"). It covers two different unknowns at once:max(60, seconds)inCoordinator._rate_hold_locked; docs "Cooldowns and policy HOLD").The only resolver was
settle_request_as_policy_hold, which converts the marker into a permanent policy HOLD. That is a lock with no automatic release.Change
I keep the HOLD as it was designed and split the two unknowns. Each one gets a resolver with evidence.
read: true): a GET cannot have had an effect. The marker becomes a persisted 60 s cooldown and is removed only after that cooldown has been written and read back.action: <hashed journal key>):actions.applybinds the marker after the journal entry is durable and before the effect. The effect uncertainty stays in the unknown-write journal, which blocks repeating that action. The host-wide marker becomes the same 60 s cooldown.pr.merge):applied.merged: false→ journal cleared, nothing repeated. A pull request can be merged only once, and the read runs only after the cooldown. A new explicit apply re-runs every preflight gate.merge_commit_shafrom REST, which REST 2026-03-10 no longer returns, so it could never succeed in production. The GraphQL merge readback fromexec_mergeis now a shared helper (merged_commit_sha) used in both places.pr.merge,pr.review,pr.closeandgit.push_branchnow reportsidentity of the configured <role> account '<x>' unreadable (<transport error>), orconfigured bot identity unreadable (...)for the push. A foreign account still reports "identity is not the configured ... account".Unchanged: unbound writes (raw transport writes outside
actions.apply) and every marker written by an older Core keep the operator HOLD. Rate/policy HOLDs are untouched. Nothing is retried and there is no account fallback.Known limit (also in the docs): if an unconfirmed reply was a 403 whose policy HOLD could not be persisted, the next request after the cooldown receives that 403 again and persists the HOLD then.
Tests
test_legacy_or_unbound_write_marker_still_needs_operator,test_foreign_identity_is_still_reported_as_foreign) were already green there and stay green.test_unconfirmed_read_settles_into_cooldown_instead_of_operator_hold: GET timeout → no marker,not_before= now+60, nothing sent at +59, request sent at +60.test_unknown_merge_write_is_resolved_only_by_target_readback[merged|absent|unreadable]: PUT timeout → journalunknown, no marker, cooldown. Nothing is sent during the cooldown, not even a readback. Afterwards:merge_commit_sha) →skipped_confirmed;merged: false→ journal cleared, PUT not repeated; only the next explicit apply writes;unknown write HOLD(negative control).test_legacy_or_unbound_write_marker_still_needs_operator: negative control. A legacy marker and an unbound write marker stay HOLD, even with the clock far in the future.test_identity_transport_failure_is_not_reported_as_foreign_identity[exec_merge|exec_review],test_push_identity_transport_failure_is_not_a_credential_mismatch,test_foreign_identity_is_still_reported_as_foreign.test_headerless_successful_get_settles_marker_and_rejects_result(renamed from..._keeps_marker_...)test_real_state_lock_failure_after_403_blocks_fresh_processtest_transport_process_death_leaves_uncertainty_for_next_process: now also checks that a later process sends again after the cooldown.test_redirect_action_retains_unknown_journal_and_blocks_fresh_action[merged]case fails.test_coordination.py,test_typed_actions.py,test_pr_review_action.pyandtest_pr_close_action.py: 242 passed. Ruff check and format are clean.mac_repo_pytest_send.sh --bundle, head eab2b8e):RESULT=rc0, no failures or errors, 5 skipped.Not included
readfield and is therefore still an operator case.pr.reviewand the other kinds; they keep the existing behaviour. Add it when needed.Ticket: T-20261130-841353723
🤖 Generated with Claude Code
https://claude.ai/code/session_01THB2EzGbmyMB2S1P43LDZb