Skip to content

The agent that grows with you

fix(update): let the Windows takeover child adopt its orchestrator's update marker

ethernet1524a30ec974
diff --git a/hermes_cli/_old_updater.py b/hermes_cli/_old_updater.py
index 0b2e8411f08..6b2b7f41878 100644
--- a/hermes_cli/_old_updater.py
+++ b/hermes_cli/_old_updater.py
@@ -89,6 +89,9 @@ def _run_child(request: dict) -> tuple[int, dict]:
if home:
env["HERMES_HOME"] = home
env.setdefault("HERMES_UPDATE_HANDOFF_PID", str(os.getpid()))
+ # Everything the user saw so far came from the OLD updater; say so before the
+ # new one (package manager) takes over, so logs show where the switch happened.
+ print("→ Handing off to the new updater (package manager) for the rest of this update...", flush=True)
with tempfile.TemporaryDirectory(prefix="hermes-update-takeover-") as directory:
context = Path(directory) / "request.json"
result = Path(directory) / "result.json"
diff --git a/hermes_cli/update_lock.py b/hermes_cli/update_lock.py
index e2e32d8c877..606d9e1d30c 100644
--- a/hermes_cli/update_lock.py
+++ b/hermes_cli/update_lock.py
@@ -11,6 +11,7 @@ from __future__ import annotations
import logging
import os
import subprocess
+import sys
import time
from contextlib import suppress
from dataclasses import dataclass
@@ -70,14 +71,86 @@ def _handoff_pid() -> int | None:
return pid if pid > 0 else None
+def _windows_parent_pid(pid: int) -> int | None:
+ """The parent of ``pid`` from a Toolhelp32 process snapshot (stdlib ctypes).
+
+ Windows keeps a dead parent's pid in the snapshot and reuses pids, so, like
+ psutil, a "parent" created after the child is a recycled pid, not our parent.
+ """
+ import ctypes
+ from ctypes import wintypes
+
+ class PROCESSENTRY32W(ctypes.Structure):
+ _fields_ = [
+ ("dwSize", wintypes.DWORD), ("cntUsage", wintypes.DWORD),
+ ("th32ProcessID", wintypes.DWORD), ("th32DefaultHeapID", ctypes.c_size_t),
+ ("th32ModuleID", wintypes.DWORD), ("cntThreads", wintypes.DWORD),
+ ("th32ParentProcessID", wintypes.DWORD), ("pcPriClassBase", ctypes.c_long),
+ ("dwFlags", wintypes.DWORD), ("szExeFile", ctypes.c_wchar * 260),
+ ]
+
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ kernel32.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
+ kernel32.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
+ for walk in (kernel32.Process32FirstW, kernel32.Process32NextW):
+ walk.argtypes = [wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32W)]
+ walk.restype = wintypes.BOOL
+ kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
+ kernel32.OpenProcess.restype = wintypes.HANDLE
+ kernel32.GetProcessTimes.argtypes = [wintypes.HANDLE] + [ctypes.POINTER(wintypes.FILETIME)] * 4
+ kernel32.GetProcessTimes.restype = wintypes.BOOL
+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
+ kernel32.CloseHandle.restype = wintypes.BOOL
+
+ def created(target: int) -> int | None:
+ handle = kernel32.OpenProcess(0x1000, False, target) # PROCESS_QUERY_LIMITED_INFORMATION
+ if not handle:
+ return None
+ try:
+ times = [wintypes.FILETIME() for _ in range(4)]
+ if not kernel32.GetProcessTimes(handle, *(ctypes.byref(t) for t in times)):
+ return None
+ return (times[0].dwHighDateTime << 32) | times[0].dwLowDateTime
+ finally:
+ kernel32.CloseHandle(handle)
+
+ snapshot = kernel32.CreateToolhelp32Snapshot(0x2, 0) # TH32CS_SNAPPROCESS
+ if not snapshot or snapshot == ctypes.c_void_p(-1).value:
+ return None
+ parent = None
+ try:
+ entry = PROCESSENTRY32W()
+ entry.dwSize = ctypes.sizeof(PROCESSENTRY32W)
+ found = kernel32.Process32FirstW(snapshot, ctypes.byref(entry))
+ while found:
+ if entry.th32ProcessID == pid:
+ parent = int(entry.th32ParentProcessID)
+ break
+ found = kernel32.Process32NextW(snapshot, ctypes.byref(entry))
+ finally:
+ kernel32.CloseHandle(snapshot)
+ if not parent:
+ return None
+ parent_created, child_created = created(parent), created(pid)
+ if parent_created is not None and child_created is not None and parent_created > child_created:
+ return None
+ return parent
+
+
def _stdlib_parent_pid(pid: int) -> int | None:
"""The parent of ``pid`` without psutil, or ``None`` when unresolvable.
The update-takeover child is spawned ``-I -S -B`` (hermes_cli/_old_updater.py) so
psutil cannot import there — and that grandchild is exactly the process that most
needs the two-hop ancestry walk to adopt the orchestrator's marker. /proc serves
- Linux; macOS keeps /proc absent, so shell out to ps once per hop.
+ Linux; macOS keeps /proc absent, so shell out to ps once per hop; Windows has
+ neither, so ask the Toolhelp32 snapshot.
"""
+ if sys.platform == "win32":
+ try:
+ return _windows_parent_pid(pid)
+ except (OSError, AttributeError, ValueError):
+ return None
try:
if os.path.isdir("/proc"):
with open(f"/proc/{pid}/stat", "rb") as fh:
diff --git a/tests/hermes_cli/test_update_lock.py b/tests/hermes_cli/test_update_lock.py
index 6b47a617c06..bff1e4f2b8c 100644
--- a/tests/hermes_cli/test_update_lock.py
+++ b/tests/hermes_cli/test_update_lock.py
@@ -257,6 +257,7 @@ class TestAncestryHandoff:
lock.release()
assert marker.exists(), "the parent still needs its marker after our stage ends"
+ @pytest.mark.platforms("any")
def test_grandchild_adopts_orchestrator_marker_without_psutil(self, marker, tmp_path):
"""Regression: the desktop hand-off's grandchild refused its own orchestrator.
@@ -267,8 +268,10 @@ class TestAncestryHandoff:
(-S skips site-packages). The psutil-only ancestry walk returned False for
the two-hops-up shim, and the takeover child refused with exit 2 —
"Another Hermes update is already running (PID <the shim itself>)" —
- observed live on a macOS rehearsal install. The stdlib fallback walk is
- what must adopt here.
+ observed live on a macOS rehearsal install, then again on Windows, where
+ the stdlib walk had no /proc and no ps. Marked for every lane: the Windows
+ lane only imports files carrying a platforms marker, which is how the
+ Windows half went unseen. The stdlib fallback walk is what must adopt here.
"""
import subprocess
import sys
@@ -310,6 +313,7 @@ class TestAncestryHandoff:
assert "ADOPTED" in result.stdout
assert marker.exists(), "the orchestrator still needs its marker after the leaf ends"
+ @pytest.mark.platforms("any")
def test_unrelated_live_holder_is_still_refused_under_stdlib_walk(self, marker, tmp_path):
"""The stdlib fallback must not widen the lock: a foreign pid stays foreign.