Skip to content

The agent that grows with you

fix(scratch): ancestry stamps read /proc stat as bytes and never fall back to wall clock

Teknium8c5a4f37f53f
diff --git a/hermes_constants_scratch.py b/hermes_constants_scratch.py
index 4a0f7ebeac0..ea9c11cd88e 100644
--- a/hermes_constants_scratch.py
+++ b/hermes_constants_scratch.py
@@ -166,27 +166,30 @@ def _under(path: str, root: str) -> bool:
# ``None``: the launcher could not compute it, so the pass signals nothing and keeps every entry
# a live process works in.
_launcher_lineage: frozenset[tuple[int, float]] | None = frozenset()
+_HAS_PROC = os.path.isdir("/proc/self")
def _birth_stamp(proc) -> float:
"""A start stamp for *proc* that a clock step cannot move. Linux: ``starttime`` from
``/proc/<pid>/stat`` (clock ticks since boot; psutil's ``create_time()`` adds a wall-clock
boot time, so an NTP/VM/resume step shifts it by whole seconds). Elsewhere:
- :func:`hermes_cli.process_identity.process_birth` (the unadjusted kernel start on macOS)."""
- try:
- # After the last ")" (comm may hold spaces) fields start at #3, so #22 is index 19.
- stat = Path(f"/proc/{proc.pid}/stat").read_text(encoding="utf-8") # windows-footgun: ok (/proc is BOM-free)
- return float(int(stat.rsplit(")", 1)[1].split()[19]))
- except (OSError, IndexError, ValueError):
- from hermes_cli.process_identity import process_birth
+ :func:`hermes_cli.process_identity.process_birth` (the unadjusted kernel start on macOS).
+ On a ``/proc`` host a failed read raises: falling back to a wall-clock value would compare
+ an epoch against recorded ticks and disown a live process."""
+ if _HAS_PROC:
+ # Bytes, not text: comm is cut at 15 bytes and can end mid-UTF-8 sequence. After the
+ # last ")" (comm may hold spaces or ")") fields start at #3, so #22 is index 19.
+ stat = Path(f"/proc/{proc.pid}/stat").read_bytes()
+ return float(int(stat.rsplit(b")", 1)[1].split()[19]))
+ from hermes_cli.process_identity import process_birth
- return process_birth(proc)
+ return process_birth(proc)
def _same_birth(proc, started: float) -> bool:
"""Exact on Linux (integer ticks); a 2 s tolerance where the stamp is a float epoch."""
now = _birth_stamp(proc)
- return now == started if os.path.exists(f"/proc/{proc.pid}/stat") else abs(now - started) < 2.0
+ return now == started if _HAS_PROC else abs(now - started) < 2.0
def lineage_with_start_times() -> list[tuple[int, float]] | None:
@@ -203,7 +206,7 @@ def lineage_with_start_times() -> list[tuple[int, float]] | None:
while proc is not None and proc.pid not in chain:
chain[proc.pid] = _birth_stamp(proc)
proc = proc.parent()
- except (psutil.Error, OSError):
+ except (psutil.Error, OSError, IndexError, ValueError):
return None
return list(chain.items())
@@ -225,9 +228,13 @@ def _own_lineage() -> set[int] | None:
except (psutil.Error, OSError):
pass
for pid, started in _launcher_lineage:
- with contextlib.suppress(psutil.Error, OSError):
+ try:
if _same_birth(psutil.Process(pid), started):
pids.add(pid)
+ except psutil.NoSuchProcess:
+ continue
+ except (psutil.Error, OSError, IndexError, ValueError):
+ pids.add(pid) # unreadable is not proof of a reused pid: spare it
return pids
diff --git a/tests/test_scratch_dir.py b/tests/test_scratch_dir.py
index d1d2701638e..c70b93cd327 100644
--- a/tests/test_scratch_dir.py
+++ b/tests/test_scratch_dir.py
@@ -92,6 +92,30 @@ def test_a_short_lived_process_still_completes_its_due_prune(tmp_path):
user_shell.wait(timeout=30)
[email protected]("linux") # /proc starttime and prctl(PR_SET_NAME)
+def test_launcher_ancestry_stamp_is_boot_relative_even_for_a_non_utf8_name(tmp_path):
+ """The ancestry stamp the detached pass compares is the kernel's start tick, never a
+ wall-clock birth that a clock step moves: a process whose name was cut mid-UTF-8 (comm is
+ 15 bytes) still gets its tick, and is recognised as itself. A wall-clock fallback there
+ disowned the user's shell after a clock step and the pass killed it."""
+ import hermes_constants_scratch as rules
+
+ ready = tmp_path / "ready"
+ child = subprocess.Popen([sys.executable, "-c", (
+ "import ctypes, sys, time; ctypes.CDLL(None).prctl(15, ctypes.c_char_p(bytes.fromhex(sys.argv[1])), 0, 0, 0); "
+ "open(sys.argv[2], 'w').close(); time.sleep(60)"), "c3a9" * 7 + "c3", str(ready)], stdin=subprocess.DEVNULL)
+ try:
+ wait_until(ready.exists, timeout=30, what="the child renaming itself")
+ stat = Path(f"/proc/{child.pid}/stat").read_bytes()
+ assert b"\xc3)" in stat # the name really is invalid UTF-8
+ stamp = rules._birth_stamp(psutil.Process(child.pid))
+ assert stamp == float(int(stat.rsplit(b")", 1)[1].split()[19]))
+ assert rules._same_birth(psutil.Process(child.pid), stamp)
+ finally:
+ child.kill()
+ child.wait(timeout=30)
+
+
def test_scratch_env_follows_home_and_respects_user_tmpdir(tmp_path):
"""Unset temp vars → scratch of env HERMES_HOME; a Hermes-exported value re-derives for a routed
home; a user/OS-set value (macOS ``/var/folders``, ``%TEMP%``) is never touched."""