Skip to content

fix(coordination): settle read and journal-bound request uncertainty automatically - #24

Merged
lukisch merged 1 commit into
mainfrom
fix/T-20261130-841353723-request-hold
Nov 30, 2026
Merged

lukisch merged 1 commit into
mainfrom
fix/T-20261130-841353723-request-hold

Conversation

@lukisch

@lukisch lukisch commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

Problem

On 2026-11-30 a pr.merge apply for ellmos-ai/bach#818 ended a GET /user unconfirmed (likely transient; the same call had succeeded twice shortly before). Two faults followed:

  1. exec_merge reported the transport failure as "identity is not the configured merge account", a wrong diagnosis.
  2. The request marker github-com-request.json (status inflight) 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 handoff transport-uncertainty-followup: "marker before every supported GH request ... no TTL/automatic retry/unblock"). It covers two different unknowns at once:

  • effect: did a write land?
  • rate/abuse state: was the unreadable reply a rate or secondary limit? The design already answers unreadable rate metadata with a conservative wait of at least 60 s (max(60, seconds) in Coordinator._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 markers (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.
  • Journal-bound write markers (action: <hashed journal key>): actions.apply binds 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.
  • Who settles: the sender, directly after the unconfirmed reply. Failing that, the next holder of the transport lock settles it, because by then the original holder has ended or died (the kernel releases OS locks). A dead process can therefore no longer leave a permanent HOLD either. Failed persistence keeps the marker, and every settlement is logged as a warning.
  • Target readback for the write (pr.merge):
    • "effect occurred": merged at the exact head, with a valid merge commit → journal applied.
    • "no effect": 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.
  • Latent bug fixed along the way: the existing merge reconciliation required merge_commit_sha from REST, which REST 2026-03-10 no longer returns, so it could never succeed in production. The GraphQL merge readback from exec_merge is now a shared helper (merged_commit_sha) used in both places.
  • Identity: a transport failure in pr.merge, pr.review, pr.close and git.push_branch now reports identity of the configured <role> account '<x>' unreadable (<transport error>), or configured 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

  • Red on origin/main: the 15 new or adjusted tests failed there. The two negative controls (test_legacy_or_unbound_write_marker_still_needs_operator, test_foreign_identity_is_still_reported_as_foreign) were already green there and stay green.
  • New:
    • 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 → journal unknown, no marker, cooldown. Nothing is sent during the cooldown, not even a readback. Afterwards:
      • merged (via GraphQL, without REST merge_commit_sha) → skipped_confirmed;
      • merged: false → journal cleared, PUT not repeated; only the next explicit apply writes;
      • readback unreadable → stays 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.
  • Adjusted to the new contract: after an unconfirmed read or a journal-bound write the marker is gone and a cooldown exists. A fresh process still sends 0 requests.
    • test_headerless_successful_get_settles_marker_and_rejects_result (renamed from ..._keeps_marker_...)
    • test_real_state_lock_failure_after_403_blocks_fresh_process
    • test_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
  • Mutation check: with the old REST-only merge readback, the [merged] case fails.
  • Local: targeted run of test_coordination.py, test_typed_actions.py, test_pr_review_action.py and test_pr_close_action.py: 242 passed. Ruff check and format are clean.
  • Full suite on the Mac Studio (mac_repo_pytest_send.sh --bundle, head eab2b8e): RESULT=rc0, no failures or errors, 5 skipped.

Not included

  • Runtime deploy or installation. The marker currently on the affected host predates this change, carries no read field and is therefore still an operator case.
  • "No effect" readback for pr.review and 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

…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
@lukisch

lukisch commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

Zweitprüfung (unabhängige Instanz): steht

Geprüft: Head eab2b8e3070a72671c49e174b773c89d27cc5f8b in eigenem Worktree, Diff vollständig gelesen (coordination.py, transport.py, actions.py, typed_actions.py, Doku, Tests), Vergleich gegen main 7816c9d.

Sicherheitszweck von t567

  • Kein frischer Prozess wiederholt einen unbestätigten Schreibzugriff. Ein unbestätigter Write wird nur dann in die 60-s-Abkühlung überführt, wenn sein Marker vor dem Effekt an einen dauerhaften Journal-Eintrag gebunden wurde. Der Journal-Eintrag (inflight/unknown) bleibt bestehen; dieselbe Aktion (inhaltsabgeleitete action_id) wird danach nur per Readback abgeglichen, eine andere Plan-/Autoritätsbindung läuft in Hold. Probe P2b belegt: nach Tod während des gebundenen Writes und nach Ablauf der Abkühlung kein erneuter POST, auch nicht in einem anderen Plan mit derselben Aktion.
  • Ein unbestätigter Schreib-Marker verschwindet nicht ohne Träger. Wörtlich verschwindet der gebundene Marker ohne Readback; das ist Absicht des PR: die Wirkungsunsicherheit wandert in das Aktionsjournal. _settleable_locked verlangt, dass das referenzierte Journal existiert und lesbar ist (sonst Hold). Ungebundene Write-Marker (direkter transport.request ohne apply, Tod zwischen Journal und Bindung, Marker älterer Versionen) bleiben operator HOLD ohne Ablauf (P1b, P2, P7).
  • pr.merge mit merged: false → ABSENT → Journal gelöscht: vertretbar, weil ein PR nur einmal gemergt werden kann, der PUT den Head per sha pinnt und jede neue Anwendung alle Preflight-Gates erneut durchläuft. Ein veralteter Lesestand kann höchstens einen 405 oder einen Fehlbericht erzeugen, keinen zweiten Effekt.

Adversariale Proben (Fake-Runner, kein Netz) – 17/17 grün am Head

# Probe Ergebnis
P1 Marker-Inhalt bei jedem gesendeten Kommando im Merge-Fluss GET und fixe GraphQL-Readback-Query: read: true; PUT: kein read, action = Journal-Key. api.request kann laut denial_reason/write_scope weder GET noch graphql noch ein --Endpoint sein, kein Write-Pfad setzt also read.
P1b Write außerhalb von apply, Timeout Marker bleibt, auch bei Uhr +60 s und +10⁷ s; nichts gesendet
P2 Prozesstod zwischen Journal-Eintrag und bind_request (os._exit) ungebundener Marker, Journal inflight, HOLD bei +0/+61/+10⁶ s, apply sendet nichts
P2b Prozesstod während des gebundenen Writes nächster Halter setzt die Abkühlung, nach 61 s kein Re-POST, Journal bleibt inflight, Lesezugriff wieder frei
P3 zwei Prozesse konkurrieren um das Auflösen (Read- und gebundener Marker) beide HOLD, 0 Requests, Marker genau einmal entfernt, Journal unverändert
P4 Readback merged: true an fremdem Head (REST oder GraphQL) bzw. merged fehlt unknown write HOLD, Journal unknown, genau 1 PUT
P5 kaputtes Marker-JSON, kaputtes Journal-JSON, read: false, read: "true", read+action, verwaister action-Key HOLD, nichts gesendet, Markerdatei bytegleich
P6 Uhr springt zurück (nach der Abkühlung und beim Auflösen) HOLD bis die Uhr observed wieder überholt
P7 Altmarker ohne read läuft nie ab; settle_request_as_policy_hold funktioniert unverändert

Die Invarianten P1b, P5 und P7 sind auch gegen main grün, sie bleiben also erhalten. Die übrigen hängen am neuen Verhalten und schlagen gegen main erwartungsgemäß fehl (9 rot).

Tests

  • Am Head lokal: tests/test_coordination.py und tests/test_typed_actions.py mit 158 passed.
  • Negativkontrolle: die PR-Tests gegen den main-Quelltext ergeben 15 rot, 143 grün. Rot sind genau die 15 neuen bzw. angepassten Tests. Die beiden Negativkontrollen (Altmarker, fremde Identität) bleiben dort grün.
  • CI: test (3.10) und test (3.12) grün, mergeStateStatus CLEAN.
  • Die vier angepassten Bestandstests entfernen keinen Schutz für Writes. Alle vier betreffen Reads oder gebundene Writes, und fresh_request_is_blocked gilt weiterhin, jetzt durch die Abkühlung.

Kleinere Punkte (kein Blocker, Folgepunkte)

  1. test_redirect_action_retains_unknown_journal_and_blocks_fresh_action blockiert die frische Aktion jetzt nur noch innerhalb der 60 s Abkühlung. Dass das Journal nach Ablauf der Abkühlung weiter blockiert, deckt der PR nur für pr.merge ab, für die übrigen Kinds nicht. Ein Test nach dem Muster von P2b wäre sinnvoll.
  2. Der Name test_timeout_and_restart_keep_request_marker_without_retry ist veraltet: Bei einem GET bleibt der Marker nicht mehr bestehen, der Test besteht wegen der Abkühlung.
  3. exec_push_branch ruft bei Fehlern nicht selbst settle_request auf, das übernimmt der nächste Halter. Das ist zulässig und dokumentiert, weicht aber von GhCliTransport ab.
  4. Scheitert bind_request (Persistenz nicht bestätigt), bleibt ein Marker stehen, obwohl nichts gesendet wurde. Für Nicht-Merge-Kinds folgt daraus ein dauerhafter HOLD pro Aktion. Das ist konservativ (Sicherheit vor Lebendigkeit) und betrifft nur einen seltenen Fall.
  5. Mischbetrieb: Ältere Core-Versionen lesen die neuen Felder read/action als „marker invalid“ und gehen fail-closed in HOLD. Ein bestehender Altmarker (ohne read) bleibt auch unter dieser Version operator HOLD und wird nicht automatisch aufgelöst.
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

@lukisch
lukisch merged commit 4e6dc32 into main Nov 30, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant