Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
47 changes: 38 additions & 9 deletions docs/TRANSPORT_COORDINATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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**
Expand All @@ -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
Expand Down Expand Up @@ -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.
38 changes: 24 additions & 14 deletions src/githubbot_core/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand All @@ -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):
Expand All @@ -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)
Expand Down
74 changes: 72 additions & 2 deletions src/githubbot_core/coordination.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import hashlib
import json
import logging
import math
import os
import time
Expand All @@ -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):
Expand Down Expand Up @@ -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)
Expand All @@ -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()
Expand Down Expand Up @@ -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")
Expand All @@ -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"):
Expand All @@ -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:])
)
7 changes: 6 additions & 1 deletion src/githubbot_core/transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = (
Expand Down
Loading
Loading