fix(orchestrator): keep installs off a running hub row and fail orphaned jobs

The runner records the hub row it runs in runner-job.json of the hub
state directory (new --state flag, set by the runner unit) and drops it
when the row ends. orchestrator.sh idle exits 1 with the row's task and
job id while that file names a live pid; install, stop, runner and the
home install.sh check it first, because stopping the runner would kill
the row. A starting runner posts /api/runner/restart, and the hub fails
every job an earlier runner left running, closing its row like a failed
run with the reason that the runner restarted.

🎯 Fix: 92 %
💥 Break: 4 %
💸 Tokens: 100 %
⏱️ Velocity: –
🛡️ Security: 100 %
🏆 Score: 88
🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 %

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-27 10:44:15 +00:00
1 parent 0f8cb32198
commit 30862411f3
15 files changed
+411 -56

No files matched your search

+82 -23
View File
@@ -6,6 +6,8 @@
--approvers: the pinned passkeys, e.g. ~/.config/kvb-orchestrator/approvers.json.
--replay: the runner's replay store, outside the hub's reach, e.g.
~/.local/state/kvb-orchestrator-approvals/runner.json.
--state: the hub state dir, e.g. ~/.local/state/kvb-orchestrator, where
the runner keeps runner-job.json while a job runs.
--rasci: the installed register script, e.g.
~/.claude/skills/kvb-org-rasci/scripts/rasci.py; optional.
--council: the council directory holding rasci.json, the agents'
@@ -44,8 +46,15 @@ Returns:
every PREVIEW_SECONDS, it posts, for each open operator row that is a git merge of a full commit
id (staged_diff.merge_of) whose HEAD differs from the preview the hub
holds, staged_diff.merge_preview, which its Match card shows; such a
merge whose job names the previewed HEAD is refused once HEAD moved. The
exit code is 0.
merge whose job names the previewed HEAD is refused once HEAD moved.
At start, before its first cycle, it removes a leftover runner-job.json
and posts /api/runner/restart once, so the hub fails every job an
earlier runner left running; a failed post is printed to stderr. While
it runs a job it keeps runner-job.json, {pid, job, task, started} with
its own pid, written by rename with mode 0600 and removed when the job
ends, whatever the outcome; `orchestrator.sh idle` refuses an install
while that pid lives, and a job whose marker cannot be written is
refused. The exit code is 0.
"""
from __future__ import annotations
@@ -77,6 +86,8 @@ import verifier
LINES = 200
PREVIEWS = "/api/runner/previews"
RESTART = "/api/runner/restart"
MARKER = "runner-job.json"
ERROR_LIMIT = 500
PREVIEW_FAILURES = (OSError, ValueError, staged_diff.DiffError)
BEAT = 2.0
@@ -100,6 +111,7 @@ class Host(NamedTuple):
shell: str
operator: Path | None
council: Path | None
marker: Path
def call(base: str, path: str, payload: dict | None) -> dict:
@@ -422,6 +434,42 @@ def sender(base: str, job_id: str) -> Callable[[dict], None]:
return send
def mark(marker: Path, job: dict) -> str | None:
"""Args:
marker: runner-job.json in the hub state dir.
job: the claimed job about to run, with id and task.
Returns:
Why the job must not run: the marker that makes `orchestrator.sh
idle` refuse an install, which would stop the runner under the job,
cannot be written; None once it is written.
"""
try:
verifier.write_private(marker, {"pid": os.getpid(), "job": job["id"], "task": job["task"], "started": time.time()})
except OSError as error:
return f"refused: the runner cannot write {marker}, which keeps an install from stopping it under this job: {error}"
return None
def refused(claimed: dict, trust: verifier.Trust, register: Register | None, gates: Path | None) -> str | None:
kind = claimed.get("kind")
if kind == TASK_JOB:
return UNREGISTERED if register is None else council_refusal(register.council) or task_refusal(claimed, trust, time.time())
if kind == GATE_JOB:
return UNGATED if gates is None else gate_refusal(claimed, trust, time.time())
return refusal(claimed, trust, time.time()) or moved(claimed)
def run(claimed: dict, register: Register | None, gates: Path | None, host: Host, send: Callable[[dict], None]) -> None:
kind = claimed.get("kind")
if kind == TASK_JOB:
change(claimed, register, send)
elif kind == GATE_JOB:
gate(claimed, gates, send)
else:
execute(claimed, host, send)
def cycle(base: str, trust: verifier.Trust, register: Register | None, gates: Path | None, host: Host) -> None:
for job in call(base, "/api/runner/jobs", None)["jobs"]:
try:
@@ -429,21 +477,36 @@ def cycle(base: str, trust: verifier.Trust, register: Register | None, gates: Pa
except urllib.error.HTTPError:
continue
send = sender(base, claimed["id"])
kind = claimed.get("kind")
if kind == TASK_JOB:
reason = UNREGISTERED if register is None else council_refusal(register.council) or task_refusal(claimed, trust, time.time())
elif kind == GATE_JOB:
reason = UNGATED if gates is None else gate_refusal(claimed, trust, time.time())
else:
reason = refusal(claimed, trust, time.time()) or moved(claimed)
reason = refused(claimed, trust, register, gates) or mark(host.marker, claimed)
if reason is not None:
send({"output": reason, "code": None, "refused": True})
elif kind == TASK_JOB:
change(claimed, register, send)
elif kind == GATE_JOB:
gate(claimed, gates, send)
else:
execute(claimed, host, send)
continue
try:
run(claimed, register, gates, host, send)
finally:
host.marker.unlink(missing_ok=True)
def restart(base: str, marker: Path) -> None:
marker.unlink(missing_ok=True)
try:
call(base, RESTART, {})
except (OSError, ValueError, TypeError) as error:
print(f"runner: the hub keeps the jobs an earlier runner left running: {error}", file=sys.stderr)
def post_previews(base: str, rules: Path | None, told: str) -> str:
"""Returns:
The error this post failed with, printed unless it equals told, the
one printed last; "" once a post succeeds.
"""
try:
previews(base, rules)
except (OSError, ValueError, KeyError, TypeError) as error:
if str(error) != told:
print(f"runner: no merge previews: {error}", file=sys.stderr)
return str(error)
return ""
def main() -> int:
@@ -452,6 +515,7 @@ def main() -> int:
parser.add_argument("--interval", type=float, required=True)
parser.add_argument("--approvers", type=Path, required=True)
parser.add_argument("--replay", type=Path, required=True)
parser.add_argument("--state", type=Path, required=True)
parser.add_argument("--rasci", type=Path)
parser.add_argument("--council", type=Path)
parser.add_argument("--gates", type=Path)
@@ -461,18 +525,13 @@ def main() -> int:
base = hub_api.base_url(args.port)
trust = verifier.Trust(approvers=args.approvers, replay=args.replay, origin=signing.origin_of(args.port))
register = Register(rasci=args.rasci, council=args.council) if args.rasci and args.council else None
host = Host(shell=os.environ.get("SHELL") or pwd.getpwuid(os.geteuid()).pw_shell, operator=args.operator, council=args.council)
host = Host(shell=os.environ.get("SHELL") or pwd.getpwuid(os.geteuid()).pw_shell, operator=args.operator, council=args.council, marker=args.state / MARKER)
rules, told, previewed = staged_diff.rules_root(), "", None
restart(base, host.marker)
while True:
if previewed is None or time.monotonic() - previewed >= PREVIEW_SECONDS:
previewed = time.monotonic()
try:
previews(base, rules)
told = ""
except (OSError, ValueError, KeyError, TypeError) as error:
if str(error) != told:
print(f"runner: no merge previews: {error}", file=sys.stderr)
told = str(error)
told = post_previews(base, rules, told)
try:
cycle(base, trust, register, args.gates, host)
except (OSError, ValueError, KeyError, TypeError):
+5 -2
View File
@@ -29,6 +29,7 @@ BOARD = re.compile(r"/api/board/([a-z-]{1,32})")
UPLOADS = "/api/uploads"
MATCH_ROUTE = "/api/match"
PREVIEWS_ROUTE = "/api/runner/previews"
RESTART_ROUTE = "/api/runner/restart"
MATCH_POSTS = {"/api/match/stale": "match_stale", "/api/match/snapshot": "match_snapshot"}
HOOK_POSTS = {"/api/asks": "ask", "/api/decisions": "question"}
POSTS = (*HOOK_POSTS, UPLOADS, "/api/messages", *MATCH_POSTS)
@@ -283,7 +284,9 @@ class Handler(Exchange):
def runner(self, path: str, body: bytes) -> None:
hub = self.server.hub
route = RUNNER_ROUTE.fullmatch(path)
if route is None:
if path == RESTART_ROUTE:
self.answer(hub.restart_runner, HTTPStatus.OK)
elif route is None:
self.answer(lambda: hub.record_preview(body), HTTPStatus.OK)
elif route.group(2) == "claim":
self.answer(lambda: hub.claim(route.group(1)), HTTPStatus.OK)
@@ -303,7 +306,7 @@ class Handler(Exchange):
return lambda body: self.answer(lambda: receive(body), HTTPStatus.OK if path in MATCH_POSTS else HTTPStatus.CREATED)
self.send_text(HTTPStatus.FORBIDDEN, "forbidden: local POST with the X-Kvb-Orchestrator header and no foreign origin only")
return None
if RUNNER_ROUTE.fullmatch(path) or path == PREVIEWS_ROUTE:
if RUNNER_ROUTE.fullmatch(path) or path in (PREVIEWS_ROUTE, RESTART_ROUTE):
if self.client():
return lambda body: self.runner(path, body)
self.send_text(HTTPStatus.FORBIDDEN, "forbidden: the runner calls with the X-Kvb-Orchestrator header and no origin only")
+37 -6
View File
@@ -15,6 +15,7 @@ TASK_JOB = "task"
GATE_JOB = "gate"
CHANGES = (TASK_JOB, GATE_JOB)
UNRUNNABLE = "The hub runner needs a command and an absolute directory, and this row lacks one; run it with operator.py run in a terminal."
RESTARTED = "the runner restarted while this job ran; run the row again"
def runner_job(job: dict) -> dict:
@@ -148,11 +149,39 @@ class Jobs:
job, changed = self.jobs.transition(job_id, "running", {"status": status, "code": code, "output": output, "finished": time.time()})
if not changed:
raise Conflict({"id": job_id, "status": job["status"]})
runs = self.close_row(job, status, code, checked is True)
tail = "\n".join(output.splitlines()[-20:])
self.log.add({"kind": "run", "title": f"{status}: {job['command'][:200]}", "text": tail, "ref": {"job": job_id, "task": job["task"], "code": code, "status": status}})
return self.ended(job, checked is True)
def restart_runner(self) -> dict:
"""Returns:
{"failed": ids}: every running job, which the restart of the
runner killed, turned failed with RESTARTED as its output, code
None and finished now, its row closed like a failed run.
"""
failed = []
for job in self.jobs.listed():
record, changed = self.jobs.transition(job["id"], "running", {"status": "failed", "code": None, "output": RESTARTED, "finished": time.time()})
if changed:
self.ended(record, False)
failed.append(job["id"])
return {"failed": failed}
def ended(self, job: dict, checked: bool) -> dict:
"""Args:
job: a job that just left running, with its status, code and
output.
checked: as in close_row().
Returns:
{"id", "status", "code", "runs", "told"} after its row closed
(close_row()), the run went to the log and, for a task change,
its batch was told (tell_applied()).
"""
status, code = job["status"], job["code"]
runs = self.close_row(job, status, code, checked)
tail = "\n".join(job["output"].splitlines()[-20:])
self.log.add({"kind": "run", "title": f"{status}: {job['command'][:200]}", "text": tail, "ref": {"job": job["id"], "task": job["task"], "code": code, "status": status}})
told = self.tell_applied(job) if job.get("kind") == TASK_JOB else []
return {"id": job_id, "status": status, "code": code, "runs": runs, "told": told}
return {"id": job["id"], "status": status, "code": code, "runs": runs, "told": told}
def close_row(self, job: dict, status: str, code: int | None, checked: bool) -> list[dict]:
"""Args:
@@ -165,14 +194,16 @@ class Jobs:
job on its row: `ran` on exit 0, with --check-failed unless
checked, so the row stays open; `failed` with where the output
stays, the job's console, never the output itself, on any other
exit; none for a refused job or a task or gate change.
exit and, why RESTARTED, on a failed job without code, which a
runner restart killed; none for a refused job or a task or gate
change.
"""
if job.get("kind") in CHANGES or status not in ("done", "failed"):
return []
slug = job["task"].removeprefix(OPERATOR)
shown = [slug, f"--command={job['command']}", f"--dir={job['directory']}"]
if status == "failed":
why = f"killed by signal {-code}" if code < 0 else f"exit {code}"
why = RESTARTED if code is None else f"killed by signal {-code}" if code < 0 else f"exit {code}"
where = f"the console of hub job {job['id']} under the row in Waits on Operator"
return [self.scripts.run(OPERATOR_SCRIPT, ["failed", *shown, "--why", why, f"--where={where}"])]
return [self.scripts.run(OPERATOR_SCRIPT, ["ran", *shown] if checked else ["ran", *shown, "--check-failed"])]
@@ -5,7 +5,7 @@ Description=Agent Orchestrator runner: runs the operator commands a pinned passk
Type=simple
Environment=PATH=/usr/bin:/bin
EnvironmentFile=%h/.local/share/kvb-orchestrator/.env
ExecStart=/usr/bin/env python3 %h/.local/share/kvb-orchestrator/client/runner.py --port ${KVB_ORCHESTRATOR_PORT} --interval 2 --approvers %h/.config/kvb-orchestrator/approvers.json --replay %h/.local/state/kvb-orchestrator-approvals/runner.json --rasci %h/.claude/skills/kvb-org-rasci/scripts/rasci.py --council ${KVB_ORCHESTRATOR_COUNCIL} --gates %h/.claude/skills/kvb-check-gate/scripts/gates.py --operator %h/.claude/skills/kvb-org-operator/scripts/operator.py
ExecStart=/usr/bin/env python3 %h/.local/share/kvb-orchestrator/client/runner.py --port ${KVB_ORCHESTRATOR_PORT} --interval 2 --approvers %h/.config/kvb-orchestrator/approvers.json --replay %h/.local/state/kvb-orchestrator-approvals/runner.json --state %h/.local/state/kvb-orchestrator --rasci %h/.claude/skills/kvb-org-rasci/scripts/rasci.py --council ${KVB_ORCHESTRATOR_COUNCIL} --gates %h/.claude/skills/kvb-check-gate/scripts/gates.py --operator %h/.claude/skills/kvb-org-operator/scripts/operator.py
Restart=always
RestartSec=5