fix(process-identity): old-format ledger entries keep main's epoch match

Review round 2 on #144757 (finding: old entries protect a reused pid):
entries without boot ticks (written before upgrade, or where boot_id is
unreadable) got clock-step leniency through entry_still_running's
keep_unprovable path, so a serve entry whose pid a live unrelated process
had reused was never pruned by _append_entry, and
data_cleanup_holders._refuse_backend_writers refused cleanup until that
stranger exited; main proceeds and prunes the row.

Clock-step immunity now comes only from boot ticks recorded in the running
boot. Removed keep_unprovable and _step_can_explain_mismatch, including the
spawner_is_dead leniency (an epoch-only spawner whose pid a stranger holds
now reads as dead, as on main, so its orphaned MCP helper is reaped).
Old-format entries keep main's epoch match until their processes restart
and rewrite them.
This commit is contained in:
Teknium
2026-10-25 19:05:46 -07:00
parent 6c3f8a2542
commit 00540458b7
4 changed files with 15 additions and 35 deletions

View File

@@ -85,7 +85,7 @@ def _refuse_backend_writers(home: Path) -> None:
pid = row.get("pid")
if type(pid) is not int or pid <= 0:
raise RuntimeError("backend ownership contains an invalid PID")
if entry_still_running(row, keep_unprovable=True):
if entry_still_running(row):
raise RuntimeError(f"backend PID {pid} still owns {home}; close its desktop/dashboard before retrying")

View File

@@ -168,20 +168,6 @@ def _verified_boot_start(pid: Optional[int], create_time: Optional[float]) -> Op
return None
def _step_can_explain_mismatch(pid: int, boot: Optional[float]) -> bool:
"""A running ``pid`` failed an epoch-only match on Linux: a clock step explains that as well as
a reused pid, so the mismatch proves nothing. ``False`` when ``boot`` gave an exact verdict and
when ``pid`` is gone or a zombie (exited, only awaiting its parent's reap)."""
import psutil # the caller's epoch match already needed it
if boot is not None or not getattr(psutil, "LINUX", False):
return False
try:
return psutil.Process(pid).status() != psutil.STATUS_ZOMBIE
except psutil.Error:
return False
# Layer 1 — spawn tags
@@ -458,7 +444,7 @@ def _append_entry(entry: LedgerEntry) -> bool:
e for e in entries
if isinstance(e.get("pid"), int)
and e["pid"] != entry.pid
and entry_still_running(e, keep_unprovable=True)
and entry_still_running(e)
]
pruned.append(asdict(entry))
try:
@@ -526,18 +512,14 @@ def ledger_entries(
]
def entry_still_running(entry: dict, *, keep_unprovable: bool = False) -> bool:
def entry_still_running(entry: dict) -> bool:
"""Is the ledger *entry*'s process still the recorded incarnation (``None`` from psutil
counts as running)? ``keep_unprovable``: an older entry with only an epoch birth whose live
pid disagrees on Linux also counts, because a clock step explains that as well as pid reuse.
Readers that protect a process (ledger pruning, the scratch prune's owner check) pass it;
killers never do."""
pid, boot = entry.get("pid"), _entry_boot(entry, "boot_start")
counts as running)? Exact boot ticks within their boot survive a clock step; an entry
without them keeps the 2 s epoch match, so a step reads it as a reused pid."""
pid = entry.get("pid")
if not isinstance(pid, int) or pid <= 0:
return False
if _pid_alive_matches(pid, entry.get("create_time"), boot=boot) is not False:
return True
return keep_unprovable and _step_can_explain_mismatch(pid, boot)
return _pid_alive_matches(pid, entry.get("create_time"), boot=_entry_boot(entry, "boot_start")) is not False
def spawner_is_dead(entry: dict) -> Optional[bool]:
@@ -548,10 +530,6 @@ def spawner_is_dead(entry: dict) -> Optional[bool]:
# A spawner recorded in an earlier boot is dead (:func:`_entry_boot`), as the epoch match says.
boot = _entry_boot(entry, "spawner_boot")
alive = _pid_alive_matches(spawner_pid, entry.get("spawner_create"), boot=boot)
# An entry that survives a clock step (``boot_start``) with an epoch-only spawner: a step
# would read its live spawner as dead and let a reaper kill the child.
if alive is False and _entry_boot(entry, "boot_start") is not None and _step_can_explain_mismatch(spawner_pid, boot):
return None
return None if alive is None else not alive

View File

@@ -268,9 +268,7 @@ def _registered_live_pids(home: Path) -> set[int]:
continue
try:
if stamp_key == "create_time":
# Boot-relative when recorded; an older epoch-only entry that a clock step
# could have shifted stays owned rather than getting its tree killed.
alive = entry_still_running(entry, keep_unprovable=True)
alive = entry_still_running(entry) # boot ticks survive a clock step
elif stamp is None:
alive = psutil.pid_exists(pid)
else:

View File

@@ -63,9 +63,10 @@ def test_ledger_never_vouches_for_an_earlier_boot_or_an_exited_backend(tmp_path,
"""The ledger survives reboots but boot ticks restart: an MCP-helper entry written in an
earlier boot whose pid and start tick equal an unrelated process running now (early-boot
services are deterministic) names a stranger, and its spawner is gone, so the orphan reaper
must leave the stranger alone. An older epoch-only serve entry whose backend has exited (a
zombie its parent has not reaped yet) no longer owns HERMES_HOME. Neither row survives the
next ledger write."""
must leave the stranger alone. Older epoch-only serve entries (written before boot ticks) keep
main's epoch match: one whose backend has exited (a zombie its parent has not reaped yet) and
one whose pid the stranger now holds no longer own HERMES_HOME. No row survives the next
ledger write."""
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
stranger = subprocess.Popen(["sleep", "60"], stdin=subprocess.DEVNULL)
backend = subprocess.Popen(["true"], stdin=subprocess.DEVNULL)
@@ -84,6 +85,9 @@ def test_ledger_never_vouches_for_an_earlier_boot_or_an_exited_backend(tmp_path,
{"pid": backend.pid, "create_time": psutil.Process(backend.pid).create_time(), "purpose": "serve",
"install": install_id(), "spawner_pid": None, "spawner_create": None,
"registered_at": time.time(), "argv": ""},
{"pid": stranger.pid, "create_time": live.create_time() - 3 * 86400, "purpose": "serve",
"install": install_id(), "spawner_pid": None, "spawner_create": None,
"registered_at": earlier_boot, "argv": ""},
]), encoding="utf-8")
assert stranger.pid not in [e["pid"] for e in ledger_entries()]