Skip to content

The agent that grows with you

fix(update-windows): cold-start every dead-but-attested profile, not only when nothing runs

kshitijk4poorc8686224d307
diff --git a/hermes_cli/gateway_windows.py b/hermes_cli/gateway_windows.py
index 5d11faa04ac..b54d87a085d 100644
--- a/hermes_cli/gateway_windows.py
+++ b/hermes_cli/gateway_windows.py
@@ -284,11 +284,12 @@ def _gateway_run_argv(python_exe: str, profile_arg: str) -> list[str]:
return argv
-def _launcher_settings() -> tuple[str, str, str, str]:
- """Return (python_path, working_dir, hermes_home, profile_arg) for generated launchers."""
+def _launcher_settings(home: Path | None = None) -> tuple[str, str, str, str]:
+ """Return (python_path, working_dir, hermes_home, profile_arg) for generated launchers.
+ ``home`` targets another profile's HERMES_HOME (per-profile cold-start, #110959)."""
from hermes_cli.gateway import PROJECT_ROOT, _profile_arg, get_python_path # avoid circular init
- hermes_home = str(_hermes_home())
+ hermes_home = str(home if home is not None else _hermes_home())
return (
_preserve_hermes_home_path(get_python_path()),
_stable_gateway_working_dir(PROJECT_ROOT),
@@ -573,13 +574,13 @@ def _prepend_pythonpath(env_overlay: dict[str, str], entries: list[str]) -> None
env_overlay["PYTHONPATH"] = os.pathsep.join(clean_entries)
-def _build_gateway_argv() -> tuple[list[str], str, dict[str, str]]:
+def _build_gateway_argv(home: Path | None = None) -> tuple[list[str], str, dict[str, str]]:
"""Build (argv, working_dir, env_overlay) for the gateway subprocess — the same logical command
as gateway.cmd, assembled as a native argv so no cmd.exe layer sits in between."""
_assert_windows()
from hermes_cli.gateway import PROJECT_ROOT
- python_path, working_dir, hermes_home, profile_arg = _launcher_settings()
+ python_path, working_dir, hermes_home, profile_arg = _launcher_settings(home)
python_exe, venv_dir, extra_pythonpath = _resolve_detached_python(python_path)
env_overlay = {"HERMES_HOME": hermes_home, **dict(_GATEWAY_ENV), "VIRTUAL_ENV": _preserve_hermes_home_path(venv_dir)}
_prepend_pythonpath(env_overlay, [_preserve_hermes_home_path(p) for p in (PROJECT_ROOT, *extra_pythonpath)])
@@ -618,9 +619,9 @@ def windowless_gateway_restart_spec(run_argv: list[str]) -> tuple[list[str], str
return [hidden_console_python, *run_argv[1:]], _stable_gateway_working_dir(PROJECT_ROOT), env_overlay
-def _spawn_detached(script_path: Path | None = None) -> int:
+def _spawn_detached(script_path: Path | None = None, home: Path | None = None) -> int:
"""Launch the gateway as a fully detached background process (``script_path`` is ignored; kept
- for API symmetry). Spawns python.exe directly — a cmd.exe shim inherits the parent console and
+ for API symmetry; ``home`` spawns another profile's gateway — ``--profile`` is derived from it). Spawns python.exe directly — a cmd.exe shim inherits the parent console and
gets reaped when the shell exits. Flags: CREATE_NEW_PROCESS_GROUP (no Ctrl+C from our group),
CREATE_NO_WINDOW (hidden console descendants inherit, so nothing flashes — #54220/#56747; the old
DETACHED_PROCESS made every descendant spawn flash), CREATE_BREAKAWAY_FROM_JOB
@@ -633,7 +634,7 @@ def _spawn_detached(script_path: Path | None = None) -> int:
process is independent of whichever shell started it.
"""
_assert_windows()
- argv, working_dir, env_overlay = _build_gateway_argv()
+ argv, working_dir, env_overlay = _build_gateway_argv(home)
env = {**os.environ, **env_overlay}
# Stray print()/native stderr goes to a sidecar log; real gateway logs still land in gateway.log
@@ -866,8 +867,9 @@ def _wait_for_gateway_ready(
_START_ATTESTATION_RELATIVE = ("state", "gateway.start-attestation.json")
-def _start_attestation_path() -> Path:
- return _hermes_home().joinpath(*_START_ATTESTATION_RELATIVE)
+def _start_attestation_path(home: Path | None = None) -> Path:
+ """Marker path; ``home`` addresses another profile's marker (per-profile cold-start, #110959)."""
+ return (home if home is not None else _hermes_home()).joinpath(*_START_ATTESTATION_RELATIVE)
def _write_start_attestation(pids: list[int], via: str) -> None:
@@ -896,9 +898,9 @@ def _write_start_attestation(pids: list[int], via: str) -> None:
logger.debug("Failed to write gateway start attestation", exc_info=True)
-def _clear_start_attestation() -> None:
+def _clear_start_attestation(home: Path | None = None) -> None:
try:
- _start_attestation_path().unlink(missing_ok=True)
+ _start_attestation_path(home).unlink(missing_ok=True)
except OSError:
pass
@@ -932,18 +934,18 @@ def _attestation_generation(data: object) -> str | None:
return str(data["generation"]) if isinstance(data, dict) and data.get("generation") else None
-def _consume_start_attestation(generation: str) -> None:
+def _consume_start_attestation(generation: str, home: Path | None = None) -> None:
"""Clear the marker only while it is still the ``generation`` that was acted on; a newer
marker belongs to a gateway start this caller knows nothing about and keeps its own report."""
# Best-effort read-then-unlink: a marker written in between loses one post-start report, never authority.
- if _attestation_generation(_read_start_attestation()) == generation:
- _clear_start_attestation()
+ if _attestation_generation(_read_start_attestation(home)) == generation:
+ _clear_start_attestation(home)
-def _read_start_attestation() -> object | None:
+def _read_start_attestation(home: Path | None = None) -> object | None:
"""Parsed attestation payload (any JSON type), or ``None`` when absent/unreadable. Never raises."""
try:
- return json.loads(_start_attestation_path().read_text(encoding="utf-8"))
+ return json.loads(_start_attestation_path(home).read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
@@ -968,7 +970,7 @@ def _attested_create_time(data: object, pid: int) -> float | None:
return float(value) if type(value) in (int, float) else None
-def _attested_pid_exited_cleanly(pid: int, create_time: float | None = None) -> bool:
+def _attested_pid_exited_cleanly(pid: int, create_time: float | None = None, home: Path | None = None) -> bool:
"""True when the lifecycle ledger shows a clean exit for ``pid`` — or, for a marker that bound
``pid`` to a ``create_time``, whenever the sentinel cannot be shown to describe THAT incarnation
(#110020 review): a sentinel for another PID or another start time means an unrelated lifecycle
@@ -977,7 +979,8 @@ def _attested_pid_exited_cleanly(pid: int, create_time: float | None = None) ->
try:
from gateway.lifecycle_ledger import get_lifecycle_sentinel_path
- data = json.loads(get_lifecycle_sentinel_path(_hermes_home()).read_text(encoding="utf-8"))
+ sentinel = get_lifecycle_sentinel_path(home if home is not None else _hermes_home())
+ data = json.loads(sentinel.read_text(encoding="utf-8"))
except OSError:
return False
except Exception:
@@ -994,15 +997,17 @@ def _attested_pid_exited_cleanly(pid: int, create_time: float | None = None) ->
return data.get("phase") == "exited" and data.get("pid") == pid
-def _attested_dead(attested: list[int], current_pids: list[int], data: object = None) -> bool:
+def _attested_dead(
+ attested: list[int], current_pids: list[int], data: object = None, home: Path | None = None
+) -> bool:
"""The liveness rule shared by the consuming and read-only probes: attested PIDs are dead when
no gateway runs now and the lifecycle ledger shows no clean exit for any of them."""
return not current_pids and not any(
- _attested_pid_exited_cleanly(pid, _attested_create_time(data, pid)) for pid in attested
+ _attested_pid_exited_cleanly(pid, _attested_create_time(data, pid), home) for pid in attested
)
-def attested_death_generation(current_pids: list[int]) -> str | None:
+def attested_death_generation(current_pids: list[int], home: Path | None = None) -> str | None:
"""The generation of a start attestation that vouches for gateway PID(s) gone without a clean exit,
or ``None``.
@@ -1012,10 +1017,11 @@ def attested_death_generation(current_pids: list[int]) -> str | None:
execution step consumes exactly the marker it was authorized by. Callers pass the liveness they
already established (``[]`` after their own discovery came back empty) so the process table is
not scanned twice. ``None`` for anything undecidable (no marker, no generation, a clean ledger
- exit): "unknown" must never read as "dead"."""
- data = _read_start_attestation()
+ exit): "unknown" must never read as "dead". ``home`` probes another profile's marker and ledger
+ (the updater evaluates every profile that is not running, #110959)."""
+ data = _read_start_attestation(home)
attested = _attested_pids_from(data)
- if not attested or not _attestation_within_horizon(data) or not _attested_dead(attested, current_pids, data):
+ if not attested or not _attestation_within_horizon(data) or not _attested_dead(attested, current_pids, data, home):
return None
return _attestation_generation(data)
diff --git a/hermes_cli/update_cmd_windows.py b/hermes_cli/update_cmd_windows.py
index d1c190a404f..4f6c0e216d2 100644
--- a/hermes_cli/update_cmd_windows.py
+++ b/hermes_cli/update_cmd_windows.py
@@ -886,7 +886,10 @@ def _pause_windows_gateways_for_update() -> dict | None:
from hermes_cli.gateway import _capture_gateway_argv
profile_processes, service_gateways, service_gateway_pids, running_pids = _discover_windows_gateways()
if not running_pids:
- return _windows_cold_start_plan()
+ token = _windows_cold_start_plan()
+ if token is not None:
+ _record_attested_cold_start_profiles(token, set())
+ return token
profiles, mapped_pids, socket_acks = _request_socket_pauses(running_pids, profile_processes, service_gateway_pids)
# Resolve venv-side launchers BEFORE draining: a dead worker's parent cannot be recovered (NoSuchProcess).
# The launcher keeps ``.pyd`` mapped and would trip the venv-holder guard; it is killed with the survivors.
@@ -918,9 +921,60 @@ def _pause_windows_gateways_for_update() -> dict | None:
if any(not u.get("argv") for u in unmapped): # no recoverable cmdline (psutil missing, denied, gone)
print(" Restart manually after update: hermes gateway run")
token = {"resume_needed": True, "profiles": profiles, "unmapped_pids": unmapped_pids, "unmapped": unmapped}
+ _record_attested_cold_start_profiles(token, set(profiles))
return _pause_windows_gateway_services(service_gateways, token, profiles, unmapped)
+def _record_attested_cold_start_profiles(token: dict, running_profiles: set) -> None:
+ """Record ``token["cold_start_profiles"] = {name: generation}`` for every known profile that is not
+ running yet holds a start attestation for a gateway that died without a clean exit (#110959).
+
+ The all-or-nothing plan only ever probed the ACTIVE profile and only when NO gateway ran at all, so a
+ dead-but-attested default beside a still-running ``beta`` never got a cold-start obligation. Only
+ Desktop-owned installs need this (elsewhere autostart brings the profile back); the active profile is
+ left to the existing plan so it is never spawned twice. Best-effort: never blocks the pause."""
+ from hermes_cli.update_cmd import _desktop_owns_gateway_lifecycle
+ from hermes_cli import gateway_windows
+ with _best_effort("Could not evaluate per-profile attested cold-starts before update: %s"):
+ if not _desktop_owns_gateway_lifecycle():
+ return
+ from hermes_cli.profiles import get_active_profile_name, profiles_to_serve
+ active = get_active_profile_name() or "default"
+ cold: dict[str, str] = {}
+ for name, home in profiles_to_serve(multiplex=True):
+ if name in running_profiles or (name == active and token.get("cold_start_if_installed")):
+ continue
+ generation = gateway_windows.attested_death_generation([], home=Path(home))
+ if generation:
+ cold[name] = generation
+ if cold:
+ token["cold_start_profiles"] = cold
+
+
+def _cold_start_attested_profiles(token: dict) -> None:
+ """Spawn each ``cold_start_profiles`` entry under its own HERMES_HOME and consume exactly the
+ generation that authorized it; one profile's failure never aborts the others (#110959)."""
+ from hermes_cli import gateway_windows
+ from hermes_cli.profiles import get_profile_dir
+ pending = dict(token.get("cold_start_profiles") or {})
+ if not pending:
+ return
+ for name, generation in sorted(pending.items()):
+ home = Path(get_profile_dir(name))
+ with _best_effort(f"Could not cold-start Windows gateway profile {name} after update: %s"):
+ pid = gateway_windows._spawn_detached(home=home)
+ if not pid:
+ raise RuntimeError("cold-start did not return a process ID")
+ ready_pids = gateway_windows._wait_for_gateway_ready(all_profiles=True)
+ if not ready_pids:
+ raise RuntimeError(f"PID {pid} did not become ready")
+ gateway_windows._consume_start_attestation(generation, home=home)
+ print(f"\n✓ Gateway profile {name} started via cold-start after update (PID: {pid})")
+ token["cold_start_profiles"].pop(name, None)
+ if not token["cold_start_profiles"]:
+ token.pop("cold_start_profiles", None)
+
+
def _cold_start_windows_gateway_after_update(token: dict | None = None) -> bool:
"""Direct-spawn a detached gateway after update for the ``cold_start_if_installed`` case (installed but down).
@@ -1149,6 +1203,7 @@ def _resume_windows_gateways_after_update(token: dict | None) -> None:
# autostart entry comes back on the current design at next login too.
_m()._refresh_windows_gateway_launchers()
_resume_windows_services(token)
+ _cold_start_attested_profiles(token)
profiles = token.get("profiles") or {}
unmapped = token.get("unmapped") or []
if not profiles and not any(u.get("argv") for u in unmapped):
diff --git a/tests/hermes_cli/test_windows_gateway_cold_start_desktop_lifecycle.py b/tests/hermes_cli/test_windows_gateway_cold_start_desktop_lifecycle.py
index db1ff57dcb7..55696c5d35e 100644
--- a/tests/hermes_cli/test_windows_gateway_cold_start_desktop_lifecycle.py
+++ b/tests/hermes_cli/test_windows_gateway_cold_start_desktop_lifecycle.py
@@ -233,3 +233,75 @@ def test_cold_start_is_authorized_by_the_token_generation_not_the_mutable_marker
assert update_cmd._cold_start_windows_gateway_after_update(token) is True
assert spawned == [1] # authorized by the token, not by the (consumed) marker
assert json.loads(marker.read_text(encoding="utf-8"))["generation"] == newer # not ours to consume
+
+
+def _running_beta_pause_fixture(monkeypatch, tmp_path):
+ """Windows update with ``beta`` (PID 777) running and the default profile home at ``tmp_path``."""
+ from types import SimpleNamespace
+ import hermes_cli.profiles as profiles_mod
+
+ homes = {"default": tmp_path, "beta": tmp_path / "profiles" / "beta"}
+ homes["beta"].mkdir(parents=True)
+ monkeypatch.setattr("hermes_cli.config.get_hermes_home", lambda: str(tmp_path))
+ monkeypatch.setattr(cli_main, "_is_windows", lambda: True)
+ monkeypatch.setattr(main_install_repair, "_is_windows", lambda: True)
+ monkeypatch.setattr(update_cmd, "_desktop_owns_gateway_lifecycle", lambda: True)
+ monkeypatch.setattr(update_cmd_windows, "_desktop_owns_gateway_lifecycle", lambda: True)
+ beta = SimpleNamespace(pid=777, profile="beta")
+ monkeypatch.setattr(update_cmd_windows, "_discover_windows_gateways", lambda: ({777: beta}, [], set(), [777]))
+ monkeypatch.setattr(update_cmd_windows, "_request_socket_pauses", lambda *a: ({"beta": 777}, [777], []))
+ monkeypatch.setattr(cli_main, "_venv_launcher_ancestors", lambda pids: [])
+ monkeypatch.setattr(cli_main, "_wait_for_windows_update_gateway_exit", lambda pids, timeout: set())
+ monkeypatch.setattr(profiles_mod, "get_active_profile_name", lambda: "default")
+ monkeypatch.setattr(profiles_mod, "profiles_to_serve", lambda multiplex: list(homes.items()))
+ monkeypatch.setattr(profiles_mod, "get_profile_dir", lambda name: homes[name])
+ # Resume side.
+ monkeypatch.setattr(cli_main, "_refresh_windows_gateway_launchers", lambda: None)
+ monkeypatch.setattr(hermes_gateway, "launch_detached_profile_gateway_restart", lambda p, o: True)
+ monkeypatch.setattr(gateway_windows, "_wait_for_gateway_ready", lambda *a, **k: [4242])
+ return homes
+
+
+def test_dead_attested_default_is_cold_started_beside_running_beta(monkeypatch, tmp_path, capsys):
+ """#110959: the all-or-nothing plan never ran while ``beta`` was alive, so a default gateway
+ that died after a ✓ stayed down after the update. Its dead attestation must become a per-profile
+ cold-start obligation on the token; resume spawns it under the default home and consumes only
+ that generation, while ``beta`` still goes through the ordinary relaunch."""
+ homes = _running_beta_pause_fixture(monkeypatch, tmp_path)
+ gateway_windows._write_start_attestation([555], "direct spawn (PID 555)")
+ marker = tmp_path / "state" / "gateway.start-attestation.json"
+ generation = json.loads(marker.read_text(encoding="utf-8"))["generation"]
+
+ token = update_cmd._pause_windows_gateways_for_update()
+
+ assert token["profiles"] == {"beta": 777}
+ assert token["cold_start_profiles"] == {"default": generation}
+ assert marker.exists() # plan-time probe is read-only
+
+ spawned = []
+ monkeypatch.setattr(gateway_windows, "_spawn_detached", lambda **k: spawned.append(k) or 4242)
+ monkeypatch.setattr(gateway_windows, "_write_start_attestation", lambda *a, **k: None)
+ update_cmd._resume_windows_gateways_after_update(token)
+
+ assert spawned == [{"home": homes["default"]}]
+ assert not marker.exists() # consumed with the default profile's home
+ assert "cold_start_profiles" not in token
+ assert token["relaunched_profiles"] == ["beta"]
+ assert token["resume_needed"] is False
+ out = capsys.readouterr().out
+ assert "Gateway profile default started via cold-start after update (PID: 4242)" in out
+
+
+def test_no_attested_profile_leaves_the_pause_token_unchanged(monkeypatch, tmp_path):
+ _running_beta_pause_fixture(monkeypatch, tmp_path)
+
+ token = update_cmd._pause_windows_gateways_for_update()
+
+ assert "cold_start_profiles" not in token
+ assert token["profiles"] == {"beta": 777}
+ spawned = []
+ monkeypatch.setattr(gateway_windows, "_spawn_detached", lambda **k: spawned.append(k) or 4242)
+ monkeypatch.setattr(gateway_windows, "_write_start_attestation", lambda *a, **k: None)
+ update_cmd._resume_windows_gateways_after_update(token)
+ assert spawned == []
+ assert token["relaunched_profiles"] == ["beta"]