diff --git a/CHANGELOG.md b/CHANGELOG.md index 7372fb0..f505756 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ Format: [Keep a Changelog](https://keepachangelog.com/de/1.1.0/), [Semantic Vers ### Behoben / Fixed +- Transport-Koordination: Ein unbestätigter Lesezugriff (GET) hinterlässt keinen dauerhaften host-weiten Unsicherheitsmarker mehr, sondern eine 60-Sekunden-Abkühlung; ebenso ein an das Aktionsjournal gebundener Schreibzugriff, dessen Wirkungsunsicherheit im Journal bleibt, bis der Ziel-Readback sie auflöst (Merge: eingetreten oder ausgeblieben). Ungebundene Schreibzugriffe und Marker älterer Versionen bleiben im HOLD. Ein Transportfehler beim Identitätsabruf (`pr.merge`, `pr.review`, `pr.close`, `git.push_branch`) wird nicht mehr als falsche Identität gemeldet. Der Merge-Readback nutzt bei fehlendem `merge_commit_sha` (REST 2026-03-10) die GraphQL-Leseabfrage / an unconfirmed GET now settles into a 60 s cooldown instead of a permanent host-wide uncertainty HOLD, as does a journal-bound write whose effect uncertainty stays in the action journal until the target readback resolves it; identity transport failures get their own error text (T-20261130-841353723). + - `actions.rerun`: Sicherheitsabstand von einer Stunde vor der 30-Tage-Grenze (`_RERUN_WINDOW`), damit Uhrabweichung oder ein genau 30 Tage alter Lauf den POST nicht doch absetzen und einen 403 mit host-weitem policy HOLD ausloesen / one-hour safety margin before the 30-day re-run limit (Folgepunkt zu #21, T-20261127-325831929). - `actions.rerun`: Ein Lauf außerhalb des 30-Tage-Rerun-Fensters von GitHub wird lokal abgelehnt, ohne den POST zu senden. Der sonst folgende HTTP 403 setzte einen persistenten host-weiten `policy_hold` und blockierte alle koordinierten Schreibaktionen / a run older than 30 days is refused locally without sending the POST; its 403 used to set a persistent host-wide policy HOLD. Jeder andere 403 bleibt unverändert fail-closed (Ticket T-20261127-325831929). diff --git a/docs/TRANSPORT_COORDINATION.md b/docs/TRANSPORT_COORDINATION.md index 3c310a4..12c906d 100644 --- a/docs/TRANSPORT_COORDINATION.md +++ b/docs/TRANSPORT_COORDINATION.md @@ -52,7 +52,10 @@ Before **every supported request**, including GET and typed Git push/readback, Core persists and reads back one shared request-inflight marker while holding transport -> rate-state locks. If the marker cannot be durably written, nothing is sent. The marker contains a random request ID and fixed schema/status only, -never a token, URL or body. It has no automatic expiry. +never a token, URL or body. It has no automatic expiry. A read marker also +carries `read: true`. A write sent by `actions.apply` binds its marker to the +hashed action-journal key (`action`) after the journal is durable and before the +effect; a write marker without that binding is called unbound below. Only successful transport replies, explicitly recognized definitive client rejections, or successfully persisted rate/policy HOLD permit marker removal. @@ -62,14 +65,32 @@ The explicit definitive client rejection set is 400/401/404/405/409/410/412/ 413/414/415/422; 403/429 use the separately persisted HOLD paths. A definitive transport rejection does not itself clear the action-level unknown journal or authorize repeating a write. A timeout, process death, malformed transport -response, failed HOLD persistence or failed marker cleanup leaves uncertainty -HOLD across process restarts. A fresh process must not send even a GET merely -because the original OS lock has become available. Ordinary action preflight and -Git use the same marker check. This takes precedence over automatic action +response, failed HOLD persistence or failed marker cleanup leaves the +marker in place. For an unbound write marker, including every marker written by +an older Core, this stays uncertainty HOLD across process restarts: a fresh +process must not send even a GET merely because the original OS lock has become +available. Ordinary action preflight and Git use the same marker check. This takes precedence over automatic action readback; application-level readback remains possible only when transport state is confirmed. Parsed application/body errors still use the action journal. -Recovery is explicit and offline: after operator inspection, trusted embedding +### Automatic settlement (T-20261130-841353723) + +A read cannot have had an effect. A journal-bound write's effect uncertainty is +already held, durably and per action, by its unknown-write journal (next +section), which blocks repeating that action. For both, the only remaining +unknown is the shared GitHub.com rate/abuse state. Such a marker is therefore +settled into a persisted cooldown of 60 seconds, the same conservative minimum +used for unreadable rate metadata, and removed only after the cooldown was +written and read back. Settlement happens under transport -> rate-state locks, +either directly after the unconfirmed reply by the sending process, or by the +next holder of the transport lock (the original holder has ended or died; OS +locks are released by the kernel). Failed persistence keeps the marker. Each +settlement is logged as a warning. Existing rate/policy HOLDs are untouched and +no request is retried. Known limit: if the 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 policy HOLD then. + +Recovery of an unbound write marker remains explicit and offline: after operator inspection, trusted embedding may call `Coordinator.settle_request_as_policy_hold(exact_request_id)`. Under transport -> rate-state locks this persists and verifies policy HOLD before consuming that exact marker. It performs no network request and does **not** @@ -96,8 +117,12 @@ source of truth for unknown effects. A subsequent call with the exact authority-bound plan can only reconcile by reads. Reviews require one exact account/head/event/body match plus the unchanged open PR head. Merges require the exact original head, merged state and a valid -merge commit SHA. This confirms desired state, not attribution of the effect to -this process. All other effects (comments, labels, dispatch, ready, close, PR +merge commit SHA (from REST or, since REST 2026-03-10 omits it, from the fixed +GraphQL merge readback). This confirms desired state, not attribution of the +effect to this process. A merge readback showing `merged: false` confirms the +effect absent, because a pull request can be merged only once and the read runs +only after the settlement cooldown: the journal entry is cleared and nothing is +repeated in that call. A new explicit apply re-runs every preflight gate. All other effects (comments, labels, dispatch, ready, close, PR creation, raw API and Git pushes) remain HOLD when unknown. No generic reset or blind retry is offered: unsupported recovery needs a separately reviewed, action-specific readback. A changed plan/scope/actor cannot reuse an unknown @@ -125,7 +150,11 @@ einem Host mit gemeinsamem lokalem Zustand. Sie bietet keine Mehrhostgarantie. Dateisperren werden niemals zur Wiederherstellung gelöscht. Bei unbestätigtem Schreibausgang oder fehlgeschlagener HOLD-Speicherung gilt dauerhaft HOLD; ein Neustart ist keine Freigabe. Nur die beschriebenen eindeutigen Review-/Merge-Leseprüfungen können den Zustand als -bestätigt kennzeichnen. Für andere Aktionen bleibt eine gesonderte geprüfte +bestätigt kennzeichnen. Ein unbestätigter Lesezugriff und ein an das +Aktionsjournal gebundener Schreibzugriff werden automatisch in eine 60-Sekunden- +Abkühlung überführt; die Wirkungsunsicherheit des Schreibzugriffs bleibt im +Journal, bis der Ziel-Readback sie als eingetreten oder (beim Merge) als +ausgeblieben belegt. Für andere Aktionen bleibt eine gesonderte geprüfte Wiederaufnahme erforderlich. Rate-HOLD erlaubt keinen Kontowechsel zur Umgehung. Mehrhostbetrieb, privater Wrapper-Anschluss und Runtime-Rollout bleiben getrennte Aufgaben. Diese Sourceänderung installiert oder veröffentlicht nichts. diff --git a/src/githubbot_core/actions.py b/src/githubbot_core/actions.py index 8a08836..1adb481 100644 --- a/src/githubbot_core/actions.py +++ b/src/githubbot_core/actions.py @@ -218,20 +218,20 @@ def _confirmed_unknown(action, transport, config): return {"review_id": matched[0]["id"], "head": p["sha"], "account": account, "state": matched[0]["state"]} if action.kind == "pr.merge": pull, error = typed_actions._pull(transport, p["repo"], p["number"]) - sha = pull.get("merge_commit_sha") - if ( - not error - and pull.get("merged") is True - and type(pull.get("number")) is int - and pull["number"] == int(p["number"]) - and isinstance(pull.get("head"), dict) - and pull["head"].get("sha") == p["sha"] - and typed_actions.SHA.fullmatch(str(sha or "")) - ): - return {"merged": True, "merge_commit_sha": sha, "head": p["sha"]} + if error or type(pull.get("number")) is not int or pull["number"] != int(p["number"]): + return None + if pull.get("merged") is False: + return ABSENT # the merge is the only effect; read only after the settle cooldown + if pull.get("merged") is True and isinstance(pull.get("head"), dict) and pull["head"].get("sha") == p["sha"]: + sha = typed_actions.merged_commit_sha(transport, pull, pull.get("node_id"), p["sha"]) + if sha: + return {"merged": True, "merge_commit_sha": sha, "head": p["sha"]} return None +ABSENT = "absent" + + def _coordinated_action(action, transport, config, digest): coordinator = getattr(transport, "coordinator", None) or Coordinator() # Fixed ordering: operation lock -> transport lock. The parent wrapper must @@ -259,6 +259,13 @@ def _coordinated_action(action, transport, config, digest): if prior.get("plan") != digest: raise Hold("unknown action belongs to another plan or authority") readback = _confirmed_unknown(action, transport, config) + if readback == ABSENT: + coordinator.discard(key) + return { + "status": "failed", + "detail": "unknown write confirmed absent by readback; journal cleared; " + "nothing repeated, apply the plan again", + } if readback is None: return { "status": "failed", @@ -273,11 +280,14 @@ def _coordinated_action(action, transport, config, digest): intent = {"schema": "githubbot-core.intent/v1", "id": action.action_id, "plan": digest, "status": "inflight"} started = False - def before_effect(): + def before_effect(request_id=None): nonlocal started if not started: coordinator.save(key, intent) started = True + if request_id is not None: + # The journal now carries this write's effect uncertainty. + coordinator.bind_request(request_id, key) class JournalTransport: def __getattr__(self, name): @@ -290,8 +300,8 @@ def request(self, method, endpoint, body=None): before_effect() return transport.request(method, endpoint, body) - def before_git_effect(self): - before_effect() + def before_git_effect(self, request_id=None): + before_effect(request_id) try: data, error = EXECUTORS[action.kind](JournalTransport(), action.params, config) diff --git a/src/githubbot_core/coordination.py b/src/githubbot_core/coordination.py index 276a595..3cfc372 100644 --- a/src/githubbot_core/coordination.py +++ b/src/githubbot_core/coordination.py @@ -4,6 +4,7 @@ import hashlib import json +import logging import math import os import time @@ -13,6 +14,8 @@ from pathlib import Path MUTATION_INTERVAL = 1.0 +_SETTLE_SECONDS = 60 # same conservative minimum as an unreadable rate reply +_BASE_MARKER = {"schema", "id", "status"} class Hold(RuntimeError): @@ -142,8 +145,12 @@ def _rate_state_locked(self): def _pending_request_locked(self): marker = self.load("github-com-request") + extra = set(marker) - _BASE_MARKER if marker and ( - set(marker) != {"schema", "id", "status"} + not _BASE_MARKER <= set(marker) + or extra not in (set(), {"read"}, {"action"}) + or ("read" in marker and marker["read"] is not True) + or ("action" in marker and not _is_action_key(marker["action"])) or marker.get("schema") != "githubbot-core.request/v1" or marker.get("status") != "inflight" or not isinstance(marker.get("id"), str) @@ -153,8 +160,27 @@ def _pending_request_locked(self): raise Hold("request uncertainty marker invalid; operator inspection required") return marker + def _settleable_locked(self, marker): + # A read cannot have an effect; a journal-bound write's effect uncertainty + # is held by its action journal. Either way only the rate state is unknown. + # A legacy/unbound write marker never qualifies. + return marker.get("read") is True or ("action" in marker and bool(self.load(marker["action"]))) + + def _settle_locked(self, marker): + """Caller holds transport -> rate-state: the marked request has ended.""" + self._rate_hold_locked(seconds=_SETTLE_SECONDS) + self._remove_request_locked(marker["id"]) + logging.getLogger(__name__).warning( + "request uncertainty settled into %ss cooldown (%s)", + _SETTLE_SECONDS, + "read" if marker.get("read") else "write held by action journal", + ) + def _check_rate_locked(self, mutation=False): - if self._pending_request_locked(): + marker = self._pending_request_locked() + if marker and self._settleable_locked(marker): + raise Hold("request in flight or awaiting automatic settlement; nothing sent") + if marker: raise Hold("request uncertainty HOLD; operator inspection required") state = self._rate_state_locked() now = self.clock() @@ -193,9 +219,15 @@ def _rate_hold_locked(self, *, seconds=None, policy=False): def begin_request(self, mutation=False): """Caller holds transport lock; durable marker must precede any request.""" with self.lock("github-com-rate-state"): + stale = self._pending_request_locked() + if stale and self._settleable_locked(stale): + # We hold the transport lock, so its request is over (or its process died). + self._settle_locked(stale) self._check_rate_locked(mutation) request_id = uuid.uuid4().hex marker = {"schema": "githubbot-core.request/v1", "id": request_id, "status": "inflight"} + if not mutation: + marker["read"] = True self.save("github-com-request", marker) if self._pending_request_locked() != marker: raise Hold("request marker persistence unconfirmed; nothing sent") @@ -213,6 +245,35 @@ def _remove_request_locked(self, request_id): finally: os.close(directory) + def bind_request(self, request_id, action_key): + """Caller holds transport lock, before the effect, after the action journal is durable.""" + with self.lock("github-com-rate-state"): + marker = self._pending_request_locked() + if not marker or marker["id"] != request_id or set(marker) != _BASE_MARKER: + raise Hold("request marker changed; nothing sent") + if not _is_action_key(action_key) or not self.load(action_key): + raise Hold("action journal missing; nothing sent") + bound = {**marker, "action": action_key} + self.save("github-com-request", bound) + if self._pending_request_locked() != bound: + raise Hold("request marker binding unconfirmed; nothing sent") + + def settle_request(self, request_id): + """Caller holds transport lock; the request ended unconfirmed. + + A read or a journal-bound write becomes a bounded cooldown; an unbound + write keeps its uncertainty HOLD. Failed persistence keeps the marker. + """ + with self.lock("github-com-rate-state"): + marker = self._pending_request_locked() + if marker and marker["id"] == request_id and self._settleable_locked(marker): + self._settle_locked(marker) + + def discard(self, name): + path = self.root / (name + ".json") + _regular(path) + path.unlink(missing_ok=True) + def finish_request(self, request_id): """Caller holds transport lock; only after complete safe response handling.""" with self.lock("github-com-rate-state"): @@ -238,3 +299,12 @@ def settle_request_as_policy_hold(self, request_id): @staticmethod def action_key(action_id): return "action-" + hashlib.sha256(action_id.encode("ascii")).hexdigest() + + +def _is_action_key(value): + return ( + isinstance(value, str) + and value.startswith("action-") + and len(value) == 71 + and all(c in "0123456789abcdef" for c in value[7:]) + ) diff --git a/src/githubbot_core/transport.py b/src/githubbot_core/transport.py index f9788db..27e20d4 100644 --- a/src/githubbot_core/transport.py +++ b/src/githubbot_core/transport.py @@ -93,11 +93,16 @@ def _invoke_response(self, args, stdin=None, *, env=None, generic_errors=False, with self.coordinator.lock("github-com-transport"): request_id = self.coordinator.begin_request(mutation) if mutation and before_effect is not None: - before_effect() + before_effect(request_id) request_attempted = True response = self._invoke_once(args, stdin, env=env, generic_errors=generic_errors) if response.state_confirmed: self.coordinator.finish_request(request_id) + else: + try: + self.coordinator.settle_request(request_id) + except (Hold, OSError): + pass # marker stays; the next transport holder settles or HOLDs return response except (Hold, OSError): message = ( diff --git a/src/githubbot_core/typed_actions.py b/src/githubbot_core/typed_actions.py index 150aca8..ec24dfd 100644 --- a/src/githubbot_core/typed_actions.py +++ b/src/githubbot_core/typed_actions.py @@ -214,12 +214,46 @@ def _reviewed_pull(transport, params: dict, *, draft: bool) -> tuple[dict, Optio ) +def _identity_denial(user, error, account: str, role: str) -> Optional[str]: + """A transport failure is not a foreign identity: report which of the two it is.""" + if error: + return f"identity of the configured {role} account {account!r} unreadable ({error}); nothing written" + if not isinstance(user, dict) or user.get("login") != account: + return f"identity is not the configured {role} account {account!r}" + return None + + +def merged_commit_sha(transport, after: dict, node_id, sha: str) -> Optional[str]: + """Merge commit of a readback already showing ``merged``; None when unconfirmed. + + REST 2026-03-10 removed merge_commit_sha from pull request objects. Read the + actual merged commit; never retry the merge or trust acceptance alone. + """ + commit_sha = after.get("merge_commit_sha") + if not commit_sha: + if not node_id: + return None + data, error = transport.request( + "POST", "graphql", {"query": MERGE_READBACK_QUERY, "variables": {"id": node_id}} + ) + if error or not isinstance(data, dict) or data.get("errors"): + return None + payload = data.get("data") + node = payload.get("node") if isinstance(payload, dict) else None + if not isinstance(node, dict) or node.get("state") != "MERGED" or node.get("headRefOid") != sha: + return None + commit = node.get("mergeCommit") + commit_sha = commit.get("oid") if isinstance(commit, dict) else None + return commit_sha if SHA.fullmatch(str(commit_sha or "")) else None + + def exec_merge(transport, params: dict, config: dict): account = str((config.get("multi_bot") or {}).get("merge_account") or "") if account: user, error = transport.get("user") - if error or (user or {}).get("login") != account: - return None, f"identity is not the configured merge account {account!r}" + denial = _identity_denial(user, error, account, "merge") + if denial: + return None, denial pull, error = _reviewed_pull(transport, params, draft=False) if error: return None, error @@ -238,24 +272,8 @@ def exec_merge(transport, params: dict, config: dict): after, error = _pull(transport, repo, number) if error or after.get("merged") is not True: return None, "merge not confirmed by readback" - commit_sha = after.get("merge_commit_sha") + commit_sha = merged_commit_sha(transport, after, pull.get("node_id"), params["sha"]) if not commit_sha: - # REST 2026-03-10 removed merge_commit_sha from pull request objects. - # Read the actual merged commit; never retry the merge or trust acceptance alone. - if not pull.get("node_id"): - return None, "merge not confirmed by readback" - data, error = transport.request( - "POST", "graphql", {"query": MERGE_READBACK_QUERY, "variables": {"id": pull["node_id"]}} - ) - if error or not isinstance(data, dict) or data.get("errors"): - return None, "merge not confirmed by readback" - payload = data.get("data") - node = payload.get("node") if isinstance(payload, dict) else None - if not isinstance(node, dict) or node.get("state") != "MERGED" or node.get("headRefOid") != params["sha"]: - return None, "merge not confirmed by readback" - commit = node.get("mergeCommit") - commit_sha = commit.get("oid") if isinstance(commit, dict) else None - if not SHA.fullmatch(str(commit_sha or "")): return None, "merge not confirmed by readback" return {"readback": {"merged": True, "merge_commit_sha": commit_sha}}, None @@ -343,8 +361,9 @@ def exec_review(transport, params: dict, config: dict): if not account: return None, "pr.review requires the configured multi_bot.merge_account" user, error = transport.get("user") - if error or not isinstance(user, dict) or user.get("login") != account: - return None, f"identity is not the configured review account {account!r}" + denial = _identity_denial(user, error, account, "review") + if denial: + return None, denial repo, number, sha = params["repo"], int(params["number"]), params["sha"] endpoint = f"repos/{repo}/pulls/{number}" @@ -440,8 +459,9 @@ def exec_close(transport, params: dict, config: dict): def current_target(): user, error = transport.get("user") - if error or not isinstance(user, dict) or user.get("login") != account: - return None, "identity is not the configured close account" + denial = _identity_denial(user, error, account, "close") + if denial: + return None, denial branch, error = _default_branch(transport, repo) if error or not isinstance(branch, str): return None, error or "default branch unreadable" @@ -803,7 +823,9 @@ def exec_push_branch(transport, params: dict, config: dict): user, error = get_for_token(token, "user") except Exception: return None, "configured bot identity unreadable" - if error or not isinstance(user, dict) or user.get("login") != account: + if error: + return None, f"configured bot identity unreadable ({error}); nothing pushed" + if not isinstance(user, dict) or user.get("login") != account: return None, "credential identity does not match the configured bot account" try: repository, error = get_for_token(token, f"repos/{repo}") @@ -844,7 +866,7 @@ def exec_push_branch(transport, params: dict, config: dict): # No '+' refspec and no --force: a non-fast-forward is rejected by git itself. marker = getattr(transport, "before_git_effect", None) if marker is not None: - marker() + marker(request_id) _, error = _run_git(path, "push", "origin", f"{sha}:{ref}", env=env, repo=repo) if error: return None, f"{error}; push outcome is unknown; read the target before retrying" diff --git a/tests/test_coordination.py b/tests/test_coordination.py index 9040afe..6418f90 100644 --- a/tests/test_coordination.py +++ b/tests/test_coordination.py @@ -732,7 +732,9 @@ def run(*args, **kw): for child in contender: finish(child) assert fresh_request_is_blocked(root)["requests"] == 0 - assert (root / "github-com-request.json").exists() + # A read marker never outlives the next transport holder; the cooldown still stops requests. + assert not (root / "github-com-request.json").exists() + assert Coordinator(root).load("github-com-rate")["not_before"] > time.time() def test_timeout_and_restart_keep_request_marker_without_retry(tmp_path): @@ -748,6 +750,45 @@ def run(*args, **kw): assert fresh_request_is_blocked(root)["requests"] == 0 +def test_unconfirmed_read_settles_into_cooldown_instead_of_operator_hold(tmp_path): + # A GET cannot have an effect; only the rate state is unknown -> bounded cooldown. + now = [1000] + c = Coordinator(tmp_path / "read", clock=lambda: now[0]) + calls = [] + + def run(*args, **kw): + calls.append(1) + if len(calls) == 1: + raise subprocess.TimeoutExpired("synthetic-gh", 1) + return reply() + + t = GhCliTransport(runner=run, coordinator=c) + assert "outcome unconfirmed" in t.get("user")[1] + assert not (c.root / "github-com-request.json").exists() + assert c.load("github-com-rate")["not_before"] == 1060 + now[0] = 1059 + assert t.get("user")[1] == "GitHub coordination HOLD; no request sent" and len(calls) == 1 + now[0] = 1060 + assert t.get("user") == ({"ok": True}, None) and len(calls) == 2 + + +def test_legacy_or_unbound_write_marker_still_needs_operator(tmp_path): + # Negative control: a marker that may belong to an unjournaled write is never auto-settled. + c = Coordinator(tmp_path / "legacy", clock=lambda: 10**9) + c.prepare() + marker = {"schema": "githubbot-core.request/v1", "id": "a" * 32, "status": "inflight"} + c.save("github-com-request", marker) + calls = [] + t = GhCliTransport(runner=lambda *a, **kw: calls.append(1), coordinator=c) + assert t.get("user")[1] == "GitHub coordination HOLD; no request sent" and not calls + assert c.load("github-com-request") == marker + (c.root / "github-com-request.json").unlink() + with c.lock("github-com-transport"): + request_id = c.begin_request(mutation=True) + assert t.get("user")[1] == "GitHub coordination HOLD; no request sent" and not calls + assert c.load("github-com-request")["id"] == request_id + + def test_marker_must_be_durable_before_request(tmp_path): class NoMarker(Coordinator): def save(self, name, value): @@ -802,6 +843,14 @@ def test_transport_process_death_leaves_uncertainty_for_next_process(tmp_path): assert (root / "github-com-request.json").exists() assert [json.loads(x)[0] for x in (root / "trace").read_text().splitlines()] == ["start"] assert fresh_request_is_blocked(root)["requests"] == 0 + # The next holder of the transport lock settled the dead reader's marker into a cooldown. + assert not (root / "github-com-request.json").exists() + import time + + later = Coordinator(root, clock=lambda: time.time() + 61) + calls = [] + assert GhCliTransport(runner=lambda *a, **kw: calls.append(1) or reply(), coordinator=later).get("user")[1] is None + assert len(calls) == 1 def test_successful_response_with_failed_marker_cleanup_remains_blocked(tmp_path): @@ -956,7 +1005,9 @@ def run(command, **kw): result = apply([action], transport, config) assert result["receipts"][0]["status"] == "failed" assert c.load(c.action_key(action.action_id))["status"] == "unknown" - assert (root / "github-com-request.json").exists() + # Effect uncertainty now lives in the action journal; the host-wide marker became a cooldown. + assert not (root / "github-com-request.json").exists() + assert c.load("github-com-rate")["not_before"] > __import__("time").time() assert len([cmd for cmd in calls if "--method" in cmd]) == 1 assert fresh_request_is_blocked(root)["requests"] == 0 result = json.loads(finish(spawn(root, "action"))) @@ -984,7 +1035,7 @@ def run(*args, **kw): @pytest.mark.parametrize("method_name", ["get", "get_paginated", "get_text", "get_for_token", "request_get"]) -def test_headerless_successful_get_keeps_marker_and_rejects_result(tmp_path, monkeypatch, method_name): +def test_headerless_successful_get_settles_marker_and_rejects_result(tmp_path, monkeypatch, method_name): root = tmp_path / method_name calls = [] @@ -1011,7 +1062,7 @@ def fake_run(cmd, **kwargs): data, error = transport.request("GET", "user") assert data is None and error and "outcome unconfirmed" in error assert len(calls) == 1 - assert (root / "github-com-request.json").exists() + assert not (root / "github-com-request.json").exists() assert fresh_request_is_blocked(root)["requests"] == 0 @@ -1031,3 +1082,76 @@ def fake_run(cmd, **kwargs): assert not (root / "github-com-request.json").exists() assert transport.get("user")[1] == "GitHub coordination HOLD; no request sent" assert len(calls) == 1 + + +def merge_world(state): + """Routing gh runner for one merge PR; REST omits merge_commit_sha like API 2026-03-10.""" + from test_typed_actions import REPO, SHA, OTHER + + calls = [] + + def run(cmd, **kw): + calls.append(cmd) + if "--method" in cmd: + if cmd[cmd.index("--method") + 1] == "PUT": + if state["put"] == "timeout": + raise subprocess.TimeoutExpired("synthetic-gh", 1) + state["pull"] = {**state["pull"], "merged": True, "state": "closed"} + return reply(body='{"merged": true}') + node = {"state": "MERGED", "headRefOid": SHA, "mergeCommit": {"oid": OTHER}} + return reply(body=json.dumps({"data": {"node": node}})) + endpoint = cmd[-1] + if endpoint == f"repos/{REPO}/pulls/7": + return reply(500) if state["pull"] is None else reply(body=json.dumps(state["pull"])) + bodies = {"user": {"login": "example-bot"}, f"repos/{REPO}": {"full_name": REPO, "default_branch": "main"}} + return reply(body=json.dumps(bodies[endpoint] if endpoint in bodies else [])) + + return calls, run + + +@pytest.mark.parametrize("verdict", ["merged", "absent", "unreadable"]) +def test_unknown_merge_write_is_resolved_only_by_target_readback(tmp_path, verdict): + from test_typed_actions import config, merge_action, pull + from githubbot_core.actions import apply + + now = [1000] + c = Coordinator(tmp_path / "write", 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) + + def puts(): + return [cmd for cmd in calls if "PUT" in cmd] + + first = apply([a], t, config())["receipts"][0] + assert first["status"] == "failed" and len(puts()) == 1 + assert c.load(key)["status"] == "unknown" + assert not (c.root / "github-com-request.json").exists() + assert c.load("github-com-rate")["not_before"] == 1060 + sent = len(calls) + now[0] = 1059 + assert apply([a], t, config())["receipts"][0]["status"] in {"denied", "failed"} + assert len(calls) == sent # cooldown: nothing sent, not even a readback + + now[0] = 1060 + if verdict == "merged": + state["pull"] = {**state["pull"], "merged": True, "state": "closed"} + if verdict == "unreadable": + state["pull"] = None + second = apply([a], t, config())["receipts"][0] + assert len(puts()) == 1 # never repeated by reconciliation + if verdict == "merged": + assert second["status"] == "skipped_confirmed" + assert c.load(key)["status"] == "applied" + elif verdict == "absent": + assert second["status"] == "failed" and "confirmed absent" in second["detail"] + assert c.load(key) == {} + state["put"] = "ok" + assert apply([a], t, config())["receipts"][0]["status"] == "applied" + assert len(puts()) == 2 # only the next explicit apply writes again + else: + # Negative control: no definitive readback -> the action stays in HOLD. + assert second["status"] == "failed" and "unknown write HOLD" in second["detail"] + assert c.load(key)["status"] == "unknown" diff --git a/tests/test_typed_actions.py b/tests/test_typed_actions.py index 69a8ec0..a8d037c 100644 --- a/tests/test_typed_actions.py +++ b/tests/test_typed_actions.py @@ -838,3 +838,40 @@ def test_cli_act_previews_then_applies_with_expected_plan(tmp_path, capsys): assert preview["actions"][0]["permitted"] and transport.writes == [] assert cli.main([*argv, "--apply", "--expect-plan", preview["plan_sha256"]], transport=transport) == 0 assert json.loads(capsys.readouterr().out)["data"]["receipts"][0]["status"] == "applied" + + +class IdentityUnreadable(TokenTransport): + """The identity read fails in transport; it must never look like a foreign account.""" + + def get(self, endpoint): + return (None, "Timeout; outcome unconfirmed") if endpoint == "user" else super().get(endpoint) + + def get_for_token(self, token, endpoint): + return (None, "GitHub request failed") if endpoint == "user" else super().get_for_token(token, endpoint) + + +@pytest.mark.parametrize("executor", [typed_actions.exec_merge, typed_actions.exec_review]) +def test_identity_transport_failure_is_not_reported_as_foreign_identity(executor): + t = IdentityUnreadable(base_gets()) + params = {"repo": REPO, "number": 7, "sha": SHA, "event": "APPROVE", "body": "synthetic"} + data, error = executor(t, params, config()) + assert data is None and t.writes == [] + assert "unreadable" in error and "Timeout; outcome unconfirmed" in error + assert "is not the configured" not in error + + +def test_push_identity_transport_failure_is_not_a_credential_mismatch(monkeypatch): + _mock_push_token(monkeypatch) + calls = [] + monkeypatch.setattr(typed_actions, "_git", lambda cmd, **kwargs: calls.append(cmd)) + t = IdentityUnreadable({f"repos/{REPO}": {"default_branch": "main"}}) + data, error = typed_actions.exec_push_branch(t, _push_action().params, config()) + assert data is None and calls == [] + assert "unreadable" in error and "does not match" not in error + + +def test_foreign_identity_is_still_reported_as_foreign(): + gets = base_gets() + gets["user"] = {"login": "someone-else"} + data, error = typed_actions.exec_merge(Transport(gets), merge_action().params, config()) + assert data is None and "is not the configured merge account" in error