Files
gabrielvidalandClaude Opus 5.5 9c4f0440ac fix(worker): an update only counts once a new process answers
/health's `commit` is read live from the checkout, so a sidecar that never
restarted reported the new commit as soon as the checkout moved and the
auto-update said `done` while the old code kept serving (the Orus Mac on
eaf3187: no `agentsMax`, no `labSync`). The installer now notes the port's
listener pid before restarting (/health's new `pid`, else lsof / ss for a
sidecar from before), and when the same process still answers after the
restart it stops it so the new job can bind — runs are detached daemons and
survive. Still the same process after that ⇒ the update fails and rolls back
instead of passing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 12:16:34 +02:00

157 lines
5.7 KiB
Python

"""
Self-update — how a worker follows the hub's version with nobody at its keyboard.
``/health`` says which commit this runner's checkout is on (``commit``), whether
it can update itself (``updatable``) and what the last attempt did
(``update``). The hub compares that commit with the one it was deployed from
and, when the worker is behind, calls ``POST /update {commit}``.
That only *starts* the update: ``worker/install.sh auto-update <commit>`` runs
detached (its own session, so the service restart it causes doesn't take it
down — launchd's AbandonProcessGroup / systemd's KillMode=process), fetches
that commit from Gitea, restarts the service only when the worker side changed,
waits for ``/health`` to report the new commit and rolls back otherwise. It
writes ``update.json`` in the state dir as it goes; this module just reads it.
The direction stays the same: the hub calls in, and the worker fetches from
Gitea, never from the hub.
Only a worker the installer set up from its own clone can update
(``WORKER_UPDATER``, the path of that clone's installer): the host sidecar and
a worker run from a dev checkout answer ``updatable: false``.
"""
from __future__ import annotations
import json
import os
import pathlib
import re
import subprocess
from typing import Callable
from fastapi import APIRouter, Header, HTTPException
from pydantic import BaseModel
import pairing
ROOT = pathlib.Path(__file__).resolve().parent.parent
# A full sha: Gitea (any git server) only serves a commit by its whole name.
_SHA_RE = re.compile(r"^[0-9a-f]{40}$")
_commit_cache: list = [None, None] # [.git/HEAD mtime, sha]
def _head_mtime() -> float | None:
try:
return (ROOT / ".git" / "HEAD").stat().st_mtime_ns
except OSError:
return None # a worktree's .git is a file: no cache, ask git
def commit() -> str | None:
"""The checkout's HEAD (full sha). /health is polled, so it is cached on
.git/HEAD's mtime — a checkout rewrites that file, so a move that restarts
nothing still shows at once."""
key = _head_mtime()
if key is not None and key == _commit_cache[0]:
return _commit_cache[1]
try:
out = subprocess.run(["git", "-C", str(ROOT), "rev-parse", "HEAD"],
capture_output=True, text=True, timeout=5)
sha = out.stdout.strip() if out.returncode == 0 else None
except (OSError, subprocess.SubprocessError):
sha = None
_commit_cache[:] = [key, sha]
return sha
def updater() -> str | None:
p = os.environ.get("WORKER_UPDATER") or ""
return p if p and os.path.isfile(p) else None
def _alive(pid) -> bool:
try:
os.kill(int(pid), 0)
return True
except (OSError, ValueError, TypeError):
return False
def running_pid() -> int | None:
"""The pid of the auto-update in progress (its lock), None when idle."""
try:
pid = int((pairing.state_dir() / "update.lock" / "pid").read_text())
except (OSError, ValueError):
return None
return pid if _alive(pid) else None
def state() -> dict | None:
"""The last auto-update (update.json). One still marked ``updating`` whose
process is gone — the machine slept or was shut mid-way — reads
``interrupted``, so the hub may try again."""
try:
st = json.loads((pairing.state_dir() / "update.json").read_text())
except (OSError, ValueError):
return None
if not isinstance(st, dict):
return None
if st.get("state") == "updating" and not running_pid():
st["state"] = "interrupted"
st.pop("pid", None)
return st
def info() -> dict:
"""The /health fields. ``pid`` lets the installer tell a restarted worker
from one that kept running: ``commit`` is the checkout's HEAD, which an
old process reports too once the checkout has moved."""
return {"commit": commit(), "updatable": bool(updater()), "update": state(),
"pid": os.getpid()}
class UpdateBody(BaseModel):
commit: str
def start(sha: str) -> dict:
"""Start ``install.sh auto-update <sha>`` detached; its output goes to
update.log next to worker.log."""
script = updater()
if not script:
raise HTTPException(409, {"message": "this runner doesn't update itself "
"(not the installer's clone)",
"kind": "no_updater"})
sha = (sha or "").strip().lower()
if not _SHA_RE.match(sha):
raise HTTPException(400, {"message": "commit must be a full 40-hex sha",
"kind": "bad_commit"})
if commit() == sha:
return {"ok": True, "started": False, "reason": "already on it"}
pid = running_pid()
if pid:
return {"ok": True, "started": False, "reason": "an update is running",
"pid": pid}
logs = pathlib.Path(os.environ.get("WORKER_LOG_DIR")
or pairing.state_dir())
logs.mkdir(parents=True, exist_ok=True)
with open(logs / "update.log", "ab") as log:
p = subprocess.Popen(["bash", script, "auto-update", sha],
stdin=subprocess.DEVNULL, stdout=log,
stderr=subprocess.STDOUT, start_new_session=True,
cwd=str(ROOT))
return {"ok": True, "started": True, "pid": p.pid}
def make_router(auth: Callable[[str | None], None]) -> APIRouter:
router = APIRouter()
@router.post("/update")
def update(body: UpdateBody, authorization: str | None = Header(default=None)):
"""Move this worker to ``commit`` (the hub's own) — asynchronous: poll
/health for ``commit`` and ``update``."""
auth(authorization)
return start(body.commit)
return router