fix(update): defer ledger-verified serve/dashboard holders to the updater instead of dead-ending the Desktop hand-off
On Windows, the Desktop update preflight scan (hermes_cli._scan_venv_blockers) classified only python -m http.server as a stoppable blocker. A hermes serve or dashboard backend that survived the Desktop teardown (or was launched manually) either dead-ended the hand-off with venv-blocked, or slipped past it and kept venv\Scripts\hermes.exe mapped, so the updater quarantine failed with os error 32 (#98336). The CLI updater downstream already owns exactly this holder class with positive-identity rungs: _ledger_reapable_backend_pids reaps dead-spawner orphans and _ledger_manual_serve_holders stops manual serves and relaunches them on their recorded host/port. Mirror the existing pausable-gateway exemption: defer ledger-verified serve/dashboard holders to those rungs instead of reporting them as blockers. Identity is positive-only, per the #99558 guard contract: token-parsed subcommand (never substring, #90778) + live-verified (pid, create_time) ledger entry with matching purpose + provable ownership (spawner dead, unrecorded, or the hand-off Desktop itself — an ancestor of the scan, verified by pid+create_time). A backend supervised by any other live process keeps blocking; ledger unreadable fails closed. Fixes #98336
This commit is contained in:
@@ -234,6 +234,93 @@ def _is_pausable_gateway(cmdline: str) -> bool:
|
||||
return looks_like_gateway_command_line(cmdline)
|
||||
|
||||
|
||||
def _is_updater_owned_backend(pid: int, cmdline: str) -> bool:
|
||||
"""Return True when *pid* is a Hermes backend the CLI updater can stop.
|
||||
|
||||
The gateway exemption above keeps ``gateway run`` holders out of the
|
||||
blocker list because the updater's own pause machinery stops and resumes
|
||||
them. ``hermes serve`` / ``hermes dashboard`` backends had no such
|
||||
deferral, so a leaked serve child (or a Desktop-owned backend the
|
||||
teardown lost track of) dead-ended the hand-off with ``venv-blocked`` —
|
||||
or, worse, survived the hand-off and made the shim quarantine fail with
|
||||
``os error 32`` (#98336) — even though the updater downstream owns
|
||||
exactly this case with its ledger rungs (`_ledger_reapable_backend_pids`
|
||||
reaps dead-spawner orphans; `_ledger_manual_serve_holders` stops manual
|
||||
serves and relaunches them on their recorded host/port).
|
||||
|
||||
Positive identity only — never name/substring matching (#90778, and the
|
||||
#99558 identity-guard contract):
|
||||
|
||||
- the argv's parsed SUBCOMMAND (token-based) is ``serve``/``dashboard``;
|
||||
- the machine spawn ledger has a live-verified ``(pid, create_time)``
|
||||
entry for the process with a matching purpose;
|
||||
- ownership is provable: the recorded spawner is dead or unrecorded
|
||||
(the updater's rungs stop/relaunch those), or the spawner is an
|
||||
ancestor of THIS scan — i.e. the Desktop app performing the hand-off,
|
||||
which exits before the updater runs, turning the backend into exactly
|
||||
the dead-spawner orphan the ledger rung reaps.
|
||||
|
||||
A backend whose recorded spawner is alive and is NOT this hand-off's
|
||||
Desktop (a second Desktop window, another supervisor) keeps blocking:
|
||||
that supervisor would respawn whatever the updater kills. Anything
|
||||
unprovable → not exempt (fail closed, pre-exemption behavior).
|
||||
"""
|
||||
try:
|
||||
from hermes_cli.update_cmd import _hermes_holder_subcommand # noqa: PLC0415
|
||||
|
||||
purpose = _hermes_holder_subcommand(cmdline)
|
||||
except Exception:
|
||||
return False
|
||||
if purpose not in ("serve", "dashboard"):
|
||||
return False
|
||||
try:
|
||||
from hermes_cli.process_identity import ( # noqa: PLC0415
|
||||
ledger_entries,
|
||||
spawner_is_dead,
|
||||
)
|
||||
|
||||
entries = ledger_entries()
|
||||
except Exception:
|
||||
return False
|
||||
for entry in entries:
|
||||
if entry.get("pid") != pid:
|
||||
continue
|
||||
if entry.get("purpose") not in ("serve", "dashboard"):
|
||||
return False
|
||||
dead = spawner_is_dead(entry)
|
||||
if dead is not False:
|
||||
# Spawner dead, unrecorded, or unprovable-but-registered: the
|
||||
# updater's ledger rungs own this holder (reap or stop+relaunch).
|
||||
return True
|
||||
return _spawner_is_this_handoff_desktop(entry)
|
||||
return False
|
||||
|
||||
|
||||
def _spawner_is_this_handoff_desktop(entry: dict) -> bool:
|
||||
"""True when the entry's live spawner is an ancestor of this scan.
|
||||
|
||||
The scan subprocess is spawned by the Desktop app's update preflight, so
|
||||
the Desktop performing the hand-off is in our ancestor chain. Identity is
|
||||
verified by ``(pid, create_time)`` — a recycled PID cannot forge the pair.
|
||||
"""
|
||||
spawner_pid = entry.get("spawner_pid")
|
||||
if not isinstance(spawner_pid, int) or spawner_pid <= 0:
|
||||
return False
|
||||
try:
|
||||
import psutil # noqa: PLC0415
|
||||
|
||||
for ancestor in psutil.Process().parents():
|
||||
if ancestor.pid != spawner_pid:
|
||||
continue
|
||||
expected = entry.get("spawner_create")
|
||||
if expected is None:
|
||||
return True
|
||||
return abs(float(ancestor.create_time()) - float(expected)) < 2.0
|
||||
except Exception:
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Entry point. Prints one JSON doc to stdout. Exits 0 for valid scan."""
|
||||
try:
|
||||
@@ -249,8 +336,17 @@ def main() -> None:
|
||||
_emit_probe_fail(f"scan aborted: {exc}")
|
||||
|
||||
processes = []
|
||||
exempted_gateways = 0
|
||||
deferred_backends = 0
|
||||
for pid, name, cmdline in matches:
|
||||
if _is_pausable_gateway(cmdline):
|
||||
exempted_gateways += 1
|
||||
continue
|
||||
if _is_updater_owned_backend(pid, cmdline):
|
||||
# Ledger-verified serve/dashboard backend the CLI updater's own
|
||||
# rungs stop (and relaunch) downstream — reporting it here would
|
||||
# dead-end the hand-off before that machinery can run (#98336).
|
||||
deferred_backends += 1
|
||||
continue
|
||||
process = {
|
||||
"pid": pid,
|
||||
@@ -263,14 +359,16 @@ def main() -> None:
|
||||
process.update(_local_preview_metadata(pid, name))
|
||||
processes.append(process)
|
||||
|
||||
exempted = sum(1 for _pid, _name, cmdline in matches if _is_pausable_gateway(cmdline))
|
||||
data = {
|
||||
"ok": True,
|
||||
"blocked": bool(processes),
|
||||
"processes": processes,
|
||||
# Diagnostic only: gateway processes present but not counted as
|
||||
# blockers because the downstream updater pauses them itself.
|
||||
"pausable_gateways": exempted,
|
||||
"pausable_gateways": exempted_gateways,
|
||||
# Diagnostic only: ledger-verified serve/dashboard backends deferred
|
||||
# to the updater's stop/relaunch rungs (#98336).
|
||||
"deferred_backends": deferred_backends,
|
||||
}
|
||||
print(json.dumps(data))
|
||||
sys.exit(0)
|
||||
|
||||
@@ -325,8 +325,11 @@ def test_main_exempts_gateway_chain_but_keeps_other_holders(monkeypatch, capsys)
|
||||
|
||||
|
||||
def test_main_desktop_serve_backend_still_blocks(monkeypatch, capsys):
|
||||
"""The desktop's own `serve` backend has no downstream pause — it must
|
||||
keep blocking exactly as before the exemption."""
|
||||
"""A `serve` backend with NO ledger identity must keep blocking —
|
||||
the updater's stop/relaunch rungs only own ledger-verified backends."""
|
||||
import hermes_cli.process_identity as pi
|
||||
|
||||
monkeypatch.setattr(pi, "ledger_entries", lambda **kw: [])
|
||||
serve = (
|
||||
78,
|
||||
"python.exe",
|
||||
@@ -337,6 +340,117 @@ def test_main_desktop_serve_backend_still_blocks(monkeypatch, capsys):
|
||||
assert data["blocked"] is True
|
||||
assert [p["pid"] for p in data["processes"]] == [78]
|
||||
assert data["pausable_gateways"] == 0
|
||||
assert data["deferred_backends"] == 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _is_updater_owned_backend — the serve/dashboard deferral (#98336)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
_SERVE_CMD = r"C:\x\venv\Scripts\python.exe -m hermes_cli.main serve --host 127.0.0.1"
|
||||
|
||||
|
||||
def _patch_ledger(monkeypatch, entries, dead):
|
||||
import hermes_cli.process_identity as pi
|
||||
|
||||
monkeypatch.setattr(pi, "ledger_entries", lambda **kw: entries)
|
||||
monkeypatch.setattr(pi, "spawner_is_dead", lambda entry: dead)
|
||||
|
||||
|
||||
def test_updater_owned_backend_dead_spawner_is_deferred(monkeypatch, capsys):
|
||||
"""A ledger-verified serve whose spawner is provably dead is exactly the
|
||||
orphan `_ledger_reapable_backend_pids` reaps — the scan must defer it
|
||||
instead of dead-ending the hand-off (#98336)."""
|
||||
_patch_ledger(
|
||||
monkeypatch, [{"pid": 78, "purpose": "serve", "spawner_pid": 4242}], dead=True
|
||||
)
|
||||
code, data = _run_main_with_detector(monkeypatch, capsys, [(78, "python.exe", _SERVE_CMD)])
|
||||
assert code == 0
|
||||
assert data["blocked"] is False
|
||||
assert data["processes"] == []
|
||||
assert data["deferred_backends"] == 1
|
||||
|
||||
|
||||
def test_updater_owned_backend_unrecorded_spawner_is_deferred(monkeypatch, capsys):
|
||||
"""spawner unrecorded (None from spawner_is_dead) but ledger-registered:
|
||||
the manual-serve rung stops and relaunches it — defer."""
|
||||
_patch_ledger(monkeypatch, [{"pid": 78, "purpose": "serve"}], dead=None)
|
||||
code, data = _run_main_with_detector(monkeypatch, capsys, [(78, "python.exe", _SERVE_CMD)])
|
||||
assert data["blocked"] is False
|
||||
assert data["deferred_backends"] == 1
|
||||
|
||||
|
||||
def test_updater_owned_backend_live_foreign_spawner_still_blocks(monkeypatch, capsys):
|
||||
"""A serve whose recorded spawner is ALIVE and not in this scan's
|
||||
ancestry (another supervisor would respawn it) must keep blocking."""
|
||||
from hermes_cli import _scan_venv_blockers as scan_mod
|
||||
|
||||
_patch_ledger(
|
||||
monkeypatch, [{"pid": 78, "purpose": "serve", "spawner_pid": 4242}], dead=False
|
||||
)
|
||||
monkeypatch.setattr(scan_mod, "_spawner_is_this_handoff_desktop", lambda entry: False)
|
||||
code, data = _run_main_with_detector(monkeypatch, capsys, [(78, "python.exe", _SERVE_CMD)])
|
||||
assert data["blocked"] is True
|
||||
assert [p["pid"] for p in data["processes"]] == [78]
|
||||
assert data["deferred_backends"] == 0
|
||||
|
||||
|
||||
def test_updater_owned_backend_handoff_desktop_spawner_is_deferred(monkeypatch, capsys):
|
||||
"""A serve owned by THIS hand-off's Desktop (the scan's own ancestor) is
|
||||
deferred: the Desktop exits before the updater runs, turning it into the
|
||||
dead-spawner orphan the ledger rung reaps (#98336 field case)."""
|
||||
from hermes_cli import _scan_venv_blockers as scan_mod
|
||||
|
||||
_patch_ledger(
|
||||
monkeypatch, [{"pid": 78, "purpose": "serve", "spawner_pid": 4242}], dead=False
|
||||
)
|
||||
monkeypatch.setattr(scan_mod, "_spawner_is_this_handoff_desktop", lambda entry: True)
|
||||
code, data = _run_main_with_detector(monkeypatch, capsys, [(78, "python.exe", _SERVE_CMD)])
|
||||
assert data["blocked"] is False
|
||||
assert data["deferred_backends"] == 1
|
||||
|
||||
|
||||
def test_updater_owned_backend_purpose_mismatch_blocks(monkeypatch, capsys):
|
||||
"""Argv says serve but the ledger entry says a different purpose — the
|
||||
identity is inconsistent; fail closed and keep blocking."""
|
||||
_patch_ledger(
|
||||
monkeypatch, [{"pid": 78, "purpose": "mcp-helper", "spawner_pid": 4242}], dead=True
|
||||
)
|
||||
code, data = _run_main_with_detector(monkeypatch, capsys, [(78, "python.exe", _SERVE_CMD)])
|
||||
assert data["blocked"] is True
|
||||
assert data["deferred_backends"] == 0
|
||||
|
||||
|
||||
def test_updater_owned_backend_non_backend_argv_never_deferred(monkeypatch, capsys):
|
||||
"""A ledger entry cannot exempt a process whose argv is not a
|
||||
serve/dashboard subcommand (#90778 token rules: `kanban --preserve-cache`
|
||||
must not read as serve)."""
|
||||
_patch_ledger(
|
||||
monkeypatch, [{"pid": 78, "purpose": "serve", "spawner_pid": 4242}], dead=True
|
||||
)
|
||||
kanban = (
|
||||
78,
|
||||
"python.exe",
|
||||
r"C:\x\venv\Scripts\python.exe -m hermes_cli.main kanban --preserve-cache",
|
||||
)
|
||||
code, data = _run_main_with_detector(monkeypatch, capsys, [kanban])
|
||||
assert data["blocked"] is True
|
||||
assert data["deferred_backends"] == 0
|
||||
|
||||
|
||||
def test_updater_owned_backend_ledger_failure_blocks(monkeypatch, capsys):
|
||||
"""Ledger unreadable → unprovable → fail closed (pre-exemption behavior)."""
|
||||
import hermes_cli.process_identity as pi
|
||||
|
||||
def _boom(**kw):
|
||||
raise RuntimeError("ledger unavailable")
|
||||
|
||||
monkeypatch.setattr(pi, "ledger_entries", _boom)
|
||||
code, data = _run_main_with_detector(monkeypatch, capsys, [(78, "python.exe", _SERVE_CMD)])
|
||||
assert data["blocked"] is True
|
||||
assert data["deferred_backends"] == 0
|
||||
|
||||
|
||||
def test_main_gateway_with_long_managed_runtime_path_is_exempt(monkeypatch, capsys):
|
||||
"""Regression: the detector must hand the FULL cmdline to the exemption.
|
||||
|
||||
@@ -305,3 +305,168 @@ class TestConcurrentGateClassification:
|
||||
assert dead.pid in kept_pids, "unknown must keep aborting"
|
||||
finally:
|
||||
_kill(gw, backend)
|
||||
|
||||
|
||||
class TestUpdaterOwnedBackendDeferral:
|
||||
"""#98336 — ledger-verified serve/dashboard holders defer to the CLI
|
||||
updater's stop/relaunch rungs instead of dead-ending the Desktop
|
||||
hand-off (and leaving hermes.exe locked → quarantine os error 32)."""
|
||||
|
||||
@staticmethod
|
||||
def _ledger_write(pid: int, purpose: str, spawner_pid: int | None,
|
||||
spawner_create: float | None) -> None:
|
||||
import psutil
|
||||
|
||||
from hermes_cli.process_identity import (
|
||||
LedgerEntry,
|
||||
_append_entry,
|
||||
install_id,
|
||||
)
|
||||
|
||||
entry = LedgerEntry(
|
||||
pid=pid,
|
||||
create_time=float(psutil.Process(pid).create_time()),
|
||||
purpose=purpose,
|
||||
install=install_id(),
|
||||
spawner_pid=spawner_pid,
|
||||
spawner_create=spawner_create,
|
||||
registered_at=time.time(),
|
||||
argv="",
|
||||
)
|
||||
assert _append_entry(entry)
|
||||
|
||||
def test_dead_spawner_serve_is_deferred_live(self, tmp_path, monkeypatch):
|
||||
"""A REAL serve-argv process, ledger-registered with a provably dead
|
||||
spawner, must classify as updater-owned (deferred, not a blocker)."""
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||||
|
||||
import psutil
|
||||
|
||||
# A real spawner that has already exited — its (pid, create_time)
|
||||
# pair is provably dead.
|
||||
spawner = subprocess.Popen(
|
||||
[sys.executable, "-c", "import time; time.sleep(0.1)"],
|
||||
)
|
||||
spawner_create = float(psutil.Process(spawner.pid).create_time())
|
||||
spawner.wait(timeout=30)
|
||||
|
||||
backend = _spawn(["-m", "hermes_cli.main", "serve", "--host", "127.0.0.1"])
|
||||
try:
|
||||
self._ledger_write(backend.pid, "serve", spawner.pid, spawner_create)
|
||||
|
||||
from hermes_cli._scan_venv_blockers import _is_updater_owned_backend
|
||||
|
||||
cmdline = " ".join(psutil.Process(backend.pid).cmdline())
|
||||
assert _is_updater_owned_backend(backend.pid, cmdline) is True, (
|
||||
"dead-spawner ledger serve must be deferred to the updater "
|
||||
"rungs (#98336)"
|
||||
)
|
||||
finally:
|
||||
_kill(backend)
|
||||
|
||||
def test_live_foreign_spawner_serve_still_blocks_live(self, tmp_path, monkeypatch):
|
||||
"""Same real serve process, but its recorded spawner is a LIVE
|
||||
process outside this scan's ancestry — must keep blocking."""
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||||
|
||||
import psutil
|
||||
|
||||
supervisor = _spawn(["fake-supervisor"])
|
||||
backend = _spawn(["-m", "hermes_cli.main", "serve", "--host", "127.0.0.1"])
|
||||
try:
|
||||
self._ledger_write(
|
||||
backend.pid,
|
||||
"serve",
|
||||
supervisor.pid,
|
||||
float(psutil.Process(supervisor.pid).create_time()),
|
||||
)
|
||||
|
||||
from hermes_cli._scan_venv_blockers import _is_updater_owned_backend
|
||||
|
||||
cmdline = " ".join(psutil.Process(backend.pid).cmdline())
|
||||
assert _is_updater_owned_backend(backend.pid, cmdline) is False, (
|
||||
"live foreign supervisor would respawn the backend — the "
|
||||
"scan must keep refusing"
|
||||
)
|
||||
finally:
|
||||
_kill(supervisor, backend)
|
||||
|
||||
def test_unregistered_serve_still_blocks_live(self, tmp_path, monkeypatch):
|
||||
"""A serve-argv process with NO ledger entry keeps blocking —
|
||||
positive identity only, never argv-shape alone."""
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||||
|
||||
import psutil
|
||||
|
||||
backend = _spawn(["-m", "hermes_cli.main", "serve", "--host", "127.0.0.1"])
|
||||
try:
|
||||
from hermes_cli._scan_venv_blockers import _is_updater_owned_backend
|
||||
|
||||
cmdline = " ".join(psutil.Process(backend.pid).cmdline())
|
||||
assert _is_updater_owned_backend(backend.pid, cmdline) is False
|
||||
finally:
|
||||
_kill(backend)
|
||||
|
||||
def test_handoff_desktop_ancestor_spawner_is_deferred_live(self, tmp_path, monkeypatch):
|
||||
"""The #98336 field topology: the recorded spawner is the scan's own
|
||||
ANCESTOR (the Desktop performing the hand-off). Run the check in a
|
||||
real child process whose parent chain contains the spawner."""
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||||
|
||||
import json as _json
|
||||
|
||||
import psutil
|
||||
|
||||
backend = _spawn(["-m", "hermes_cli.main", "serve", "--host", "127.0.0.1"])
|
||||
|
||||
check_file = tmp_path / "check_owned.py"
|
||||
check_file.write_text(
|
||||
"import json, sys\n"
|
||||
f"sys.path.insert(0, {str(PROJECT_ROOT)!r})\n"
|
||||
"import psutil\n"
|
||||
"from hermes_cli._scan_venv_blockers import _is_updater_owned_backend\n"
|
||||
"pid = int(sys.argv[1])\n"
|
||||
"cmdline = ' '.join(psutil.Process(pid).cmdline())\n"
|
||||
"print(json.dumps({'owned': _is_updater_owned_backend(pid, cmdline)}))\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
# Fake-desktop parent: registers the backend in the ledger with
|
||||
# ITSELF as spawner, then runs the check in a child — exactly the
|
||||
# Desktop → scan-subprocess topology of the update preflight.
|
||||
parent_file = tmp_path / "fake_desktop.py"
|
||||
parent_file.write_text(
|
||||
"import json, os, subprocess, sys, time\n"
|
||||
f"sys.path.insert(0, {str(PROJECT_ROOT)!r})\n"
|
||||
"import psutil\n"
|
||||
"from hermes_cli.process_identity import LedgerEntry, _append_entry, install_id\n"
|
||||
"backend_pid = int(sys.argv[1])\n"
|
||||
"entry = LedgerEntry(pid=backend_pid,\n"
|
||||
" create_time=float(psutil.Process(backend_pid).create_time()),\n"
|
||||
" purpose='serve', install=install_id(),\n"
|
||||
" spawner_pid=os.getpid(),\n"
|
||||
" spawner_create=float(psutil.Process().create_time()),\n"
|
||||
" registered_at=time.time(), argv='')\n"
|
||||
"assert _append_entry(entry)\n"
|
||||
f"r = subprocess.run([sys.executable, {str(check_file)!r}, sys.argv[1]],\n"
|
||||
f" capture_output=True, text=True, cwd={str(PROJECT_ROOT)!r})\n"
|
||||
"print(r.stdout.strip())\n"
|
||||
"sys.stderr.write(r.stderr[-500:])\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[sys.executable, str(parent_file), str(backend.pid)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
cwd=str(PROJECT_ROOT),
|
||||
timeout=120,
|
||||
env={**os.environ, "HERMES_HOME": str(tmp_path)},
|
||||
)
|
||||
line = result.stdout.strip().splitlines()[-1] if result.stdout.strip() else "{}"
|
||||
payload = _json.loads(line)
|
||||
assert payload.get("owned") is True, (
|
||||
"hand-off Desktop ancestor spawner must defer the backend "
|
||||
f"(#98336): stdout={result.stdout!r} stderr={result.stderr[-500:]!r}"
|
||||
)
|
||||
finally:
|
||||
_kill(backend)
|
||||
|
||||
Reference in New Issue
Block a user