Skip to content

The agent that grows with you

fix: an unreadable profile roster never admits a restart debt only one profile can see

Tekniumac57728a8cdc
diff --git a/hermes_cli/_update_takeover.py b/hermes_cli/_update_takeover.py
index 89e3f1b83e7..981e8ab9722 100644
--- a/hermes_cli/_update_takeover.py
+++ b/hermes_cli/_update_takeover.py
@@ -70,25 +70,14 @@ def _arm_fleet_obligation(root: Path) -> None:
``main`` would report any exception here as a failed update."""
# This runs in the HISTORICAL interpreter, before PM syncs the new dependencies: only stdlib-only
# modules here (``update_cmd_fleet``'s writer imports ``update_cmd`` -> config -> ruamel, which a
- # release older than ruamel does not have).
- from hermes_cli.update_host_obligation import write_host_obligation
+ # release older than ruamel does not have). Same arm and per-home fallback as the commit point's;
+ # its False (a debt other profiles cannot see) is already said out loud, and the tree has moved.
+ from hermes_cli.update_host_obligation import PROFILE_MARKER_NAME, arm_host_obligation
+ from hermes_constants import get_hermes_home
# A git-less archive root has no SHA: an SHA-less record still owes the restart; its readers hold
# the fleet to the checkout instead of a named pull.
- sha = _head_sha(root)
- if write_host_obligation(expected_sha=sha):
- return
- # Same fallback as ``update_cmd_fleet._write_fleet_restart_pending_marker``: the per-home
- # breadcrumb every reader still honours.
- from hermes_cli._early_recovery import write_durable_text
- from hermes_constants import get_hermes_home
-
- lines = [f"started={time.time()}", f"pid={os.getpid()}"] + ([f"expected_sha={sha}"] if sha else [])
- try:
- write_durable_text(get_hermes_home() / "fleet_restart_pending", "\n".join(lines) + "\n")
- except OSError as exc:
- print(f"Warning: could not record the owed gateway restart ({exc}); run `hermes update` again "
- "to restart the gateway onto the new code.", file=sys.stderr)
+ arm_host_obligation(get_hermes_home() / PROFILE_MARKER_NAME, expected_sha=_head_sha(root))
def _head_sha(root: Path) -> str:
diff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.py
index 61a9329cb4b..f67dd71e419 100644
--- a/hermes_cli/update_cmd_fleet.py
+++ b/hermes_cli/update_cmd_fleet.py
@@ -17,6 +17,7 @@ from dataclasses import dataclass, field
from pathlib import Path
from hermes_cli.update_cmd_common import _best_effort
+from hermes_cli.update_host_obligation import PROFILE_MARKER_NAME
from hermes_cli.update_inventory import _gateway_service_matches_profile
# Log-record parity with the origin module.
@@ -26,7 +27,7 @@ logger = logging.getLogger("hermes_cli.update_cmd")
# after a pull advanced HEAD; cleared only when the restart completes or nothing ran.
# The existing ``.update-incomplete`` / ``.lazy-refresh-incomplete`` markers gate dependency/venv repair;
# this one is the fleet-restart obligation after a git pull that advanced HEAD (#95294).
-_FLEET_RESTART_PENDING_NAME = "fleet_restart_pending"
+_FLEET_RESTART_PENDING_NAME = PROFILE_MARKER_NAME
_FRESH_RESTART_SUPERVISORS = frozenset({"systemd", "launchd", "service", "s6"})
@@ -60,39 +61,12 @@ def _fleet_restart_pending_marker_path() -> Path:
return get_hermes_home() / _FLEET_RESTART_PENDING_NAME
-def _write_legacy_fleet_restart_pending_marker(
- *, expected_sha: str = "", runtimes: list[dict] | None = None
-) -> bool:
- """Arm the LEGACY per-``HERMES_HOME`` marker. True when written. Never raises.
-
- Fallback only: ``$HERMES_HOME`` is writable by construction (the updater already writes its
- receipts there), so it still carries the obligation when the host state dir cannot.
- """
- path = _fleet_restart_pending_marker_path()
- try:
- lines = [f"started={_time.time()}", f"pid={os.getpid()}"]
- if expected_sha:
- lines.append(f"expected_sha={expected_sha}")
- if runtimes is not None:
- lines.append("inventory=" + json.dumps({"version": 1, "runtimes": runtimes}))
- path.write_text("\n".join(lines) + "\n", encoding="utf-8")
- return True
- except OSError as exc:
- logger.debug("Could not write legacy fleet-restart-pending marker: %s", exc)
- return False
-
-
def _write_fleet_restart_pending_marker(*, expected_sha: str = "", runtimes: list[dict] | None = None, owner: str = "") -> bool:
"""Arm the HOST pull→restart obligation. Never raises; False when no store every profile reads took it.
- An unwritable host state dir (``HERMES_GATEWAY_LOCK_DIR`` on a read-only mount, a container
- UID that does not own ``$HOME``) must never disarm the obligation: an update interrupted
- after this point would then leave stale code running with no warning and no catch-up restart
- (#117275). The legacy per-home marker — which every reader here still honours — carries it
- instead, and a host that can write neither says so out loud. That marker is visible to the
- invoking profile only, so it settles the debt only on an install with no other profile: with
- one, the other profiles would read "nothing owed", so the marker is still left for this
- profile but the arm returns False and the commit point refuses to move (review S2).
+ An unwritable host state dir falls back to this profile's per-home marker, which settles the
+ debt only on an install proven to have no other profile; otherwise the arm returns False and
+ the commit point refuses to move (``update_host_obligation.arm_host_obligation``, review S2).
"""
if runtimes == []:
# An explicit empty inventory owes no restart (e.g. Desktop-hosted `serve` with no
@@ -100,31 +74,12 @@ def _write_fleet_restart_pending_marker(*, expected_sha: str = "", runtimes: lis
# a no-gateway host would then fail every later ``hermes update`` (#115311).
return True
from hermes_cli.update_cmd import _m
- from hermes_cli.update_host_obligation import host_obligation_path, write_host_obligation
+ from hermes_cli.update_host_obligation import arm_host_obligation
if _m()._pytest_owns_live_checkout(_fleet_restart_pending_marker_path().parent):
logger.debug("Skipping fleet-restart-pending obligation under pytest (live checkout)")
return True
- if write_host_obligation(
- expected_sha=expected_sha, runtimes=runtimes, profile=_current_profile_name(), owner=owner):
- return True
- from hermes_cli.profiles import list_profile_names
- others = len(list_profile_names()) > 1
- if _write_legacy_fleet_restart_pending_marker(expected_sha=expected_sha, runtimes=runtimes) and not others:
- logger.warning(
- "Host update-restart obligation (%s) is unwritable; armed the per-home marker %s instead.",
- host_obligation_path(), _fleet_restart_pending_marker_path())
- return True
- logger.error(
- "Could not arm the update-restart obligation in %s%s; an interrupted update will not warn.",
- host_obligation_path(),
- " (this profile's marker hides it from the other profiles)" if others
- else f" or {_fleet_restart_pending_marker_path()}")
- print(
- " ⚠ Could not record the pending gateway-restart obligation (state dir not writable) — "
- "restart gateways with `hermes gateway restart` if this update is interrupted.",
- file=sys.stderr,
- )
- return False
+ return arm_host_obligation(_fleet_restart_pending_marker_path(), expected_sha=expected_sha, runtimes=runtimes,
+ profile=_current_profile_name(), owner=owner)
def _current_profile_name() -> str:
diff --git a/hermes_cli/update_host_obligation.py b/hermes_cli/update_host_obligation.py
index 8661af0bcf7..ed9b20b78a3 100644
--- a/hermes_cli/update_host_obligation.py
+++ b/hermes_cli/update_host_obligation.py
@@ -27,6 +27,8 @@ import hashlib
import json
import logging
import os
+import stat
+import sys
import tempfile
import time
from pathlib import Path
@@ -39,6 +41,9 @@ logger = logging.getLogger("hermes_cli.update_cmd")
#: the upgrade; it names no install, so it keeps its old meaning: owed by whichever install reads it.
HOST_OBLIGATION_NAME = "host-update-restart.json"
+#: The per-``HERMES_HOME`` breadcrumb an unwritable host record falls back to; every reader honours it.
+PROFILE_MARKER_NAME = "fleet_restart_pending"
+
_RECORD_VERSION = 1
@@ -125,6 +130,79 @@ def write_host_obligation(
return False
+def arm_host_obligation(
+ marker: Path, *, expected_sha: str = "", runtimes: Optional[list] = None, profile: str = "", owner: str = ""
+) -> bool:
+ """Arm the host record, else ``marker`` (the arming profile's per-home breadcrumb). Never raises.
+
+ The one fallback for every arm (``hermes update``'s commit point, a historical updater's
+ takeover). An unwritable host state dir (``HERMES_GATEWAY_LOCK_DIR`` on a read-only mount, a
+ container UID that does not own ``$HOME``) must never disarm the obligation (#117275), but the
+ marker is visible to the arming profile only: it settles the debt only on an install PROVEN to
+ have no other profile, and an unreadable profile roster proves nothing (review S2 residual).
+ Otherwise the marker is still left for this profile, the gap is said out loud, and the result
+ is False: the commit point refuses to move; a takeover, whose tree already moved, keeps the warning.
+ """
+ if write_host_obligation(expected_sha=expected_sha, runtimes=runtimes, profile=profile, owner=owner):
+ return True
+ lines = [f"started={time.time()}", f"pid={os.getpid()}"] + ([f"expected_sha={expected_sha}"] if expected_sha else [])
+ if runtimes is not None:
+ lines.append("inventory=" + json.dumps({"version": 1, "runtimes": runtimes}))
+ hidden = ""
+ try:
+ replace_bytes(marker, ("\n".join(lines) + "\n").encode("utf-8"))
+ except OSError as exc:
+ hidden = f" or {marker} ({exc})"
+ if not hidden:
+ try:
+ if _named_profiles_exist():
+ hidden = f" ({marker} hides it from the other profiles)"
+ except OSError as exc:
+ hidden = f" ({marker} may hide it from other profiles: the profile list is unreadable: {exc})"
+ if not hidden:
+ logger.warning("Host update-restart obligation (%s) is unwritable; armed the per-home marker %s instead.",
+ host_obligation_path(), marker)
+ return True
+ logger.error("Could not arm the update-restart obligation in %s%s; an interrupted update will not warn.",
+ host_obligation_path(), hidden)
+ # ASCII: a historical updater's takeover may print through a legacy console code page.
+ print(" Warning: could not record the pending gateway-restart obligation where every profile sees it "
+ "(state dir not writable) - restart gateways with `hermes gateway restart` if this update is "
+ "interrupted.", file=sys.stderr)
+ return False
+
+
+def _named_profiles_exist() -> bool:
+ """True when the install has a live named profile beside ``default``, read from a COMPLETE roster.
+
+ ``profiles.list_profile_names`` suppresses enumeration errors and reads an unreadable roster as
+ "default only"; here any error listing the roster or reading an entry's identity raises instead.
+ Same identity rule as ``hermes_constants.named_profile_is_live`` (stdlib only: see above).
+ """
+ from hermes_constants import _PROFILE_IDENTITY_MARKERS, PROFILE_ID_RE, get_default_hermes_root, profile_tombstone_path
+
+ try:
+ entries = list((get_default_hermes_root() / "profiles").iterdir())
+ except (FileNotFoundError, NotADirectoryError):
+ return False
+ for home in entries:
+ if home.name == "default" or not PROFILE_ID_RE.match(home.name) or not stat.S_ISDIR(_mode(home, os.stat)):
+ continue
+ identity = any((mode := _mode(home / name, os.lstat)) and not stat.S_ISDIR(mode)
+ for name in _PROFILE_IDENTITY_MARKERS)
+ if identity and not _mode(profile_tombstone_path(home), os.lstat):
+ return True
+ return False
+
+
+def _mode(path: Path, probe: Callable[[Path], os.stat_result]) -> int:
+ """``probe(path).st_mode``; 0 when absent. Any other error raises: unreadable is unknown, not absent."""
+ try:
+ return probe(path).st_mode
+ except (FileNotFoundError, NotADirectoryError):
+ return 0
+
+
def _write_locked(path: Path, *, expected_sha: str, runtimes: Optional[list], profile: str, owner: str) -> bool:
existing = _read_record(path)
try:
diff --git a/tests/hermes_cli/test_old_updater_takeover.py b/tests/hermes_cli/test_old_updater_takeover.py
index 460dd825609..2149e9ccd6d 100644
--- a/tests/hermes_cli/test_old_updater_takeover.py
+++ b/tests/hermes_cli/test_old_updater_takeover.py
@@ -603,6 +603,33 @@ def test_the_takeover_breadcrumb_is_written_temp_fsync_rename(tmp_path, monkeypa
assert f"expected_sha={'a' * 40}" in crumb.read_text(encoding="utf-8")
[email protected](getattr(os, "geteuid", lambda: 1)() == 0, reason="root ignores directory permissions")
+def test_a_takeover_debt_another_profile_cannot_see_is_never_silent(tmp_path, monkeypatch, capsys):
+ """The takeover arms after the historical updater already moved the tree, through the same
+ fallback as the commit point: with the host record unwritable on a two-profile install, the
+ arming profile's marker hides the debt from the other one, so the takeover must say so (it
+ cannot refuse a move that already happened) (kshitijk4poor P2, review S2)."""
+ from hermes_cli import _update_takeover
+
+ homes = {name: tmp_path / "profiles" / name for name in ("coder", "writer")}
+ for home in homes.values():
+ home.mkdir(parents=True)
+ (home / "config.yaml").write_text("{}\n", encoding="utf-8")
+ lock_dir = tmp_path / "gateway-locks"
+ lock_dir.mkdir()
+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(lock_dir))
+ monkeypatch.setenv("HERMES_HOME", str(homes["coder"]))
+ monkeypatch.setattr(_update_takeover, "_head_sha", lambda _root: "a" * 40)
+ lock_dir.chmod(0o500)
+ try:
+ _update_takeover._arm_fleet_obligation(tmp_path)
+ finally:
+ lock_dir.chmod(0o700)
+
+ assert (homes["coder"] / "fleet_restart_pending").is_file()
+ assert "hermes gateway restart" in capsys.readouterr().err
+
+
def test_a_historical_updater_arms_the_host_record_under_the_current_mutex(tmp_path, monkeypatch):
"""An N-1 updater imported ``update_lock`` before its pull, then lazily imports the pulled
``update_host_obligation``: the arm must still write the record, under the same sidecar lock
diff --git a/tests/hermes_cli/test_update_host_obligation.py b/tests/hermes_cli/test_update_host_obligation.py
index cd57c7dfc61..9a34518e262 100644
--- a/tests/hermes_cli/test_update_host_obligation.py
+++ b/tests/hermes_cli/test_update_host_obligation.py
@@ -299,6 +299,30 @@ def test_every_host_record_write_makes_its_rename_durable(tmp_path, monkeypatch)
assert events == ["file", "rename", "dir"] * 2
[email protected](getattr(os, "geteuid", lambda: 1)() == 0, reason="root ignores directory permissions")
[email protected]("unreadable", ["roster", "profile"])
+def test_an_unreadable_profile_roster_never_admits_a_private_restart_marker(
+ two_profiles, no_live_fleet, monkeypatch, tmp_path, unreadable):
+ """Host record unwritable AND the profile roster (or one profile's identity) unreadable: that is
+ an UNKNOWN inventory, not a single-profile install. The default profile's marker would hide the
+ debt from the profile nobody could read, so the arm refuses (review S2 residual)."""
+ (two_profiles["writer"] / "config.yaml").write_text("{}\n", encoding="utf-8") # the one named profile
+ _enter(monkeypatch, tmp_path) # the default profile arms
+ lock_dir = tmp_path / "gateway-locks"
+ lock_dir.mkdir(parents=True, exist_ok=True)
+ blind = tmp_path / "profiles" if unreadable == "roster" else two_profiles["writer"]
+ lock_dir.chmod(0o500)
+ blind.chmod(0o300 if unreadable == "roster" else 0o000) # roster: traversable, not listable
+ try:
+ armed = fleet._write_fleet_restart_pending_marker(expected_sha=SHA)
+ finally:
+ blind.chmod(0o700)
+ lock_dir.chmod(0o700)
+
+ assert armed is False
+ assert fleet._fleet_restart_pending_marker_path().is_file(), "the arming profile still keeps its marker"
+
+
def test_unreadable_host_record_is_never_discharged_by_the_legacy_marker(two_profiles, no_live_fleet, monkeypatch, tmp_path):
"""A record whose terms are UNKNOWN cannot be settled by another record's terms.