Skip to content

The agent that grows with you

gateway: converge on multiplex-only — real migrate, no opt-out, no rollback, host lock refuses

teknium1ed703493da63
diff --git a/gateway/run.py b/gateway/run.py
index a09364ef788..e28ec54c318 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -1697,12 +1697,12 @@ def _cron_tick_profile_homes(config: object) -> list[tuple[str, "Path"]]:
def _cron_profile_gate(name: str, home: "Path") -> bool:
"""Tick ``home`` this cycle unless ANOTHER gateway process owns it.
- Same stand-down the serve/Desktop ticker applies (``hermes_cli/web_server.py``): a host
- deliberately pinned to per-profile gateways (``gateway.multiplex_profiles: false``, the s6
- per-profile services in ``container_boot.reconcile_profile_gateways``) runs profile B's own
- gateway, and without this both it and this process race B's ``cron/.tick.lock``. The lock
- stops a simultaneous double-run but not the race: when this process wins, B's delivery leaves
- through ``SharedRouteAdapters``/fail-closed instead of B's live adapters.
+ Same stand-down the serve/Desktop ticker applies (``hermes_cli/web_server.py``): a host that
+ has not finished converging onto the one host gateway (``hermes gateway migrate --multiplex``)
+ may still run profile B's own gateway, and without this both it and this process race B's
+ ``cron/.tick.lock``. The lock stops a simultaneous double-run but not the race: when this
+ process wins, B's delivery leaves through ``SharedRouteAdapters``/fail-closed instead of B's
+ live adapters.
The liveness answer is compared against our OWN pid, never used bare: this process holds the
launch home's ``gateway.pid`` and publishes every served profile in ``served_profiles``, so a
@@ -5302,7 +5302,7 @@ def _start_gateway_make_shutdown_signal_handler(runner, _signal_initiated_shutdo
return shutdown_signal_handler
-def _start_gateway_claim_pid_file() -> bool:
+def _start_gateway_claim_pid_file(force: bool = False) -> bool:
"""Claim the runtime lock + PID file (O_EXCL winner is the authoritative gateway). False = lost."""
import atexit
from gateway.status import (
@@ -5324,16 +5324,26 @@ def _start_gateway_claim_pid_file() -> bool:
return False
atexit.register(remove_pid_file)
atexit.register(release_gateway_runtime_lock)
- _claim_host_gateway_role()
+ _claim_host_gateway_role(force=force)
return True
-def _claim_host_gateway_role() -> None:
- """Take the HOST-wide gateway lock alongside the per-home one and publish the record.
+def _claim_host_gateway_role(force: bool = False) -> None:
+ """Take the HOST-wide gateway lock, publish the record — or REFUSE to be the second gateway.
- Observe-only in this step: the per-home lock above still decides whether this process runs,
- so a host with two gateways (the shape the multiplex-only ruling forbids) starts as it always
- did and says so in the log. Flipping this into a refusal is a separate, reviewable change.
+ The lock is no longer observe-only. ``gateway.host_attach`` already answers "is there a host
+ gateway and does it serve me?" before anything binds, but it reads a RECORD, and a record is
+ published a moment after the owner starts: two gateways launched together (a supervisor
+ restarting two units, an update relaunch racing a manual start) can both see no owner and both
+ proceed. The lock is the only atomic arbiter of that race, so losing it means we are the second
+ gateway on this host — the shape multiplex-only forbids.
+
+ The refusal is deliberately EX_TEMPFAIL (75), never the parking 78: losing a lock race is a
+ runtime observation, not a config verdict. Every supervisor we generate retries 75, and on the
+ retry the owner's record exists, so the attach path resolves the profile properly (attach,
+ rescan-then-attach, or a named refusal) instead of the unit being parked forever.
+
+ ``--force`` skips the question exactly as it does in the attach path.
"""
from gateway import host_rendezvous as hr
@@ -5350,18 +5360,46 @@ def _claim_host_gateway_role() -> None:
hr.cleanup_on_exit(hr.ROLE_GATEWAY)
return
if outcome is hr.HostLockOutcome.COULD_NOT_OPEN:
+ # NOT contention: a read-only/undeletable lock dir. Refusing here would take a working
+ # single-gateway host down over an unusable directory.
logger.warning(
"Host gateway lock could not be opened (%s); this gateway is not discoverable. "
"No second gateway is implied — the lock directory itself is unusable.", error)
return
- owner = hr.read_record(hr.ROLE_GATEWAY)
- logger.warning(
- "Another gateway already owns this host (%s). Multiplex-only expects exactly one "
- "gateway per host; starting anyway (observe-only).",
- hr.describe(owner) if owner else "owner unknown",
- )
except Exception:
logger.debug("host gateway rendezvous failed", exc_info=True)
+ return
+ # Lost the lock. Reading the owner's record may fail (it is published a moment after the
+ # claim); that changes WHO we can name, never the verdict -- we are the second gateway.
+ owner = None
+ try:
+ owner = hr.read_record(hr.ROLE_GATEWAY, include_stale=True)
+ except Exception:
+ logger.debug("host gateway record unreadable", exc_info=True)
+ if force:
+ logger.warning("--force: starting a second gateway although %s owns this host.",
+ hr.describe(owner) if owner else "another process")
+ return
+ _refuse_second_host_gateway(owner)
+
+
+def _refuse_second_host_gateway(owner) -> None:
+ """Print the named refusal and exit 75 so a supervisor retries instead of parking the unit."""
+ from gateway import host_rendezvous as hr
+ from gateway.restart import GATEWAY_SERVICE_RESTART_EXIT_CODE
+ from hermes_cli.gateway_migrate import MIGRATE_COMMAND
+
+ who = hr.describe(owner) if owner else "owner unknown (its record is gone)"
+ message = (
+ f"❌ Another gateway already owns this host: {who}\n"
+ f" Exactly one gateway per host serves every profile, so this process will not start a\n"
+ f" second one (it would double-bind this profile's platforms).\n"
+ f" Fold every profile onto the owner: {MIGRATE_COMMAND}\n"
+ f" Or take the host over: hermes gateway run --replace\n"
+ f" Or start one anyway: hermes gateway run --force")
+ logger.error("Refusing to start a second gateway on this host: %s", who)
+ print(message)
+ raise SystemExit(GATEWAY_SERVICE_RESTART_EXIT_CODE)
def _refresh_host_gateway_record(runner) -> None:
@@ -5709,7 +5747,7 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =
_planned_stop_watcher_thread.start()
# PID file BEFORE adapters: of two concurrent `run --replace`, only the O_EXCL winner opens sockets.
- if not _start_gateway_claim_pid_file():
+ if not _start_gateway_claim_pid_file(force=force or replace):
return False
# Right after the PID claim (which makes us authoritative); non-fatal — consumers fall back to scan.
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 56bbc6ad806..5f82c5d3d92 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -2095,12 +2095,13 @@ DEFAULT_CONFIG = {
"write_sessions_json": True,
# One gateway for every profile on this host: the DEFAULT profile's gateway also connects
# each named profile's bots (their own .env / config.yaml, per-profile secret scope) and
- # stamps the profile into session keys. On by default. An UNSET key is a request, not a
- # verdict: at boot the default gateway runs the migration preflight and stays standalone
- # (logging why) when a secondary still runs its own gateway or a blocker exists — an
- # explicit `true` (config or GATEWAY_MULTIPLEX_PROFILES) is honoured as before, an explicit
- # `false` keeps per-profile gateways for good. `hermes gateway migrate --multiplex` folds a
- # per-profile fleet (records a rollback manifest; `--standalone` undoes it and pins false).
+ # stamps the profile into session keys. This is the ONLY supported topology — there is no
+ # `false` opt-out any more: an explicit `false` still parses (it is the runtime mode flag
+ # every scoped code path reads) but is warned about and IGNORED for process topology, and
+ # `hermes gateway migrate --multiplex` folds any per-profile fleet that is left.
+ # An UNSET key is a request, not a verdict: at boot the gateway runs the migration
+ # preflight and stays standalone (logging why) while a secondary still runs its own
+ # gateway or a blocker exists, then converges once that is resolved.
# Two profiles configuring the same bot token cannot be served together — the duplicate
# adapter is parked; `hermes profile create --clone` therefore leaves messaging channels
# behind unless --clone-channels is passed.
@@ -2108,9 +2109,9 @@ DEFAULT_CONFIG = {
# May `hermes update` fold this install onto a multiplexed default gateway by itself?
# True (the default) keeps today's behaviour: a multi-profile install whose secondaries run
# their own gateways is migrated automatically after an update when nothing blocks it.
- # Set to False to stay on per-profile gateways — a durable opt-out that survives updates, so
- # the decision is not re-litigated on every release. Only the AUTOMATIC path reads this:
- # `hermes gateway migrate --multiplex` is an explicit request and always proceeds.
+ # Set to False to choose WHEN you converge, not whether: the fold is left to you to run by
+ # hand (it is not an opt-out from the one-gateway-per-host model, which has none). Only the
+ # AUTOMATIC path reads this: `hermes gateway migrate --multiplex` is explicit and proceeds.
"auto_multiplex_migration": True,
# Route inbound chats of the default profile's bots to another profile
# (gateway/profile_routing.py): [{profile, platform, chat_id|user_id|guild_id|...}].
diff --git a/hermes_cli/container_boot.py b/hermes_cli/container_boot.py
index 602cedc3742..3604efc6b0b 100644
--- a/hermes_cli/container_boot.py
+++ b/hermes_cli/container_boot.py
@@ -77,18 +77,15 @@ def reconcile_profile_gateways(
review).
"""
actions: list[ReconcileAction] = []
- # Under a multiplexing root gateway named slots are still registered but must not boot from
- # their persisted run intent, or they would become additional multiplex owners.
- # Explicit opt-in only: the unset default (on) is refused on s6 hosts by the gateway's own boot
- # guard (per-profile gateways are s6 slots the preflight cannot fold), so the slots keep booting.
- from gateway.config import load_gateway_config
- from utils import is_truthy_value
- try:
- multiplex_profiles = load_gateway_config().multiplex_profiles is True
- except Exception:
- log.warning("Unable to load gateway configuration during container boot; using the "
- "GATEWAY_MULTIPLEX_PROFILES override if set.", exc_info=True)
- multiplex_profiles = is_truthy_value(os.environ.get("GATEWAY_MULTIPLEX_PROFILES"))
+ # ONE gateway per container: named slots are registered (so `hermes -p X gateway start` has a
+ # target and `s6-svstat` can report them) but are NEVER booted from their persisted run intent.
+ # This is the s6 leg of the multiplex-only convergence: an image upgraded from a release that
+ # booted N per-profile slots comes back up with one multiplexing root gateway and no manual
+ # step, instead of N processes fighting over the same profiles.
+ #
+ # It used to be gated on `gateway.multiplex_profiles`, which made the UNSET default (on) boot
+ # the slots anyway — the container shipped the opt-out topology by accident. The key is retired
+ # as a topology switch (hermes_cli/gateway_multiplex_mode.py), so there is nothing to read.
# A legacy `gateway run` container with no state yet seeds `running` (pre-s6 behavior).
legacy_default_state = _maybe_migrate_legacy_gateway_run_state(
@@ -113,7 +110,8 @@ def reconcile_profile_gateways(
continue
prior_state = _read_desired_state(entry)
- should_start = not multiplex_profiles and prior_state in _AUTOSTART_STATES
+ # Registered down, always: a started named slot IS a second gateway on this host.
+ should_start = False
if not dry_run:
_cleanup_stale_runtime_files(entry)
_register_service(scandir, entry.name, start=should_start)
diff --git a/hermes_cli/cron.py b/hermes_cli/cron.py
index eb7f28bdc4d..5431dda516a 100644
--- a/hermes_cli/cron.py
+++ b/hermes_cli/cron.py
@@ -516,13 +516,10 @@ def cron_status():
" sudo hermes --profile default gateway install --system # Linux servers: boot-time service\n"
" hermes --profile default gateway run # Or run in foreground")
if active not in ("default", "custom"):
- print("\n Then make sure it serves this profile:\n"
- " hermes --profile default config set gateway.multiplex_profiles true\n"
- " hermes --profile default gateway restart\n"
- " To fold existing per-profile services into it, with preflight checks:\n"
+ print("\n It serves this profile automatically. If a per-profile service or gateway\n"
+ " from an older release is still installed, fold it in (preflight + dry run):\n"
+ " hermes --profile default gateway migrate --multiplex --dry-run\n"
" hermes --profile default gateway migrate --multiplex\n"
- " LEGACY (pre-multiplex topology, not recommended): a per-profile service via\n"
- " hermes gateway install # starts a SECOND gateway process on this host\n"
" Check: hermes cron status from this profile should show its ticker heartbeat.\n")
print()
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 0a9af29e0cb..4934d312a10 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -1547,9 +1547,8 @@ def _print_multiplex_standalone_reason() -> None:
except Exception:
return
if reason:
- print(f"⚠ Serving the default profile only (gateway.multiplex_profiles unset): {reason}")
+ print(f"⚠ Serving the default profile only: {reason}")
print(" Fold every profile onto this gateway: hermes gateway migrate --multiplex")
- print(" Keep per-profile gateways: hermes config set gateway.multiplex_profiles false")
def _print_served_ingress_urls(profile: str | None = None) -> None:
diff --git a/hermes_cli/gateway_migrate.py b/hermes_cli/gateway_migrate.py
index 52596df0bca..09589cfafb8 100644
--- a/hermes_cli/gateway_migrate.py
+++ b/hermes_cli/gateway_migrate.py
@@ -1,8 +1,18 @@
-"""``hermes gateway migrate --multiplex`` / ``--standalone``: move a per-profile-gateway install onto one
-multiplexed default gateway (and back), with a table-driven preflight.
+"""``hermes gateway migrate --multiplex``: converge a per-profile-gateway install onto the ONE
+host gateway, with a table-driven preflight.
-Standalone per-profile gateways stay supported; this is a migration path, not a removal. The
-preflight reuses the gateway's own conflict logic (``GatewayRunner._adapter_credential_fingerprint``,
+Multiplex-only (Teknium ruling): exactly one ``hermes gateway run`` per host, serving every
+profile. This command is the supported convergence path, and it is defined by TOPOLOGY, not by a
+config flag — a host is converged when no secondary profile owns a gateway process or a supervisor
+unit any more. That makes it re-runnable: a half-migrated host (flag flipped, a unit left behind, a
+crash between the two) converges on the next run instead of being reported "already multiplexed".
+
+There is no ``--standalone`` rollback command: reinstalling per-profile services is no longer a
+supported topology. The rollback machinery survives as the COMPENSATOR inside a single failed
+apply (:func:`rollback_migration`) — a failed apply must never leave profiles with no gateway at
+all — and the recorded manifest is what the next re-run resumes from.
+
+The preflight reuses the gateway's own conflict logic (``GatewayRunner._adapter_credential_fingerprint``,
``platform_binds_port``, the adapters' ``serves_profile_prefix`` declaration) so its verdict matches
what the multiplexer would do at startup. ``hermes update`` calls :func:`maybe_auto_migrate_after_update`.
"""
@@ -75,7 +85,9 @@ class ProfileGateway:
def _service_label(service: tuple[str, bool]) -> str:
kind, system = service
- return f"{kind} ({'system' if system else 'user'})" if kind == "systemd" else kind
+ if kind == "systemd":
+ return f"systemd ({'system' if system else 'user'})"
+ return "Windows scheduled task" if kind == "windows" else kind
def _service_dict(service: tuple[str, bool]) -> dict:
@@ -106,7 +118,13 @@ class MigrationPlan:
@property
def already_multiplexed(self) -> bool:
- if self.interrupted:
+ """Converged: nothing is left for this command to do.
+
+ TOPOLOGY, not the flag. A host whose flag is on while a secondary still owns a gateway
+ process or a supervisor unit is HALF-migrated; reporting that as "already multiplexed"
+ made the re-run a no-op on exactly the host that needed it most (#100896).
+ """
+ if self.interrupted or self.standalone_secondaries:
return False
return self.multiplex_flag_on or bool(self.live_served and len(self.live_served) > 1)
@@ -205,7 +223,7 @@ def _gateway_identity(home: Path, pid: Optional[int], services: list[tuple[str,
def _installed_services(home: Path) -> list[tuple[str, bool]]:
- """Every installed service for ``home``'s gateway (units / plist on disk), user scope first."""
+ """Every installed service for ``home``'s gateway (units / plist / scheduled task), user scope first."""
from hermes_cli import gateway as gw
found: list[tuple[str, bool]] = []
with _home_env(home):
@@ -213,9 +231,25 @@ def _installed_services(home: Path) -> list[tuple[str, bool]]:
found.extend(("systemd", system) for system in (False, True) if gw.get_systemd_unit_path(system=system).exists())
if gw.is_macos() and gw.get_launchd_plist_path().exists():
found.append(("launchd", False))
+ if gw.is_windows() and _windows_task_installed():
+ found.append(("windows", False))
return found
+def _windows_task_installed() -> bool:
+ """Is a per-profile Windows gateway installed for the ACTIVE ``HERMES_HOME``?
+
+ ``get_task_name()`` is home-suffixed, so this answers per profile exactly the way the systemd
+ unit path does. Either half counts: ``hermes gateway install`` falls back to a Startup-folder
+ entry when it cannot register a scheduled task, and a migration that removed only the task
+ would leave the fallback launching a second gateway at the next logon.
+ """
+ from hermes_cli import gateway_windows as gww
+ with contextlib.suppress(Exception):
+ return bool(gww.is_task_registered() or gww.is_startup_entry_installed())
+ return False
+
+
def _systemd_service_user(home: Path, services: list[tuple[str, bool]]) -> Optional[str]:
"""Read ``User=`` before migration removes a system-scope unit."""
if ("systemd", True) not in services:
@@ -232,6 +266,11 @@ def _service_op(kind: str, system: bool, verb: str, home: Path, *, run_as_user:
if verb == "install":
if kind == "launchd":
gw.launchd_install()
+ elif kind == "windows":
+ # Non-interactive: the migration already asked; prompting here would hang a
+ # supervised/`--yes` run on a console that has no operator.
+ from hermes_cli import gateway_windows as gww
+ gww.install(start_now=True, start_on_login=True)
else:
gw.systemd_install(system=system, run_as_user=run_as_user, non_interactive=True)
return
@@ -408,7 +447,7 @@ def _check_secondary_port_binders(plan: MigrationPlan, configs: dict[str, object
f"Profile '{profile.name}' enables {platform.value}, which binds its own port and has no "
f"/p/{profile.name}/ ingress on the default listener yet; the multiplexer would skip "
f"the whole profile. Disable it there (platforms.{platform.value}.enabled: false) or "
- f"keep '{profile.name}' on a standalone gateway (hermes -p {profile.name} gateway start --force)."
+ f"add a /p/<profile>/ ingress for it first."
)
@@ -484,7 +523,11 @@ def format_plan(plan: MigrationPlan, *, dry_run: bool) -> list[str]:
if plan.interrupted:
lines.append(f" ↻ An earlier migration was interrupted before the default gateway came up "
f"(flag on, no live multiplexer; manifest {plan.default_home / MANIFEST_NAME}); this run resumes it.")
+ elif plan.multiplex_flag_on and plan.standalone_secondaries:
+ lines.append(" ↻ Half-migrated host: the flag is on, but the profile(s) below still own a "
+ "gateway. This run converges them.")
steps = []
+ signalled = [p for p in plan.standalone_secondaries if p.pid]
for p in plan.standalone_secondaries:
what = " + ".join(x for x in (f"stop pid {p.pid}" if p.pid else "", f"uninstall {p.service_label()}" if p.services else "") if x)
steps.append(f" - {p.name}: {what}")
@@ -498,7 +541,16 @@ def format_plan(plan: MigrationPlan, *, dry_run: bool) -> list[str]:
target = plan.target_service_kind()
lines.append(f" - default: {'restart' if plan.default.has_gateway else 'start'} the gateway"
+ (f" via {target[0]}" if target else " (detached)") + f", verify it serves {len(plan.profiles)} profiles")
- lines.append(f" - record the previous state in {plan.default_home / MANIFEST_NAME} (rollback: hermes gateway migrate --standalone)")
+ lines.append(f" - record the previous state in {plan.default_home / MANIFEST_NAME} "
+ f"(used to undo a FAILED apply, and to resume this command after a crash)")
+ if signalled:
+ # Never stop a running gateway without saying so first, and say it in the imperative
+ # tense the operator can still act on: this block prints BEFORE anything is signalled.
+ lines += ["",
+ " ⚠ This SIGTERMs running gateway process(es): "
+ + ", ".join(f"{p.name} (pid {p.pid})" for p in signalled) + ".",
+ " They drain in-flight turns and exit; their profiles are served by the host "
+ "gateway afterwards."]
return lines + _plan_tail(plan)
@@ -513,11 +565,6 @@ def _plan_tail(plan: MigrationPlan) -> list[str]:
return lines
-def _no_manifest_lines(default_home: Path) -> list[str]:
- return [f"✗ No migration manifest at {_manifest_path(default_home)}; nothing to roll back.",
- " To leave multiplex mode by hand: hermes config set gateway.multiplex_profiles false && hermes gateway restart"]
-
-
def _manifest_secondaries(manifest: dict) -> Optional[list[dict]]:
"""The manifest's secondary records, or None when the (hand-edited) manifest is malformed."""
recs = manifest.get("secondaries", [])
@@ -559,30 +606,6 @@ def _target_from_manifest(manifest: dict) -> tuple[Optional[tuple[str, bool]], O
_NOTHING_RECORDED = "no gateway was recorded; nothing to restore"
-def format_rollback_plan(default_home: Path, manifest: dict, *, dry_run: bool) -> list[str]:
- head = "Rollback plan (dry run — nothing changed)" if dry_run else "Rollback plan"
- lines = [head, f" default home: {default_home}", "", " Steps:"]
- lines.append(" - default: restore gateway.multiplex_profiles to its pre-migration value")
- lines.append(" - default: clear multiplex-owned runtime status")
- secondaries = _manifest_secondaries(manifest)
- if secondaries is None:
- return lines + [f" ✗ malformed secondary records in {_manifest_path(default_home)}; fix or delete the manifest"]
- for rec in secondaries:
- services = _recorded_services(rec)
- if services:
- action = "reinstall and start its " + " + ".join(_service_label(s) for s in services) + " service"
- elif rec.get("pid"):
- action = "start its standalone gateway (detached)"
- else:
- action = _NOTHING_RECORDED
- lines.append(f" - {rec['profile']}: {action}")
- lines += [
- f" - remove rollback manifest {_manifest_path(default_home)}",
- " - default: restart the standalone gateway last",
- ]
- return lines
-
-
def format_update_warning(plan: MigrationPlan, auto_blockers: list[str]) -> list[str]:
return [
"⚠ Your profiles each run their own gateway. A single multiplexed gateway is the recommended",
@@ -749,18 +772,17 @@ def apply_migration(plan: MigrationPlan, *, served_wait: float = _SERVED_WAIT_SE
print("✓ Already multiplexed — nothing to do.")
return True
target, run_as_user = plan.target_service_kind(), plan.target_run_as_user()
- if plan.interrupted:
- # An earlier apply flipped the flag (and removed some or all secondaries) but the default never
- # came up; the manifest is the only record of the units that existed. Finish from it, don't rewrite it.
- manifest = _read_manifest(plan.default_home) or {}
- target, run_as_user = _target_from_manifest(manifest)
- print(f" ↻ resuming an interrupted migration recorded in {_manifest_path(plan.default_home)}")
- elif _read_manifest(plan.default_home) is not None:
- # Flag off + manifest present = a rollback (or an apply killed before its flag write) that did
- # not finish. Overwriting the manifest would discard the only record of the units to restore.
- _print([f"✗ A previous migration's manifest is still at {_manifest_path(plan.default_home)} (its rollback did not finish).",
- " Finish it with: hermes gateway migrate --standalone (or delete the manifest to start over)"])
- return False
+ recorded = _read_manifest(plan.default_home)
+ if recorded is not None:
+ # A manifest on disk means an earlier apply got past its first destructive step: it either
+ # died mid-way (``interrupted``) or its compensating rollback did not finish. Either way the
+ # manifest is the ONLY record of the units that existed, so resume from it and never
+ # overwrite it. Re-running this command IS the recovery — there is no rollback command to
+ # send the operator to, and refusing here left a half-migrated host with no way forward.
+ manifest = recorded
+ m_target, m_user = _target_from_manifest(manifest)
+ target, run_as_user = m_target or target, m_user or run_as_user
+ print(f" ↻ resuming the migration recorded in {_manifest_path(plan.default_home)}")
else:
blocker = _preflight_apply(plan, target, run_as_user)
if blocker is not None:
@@ -782,32 +804,40 @@ def apply_migration(plan: MigrationPlan, *, served_wait: float = _SERVED_WAIT_SE
print(f" ✓ {_restart_default(plan.default, target, plan.default_home, run_as_user=run_as_user)}")
except Exception as exc:
_print([f" ✗ migration failed ({exc})",
- " ↩ Rolling back to per-profile gateways so no profile is left without one..."])
+ " ↩ Restoring the per-profile gateways so no profile is left without one..."])
rolled_back = rollback_migration(plan.default_home)
if not rolled_back:
- print(f" Re-run {MIGRATE_COMMAND} to resume, or hermes gateway migrate --standalone to roll back.")
+ print(f" Re-run {MIGRATE_COMMAND} to resume from the manifest.")
return False
expected = {p.name for p in plan.profiles}
served = _wait_for_served(plan.default_home, expected, served_wait)
if served is not None and expected <= set(served):
+ # Manifest present == migration UNFINISHED. That is the whole resume/half-migrated signal
+ # (`MigrationPlan.interrupted`), so a CONFIRMED convergence must clear it -- otherwise the
+ # host reports itself interrupted forever and never says "already multiplexing".
+ _manifest_path(plan.default_home).unlink(missing_ok=True)
_print(["", f"✓ Migrated: the default gateway now serves {len(served)} profiles: {', '.join(served)}",
- " Rollback any time with: hermes gateway migrate --standalone",
*[f" • {n}" for n in plan.notices]])
return True
missing = sorted(expected - set(served or []))
_print(["", f"⚠ Migration applied, but the default gateway has not confirmed serving: {', '.join(missing)}",
" Check `hermes gateway status` and the gateway log; the flag and manifest are in place.",
- " Rollback: hermes gateway migrate --standalone"])
+ f" Re-run {MIGRATE_COMMAND} once it is healthy — it resumes from the manifest."])
return False
def rollback_migration(default_home: Optional[Path] = None) -> bool:
- """``--standalone``: flag off, reinstall/start the recorded per-profile gateways, restart default."""
+ """COMPENSATOR for a failed apply: restore the flag and the recorded per-profile gateways.
+
+ Not a user-facing rollback — ``--standalone`` is gone and per-profile gateways are no longer a
+ supported topology. This runs only inside :func:`apply_migration` when a destructive step
+ raised, because the one outcome worse than a per-profile fleet is a profile with NO gateway.
+ """
default_home = default_home or _default_home()
manifest = _read_manifest(default_home)
if manifest is None:
- _print(_no_manifest_lines(default_home))
+ print(f"✗ No migration manifest at {_manifest_path(default_home)}; nothing to restore.")
return False
incomplete = f"⚠ Rollback incomplete; manifest kept at {_manifest_path(default_home)}."
secondaries = _manifest_secondaries(manifest)
@@ -878,7 +908,7 @@ def rollback_migration(default_home: Optional[Path] = None) -> bool:
print(f" ✗ default: could not restart its standalone gateway ({exc})")
print(" The default gateway is still multiplexing; stop it by hand (hermes gateway stop) and re-run.")
if ok:
- print("✓ Rolled back to per-profile gateways.")
+ print("✓ Restored the per-profile gateways that existed before this attempt.")
else:
print(incomplete)
return ok
@@ -888,27 +918,24 @@ def rollback_migration(default_home: Optional[Path] = None) -> bool:
def _host_supports_migration() -> Optional[str]:
- """Reason the host cannot be migrated by this command (s6 slots / Windows tasks), else None."""
+ """Reason the host cannot be converged by this command (s6 slots), else None.
+
+ Windows IS handled now: per-profile Scheduled Tasks (and the Startup-folder fallback) are
+ detected and removed like any other unit. s6 is not, and cannot be from here: the per-profile
+ gateways are slots the container image registers at boot
+ (``hermes_cli/container_boot.py::reconcile_profile_gateways``), so the convergence belongs to
+ the container's own boot, not to a process inside it.
+ """
from hermes_cli import gateway as gw
if gw._running_under_s6():
- return "s6-supervised container: per-profile gateways are s6 slots; set gateway.multiplex_profiles on the default profile and restart the container instead."
- if gw.is_windows():
- return "Windows Scheduled Tasks are not migrated automatically; set gateway.multiplex_profiles true, stop the per-profile tasks, and `hermes gateway restart`."
+ return ("s6-supervised container: per-profile gateways are s6 slots registered by the "
+ "container's boot, not by this process. Restart the container so its boot "
+ "reconciles them; nothing on this host was changed.")
return None
def cmd_migrate(args) -> None:
- """``hermes gateway migrate [--multiplex|--standalone] [--dry-run] [--yes]``."""
- if getattr(args, "standalone", False):
- if getattr(args, "dry_run", False):
- default_home = _default_home()
- manifest = _read_manifest(default_home)
- if manifest is None:
- _print(_no_manifest_lines(default_home))
- sys.exit(1)
- _print(format_rollback_plan(default_home, manifest, dry_run=True))
- return
- sys.exit(0 if rollback_migration() else 1)
+ """``hermes gateway migrate [--multiplex] [--dry-run] [--yes]``."""
reason = _host_supports_migration()
if reason:
print(f"✗ {reason}")
diff --git a/hermes_cli/gateway_multiplex_mode.py b/hermes_cli/gateway_multiplex_mode.py
index 7d6eb549053..a133e5edc0c 100644
--- a/hermes_cli/gateway_multiplex_mode.py
+++ b/hermes_cli/gateway_multiplex_mode.py
@@ -1,12 +1,16 @@
-"""Boot-time verdict for an UNSET ``gateway.multiplex_profiles`` (the default is on).
+"""Boot-time verdict for ``gateway.multiplex_profiles`` (the default is on, and there is no opt-out).
``GatewayConfig.from_dict`` leaves the flag ``None`` when neither config.yaml nor
``GATEWAY_MULTIPLEX_PROFILES`` set it. Turning the default on must not make a default gateway
double-bind a fleet that still runs per-profile gateways (two pollers on one bot token, port
fights), so the implicit default is a *request*: the gateway runs the same preflight
``hermes gateway migrate --multiplex`` runs and multiplexes only when the fold would have been
-safe. An explicit value is never second-guessed — ``true`` multiplexes (the operator or the
-migration chose it), ``false`` keeps per-profile gateways for good (``--standalone`` pins it).
+safe. An explicit ``true`` is never second-guessed.
+
+An explicit ``false`` is RETIRED (multiplex-only ruling): it parses, it is logged, and it is then
+resolved exactly like an unset key. The key itself survives because it is still the RUNTIME
+mode flag every scoped code path reads (``config.multiplex_profiles``) — what it can no longer do
+is pin a second gateway process onto this host.
The refusal is logged, never fatal: the gateway comes up standalone exactly as before the
default flipped, and the log names the blocker plus ``hermes gateway migrate --multiplex``.
@@ -23,6 +27,13 @@ logger = logging.getLogger(__name__)
SINGLE_PROFILE_REASON = "only one profile exists (nothing to multiplex)"
+#: ``gateway.multiplex_profiles: false`` is no longer an opt-out from the one-gateway-per-host
+#: topology; it parses, it is reported, and it is ignored.
+RETIRED_OPT_OUT_REASON = (
+ "gateway.multiplex_profiles: false is retired and was ignored: one gateway per host serves "
+ "every profile. Remove the key; `hermes gateway migrate --multiplex` folds any leftover "
+ "per-profile gateway.")
+
def explicit_multiplex_flag(default_home: Path) -> Optional[bool]:
"""The operator's explicit choice for the DEFAULT profile's gateway: a recognized
@@ -73,13 +84,17 @@ class MultiplexDecision:
def implicit_multiplex_blocker() -> Optional[str]:
- """Why THIS process must not multiplex on the implicit default, or None when it may.
+ """Why THIS process must not multiplex right now, or None when it may.
Mirrors what makes ``hermes gateway migrate --multiplex`` refuse or leave a per-profile gateway
- in place: hosts whose per-profile gateways the preflight cannot see (s6 slots, Windows
- scheduled tasks) stay standalone; a secondary that still runs its own gateway (live process or
- installed service) or a preflight blocker (duplicate bot credential, port binder without a
- ``/p/<profile>/`` ingress) keeps this gateway standalone.
+ in place: hosts whose per-profile gateways the preflight cannot see (s6 slots) stay standalone;
+ a secondary that still runs its own gateway (live process or installed service) or a preflight
+ blocker (duplicate bot credential, port binder without a ``/p/<profile>/`` ingress) keeps this
+ gateway standalone.
+
+ Every blocker here is a TRANSIENT, fixable condition, which is why this function is now also
+ the whole answer for an explicit ``gateway.multiplex_profiles: false`` (see
+ :func:`resolve_multiplex_mode`): the host converges the moment the blocker is gone.
The launching profile's IDENTITY is deliberately not a blocker: multiplex-only means "the one
host process", whichever profile started it. Gating on ``active == 'default'`` made a host
@@ -101,25 +116,38 @@ def implicit_multiplex_blocker() -> Optional[str]:
owned = ", ".join(
f"'{p.name}' ({'pid ' + str(p.pid) if p.pid else p.service_label()})"
for p in plan.standalone_secondaries)
- return (f"profile(s) {owned} still run their own gateway; fold them with `{MIGRATE_COMMAND}` "
- f"or pin gateway.multiplex_profiles: false to keep per-profile gateways")
+ return f"profile(s) {owned} still run their own gateway; fold them with `{MIGRATE_COMMAND}`"
if plan.blocked:
return "; ".join(plan.blockers)
return None
def resolve_multiplex_mode(config) -> MultiplexDecision:
- """Settle ``config.multiplex_profiles`` for one gateway boot; the config is updated in place."""
+ """Settle ``config.multiplex_profiles`` for one gateway boot; the config is updated in place.
+
+ ``gateway.multiplex_profiles: false`` is RETIRED as a topology opt-out (multiplex-only ruling).
+ The key still parses and still drives the runtime mode this function writes back, but an
+ explicit ``false`` no longer pins a per-profile fleet: it is warned about and resolved exactly
+ like an unset key. That is safe because the unset path is not optimistic — it refuses to
+ multiplex while any real blocker holds (an s6 container, a secondary that still owns a gateway,
+ a duplicate bot credential), so a host that genuinely cannot fold still comes up standalone and
+ says why, and it converges by itself once ``hermes gateway migrate --multiplex`` has run.
+ """
current = getattr(config, "multiplex_profiles", None)
- if current is not None:
- return MultiplexDecision(bool(current), "config")
+ if current:
+ return MultiplexDecision(True, "config")
+ retired_opt_out = current is False
try:
blocker = implicit_multiplex_blocker()
except Exception as exc: # a broken preflight must not take the gateway down with it
logger.warning("Multiplex preflight failed; starting standalone: %s", exc, exc_info=True)
blocker = f"preflight failed ({exc})"
- decision = (MultiplexDecision(False, "guard", blocker) if blocker
- else MultiplexDecision(True, "default", "gateway.multiplex_profiles unset; default applies"))
+ if blocker:
+ decision = MultiplexDecision(False, "guard", blocker)
+ elif retired_opt_out:
+ decision = MultiplexDecision(True, "retired-opt-out", RETIRED_OPT_OUT_REASON)
+ else:
+ decision = MultiplexDecision(True, "default", "gateway.multiplex_profiles unset; default applies")
config.multiplex_profiles = decision.enabled
return decision
@@ -136,15 +164,14 @@ def record_multiplex_decision(decision: MultiplexDecision) -> None:
def log_multiplex_decision(decision: MultiplexDecision) -> None:
record_multiplex_decision(decision)
- if decision.source == "config" and not decision.enabled:
- logger.info("gateway.multiplex_profiles is false: serving this profile only "
- "(hermes gateway migrate --multiplex folds every profile onto the default gateway).")
+ if decision.source == "retired-opt-out":
+ logger.warning("%s", RETIRED_OPT_OUT_REASON)
elif decision.source == "guard" and decision.reason == SINGLE_PROFILE_REASON:
logger.info("Single-profile install: gateway.multiplex_profiles unset, serving the default profile only.")
elif decision.source == "guard":
logger.warning(
- "gateway.multiplex_profiles is unset (default: on) but this gateway stays standalone: %s. "
- "It serves the default profile only; set gateway.multiplex_profiles explicitly to silence this.",
+ "This gateway stays standalone: %s. It serves the default profile only; the host "
+ "converges once that is resolved.",
decision.reason)
elif decision.source == "default":
logger.info("Serving every profile on this host (gateway.multiplex_profiles unset; default on).")
diff --git a/hermes_cli/subcommands/gateway.py b/hermes_cli/subcommands/gateway.py
index dbd1c3fa0cb..9c7c5d1ea42 100644
--- a/hermes_cli/subcommands/gateway.py
+++ b/hermes_cli/subcommands/gateway.py
@@ -130,15 +130,15 @@ def build_gateway_parser(
_flag(gateway_migrate_legacy, "-y", "--yes", dest="yes", help="Skip the confirmation prompt")
gateway_migrate = gateway_subparsers.add_parser(
- "migrate", help="Move per-profile gateways onto one multiplexed default gateway (or back)",
- description="Stop and uninstall each secondary profile's standalone gateway, turn on "
- "gateway.multiplex_profiles on the default profile and restart its gateway so it serves "
- "every profile. Runs a preflight first (duplicate bot tokens, port-binding platforms "
- "without a /p/<profile>/ ingress) and changes nothing when blocked. "
- "--standalone rolls the recorded migration back.")
- mode = gateway_migrate.add_mutually_exclusive_group()
- _flag(mode, "--multiplex", dest="multiplex", help="Migrate to one multiplexed gateway (default)")
- _flag(mode, "--standalone", dest="standalone", help="Roll back to per-profile gateways from the recorded manifest")
+ "migrate", help="Converge every per-profile gateway onto the ONE host gateway",
+ description="Converge this host onto the one-gateway-per-host model: stop and uninstall "
+ "each secondary profile's gateway and its supervisor unit (systemd, launchd, Windows "
+ "Scheduled Task), then restart the default profile's gateway so it serves every "
+ "profile. Runs a preflight first (duplicate bot tokens, port-binding platforms "
+ "without a /p/<profile>/ ingress) and changes nothing when blocked. Safe to re-run: a "
+ "half-migrated host converges on the next run. Per-profile gateways are not a "
+ "supported topology any more, so there is no rollback command.")
+ _flag(gateway_migrate, "--multiplex", dest="multiplex", help="Converge onto the one host gateway (default)")
_flag(gateway_migrate, "--dry-run", dest="dry_run", help="Print the plan and blockers without changing anything")
_flag(gateway_migrate, "-y", "--yes", dest="yes", help="Apply without confirmation")
diff --git a/tests/gateway/test_host_gateway_lock_refusal.py b/tests/gateway/test_host_gateway_lock_refusal.py
new file mode 100644
index 00000000000..b818f1eca62
--- /dev/null
+++ b/tests/gateway/test_host_gateway_lock_refusal.py
@@ -0,0 +1,85 @@
+"""The host gateway lock REFUSES a second gateway instead of observing it (multiplex-only).
+
+The real flock is taken on the real lock path; nothing is monkeypatched about the lock itself, so
+the test fails on any build where losing the host lock still starts a second gateway.
+"""
+
+from __future__ import annotations
+
+import sys
+
+import pytest
+
+
+def host_lock_dir(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "gateway-locks"))
+ from gateway import host_rendezvous as hr
+ hr._lock_handles.clear()
+ yield tmp_path
+ hr._lock_handles.clear()
+
+
+def _hold_host_lock_from_another_description(hr):
+ """Hold the host gateway lock on a SEPARATE open file description.
+
+ flock is per-description, so this contends with ``claim_host_lock`` exactly the way a second
+ process would — and it bypasses the per-process memo that would otherwise answer ACQUIRED.
+ """
+ import fcntl
+
+ hr.ensure_host_state_dir()
+ handle = open(hr.lock_path(hr.ROLE_GATEWAY), "a+", encoding="utf-8")
+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
+ return handle
+
+
[email protected](sys.platform == "win32", reason="flock-based contention setup")
+def test_second_host_gateway_is_refused_with_75_naming_the_owner_and_the_migrate_command(
+ host_lock_dir, capsys,
+):
+ from gateway import host_rendezvous as hr
+ from gateway.restart import GATEWAY_FATAL_CONFIG_EXIT_CODE, GATEWAY_SERVICE_RESTART_EXIT_CODE
+ from gateway.run import _claim_host_gateway_role
+ from hermes_cli.gateway_migrate import MIGRATE_COMMAND
+
+ hr.publish_record(hr.ROLE_GATEWAY, profiles=("default", "coder"), home=str(host_lock_dir))
+ owner = hr.read_record(hr.ROLE_GATEWAY, include_stale=True)
+ assert owner is not None
+ handle = _hold_host_lock_from_another_description(hr)
+ try:
+ with pytest.raises(SystemExit) as exc:
+ _claim_host_gateway_role()
+ finally:
+ handle.close()
+
+ # 75 (EX_TEMPFAIL) so systemd/s6/launchd RETRY; 78 would park the unit on a runtime condition.
+ assert exc.value.code == GATEWAY_SERVICE_RESTART_EXIT_CODE
+ assert exc.value.code != GATEWAY_FATAL_CONFIG_EXIT_CODE
+ out = capsys.readouterr().out
+ assert f"PID {owner.pid}" in out and MIGRATE_COMMAND in out
+ assert "--force" in out and "--replace" in out
+
+
[email protected](sys.platform == "win32", reason="flock-based contention setup")
+def test_force_still_starts_a_second_gateway_and_an_unusable_lock_dir_is_not_a_refusal(
+ host_lock_dir, monkeypatch,
+):
+ """The two non-refusals: the operator's explicit escape hatch, and a lock dir we cannot open
+ (EROFS/EACCES is not evidence of a second gateway, and refusing there takes a healthy
+ single-gateway host down)."""
+ from gateway import host_rendezvous as hr
+ from gateway.run import _claim_host_gateway_role
+
+ hr.publish_record(hr.ROLE_GATEWAY, profiles=(), home=str(host_lock_dir))
+ handle = _hold_host_lock_from_another_description(hr)
+ try:
+ _claim_host_gateway_role(force=True) # no SystemExit
+ finally:
+ handle.close()
+
+ hr._lock_handles.clear()
+ monkeypatch.setattr(
+ hr, "claim_host_lock",
+ lambda role: (hr.HostLockOutcome.COULD_NOT_OPEN, OSError("read-only file system")))
+ _claim_host_gateway_role() # no SystemExit
diff --git a/tests/hermes_cli/test_container_boot.py b/tests/hermes_cli/test_container_boot.py
index cb772eeb659..6ccbc110a8c 100644
--- a/tests/hermes_cli/test_container_boot.py
+++ b/tests/hermes_cli/test_container_boot.py
@@ -109,66 +109,57 @@ def _named_actions(actions: list[ReconcileAction]) -> list[ReconcileAction]:
# ---------------------------------------------------------------------------
-def test_running_profile_is_registered_and_autostarted(tmp_path: Path) -> None:
+def test_a_named_profile_slot_is_registered_but_never_autostarted(tmp_path: Path) -> None:
+ """Multiplex-only: the container boots ONE gateway. A named slot that s6 starts on its own is
+ a second gateway process, so the slot is registered DOWN even when its run intent says
+ "running" -- that is how an image upgraded from the per-profile era converges with no manual
+ step (the root gateway serves `coder` instead)."""
scandir = tmp_path / "run-service"; scandir.mkdir()
_make_profile(tmp_path, "coder", state="running")
+ (tmp_path / "gateway_state.json").write_text('{"gateway_state": "running"}', encoding="utf-8")
actions = reconcile_profile_gateways(
hermes_home=tmp_path, scandir=scandir, dry_run=False,
)
assert _named_actions(actions) == [ReconcileAction(
- profile="coder", prior_state="running", action="started",
+ profile="coder", prior_state="running", action="registered",
)]
svc = scandir / "gateway-coder"
assert (svc / "run").exists()
assert (svc / "run").stat().st_mode & 0o111 # executable
assert (svc / "type").read_text().strip() == "longrun"
- # Auto-start means no down-marker.
- assert not (svc / "down").exists()
-
-
- "config_value,env_value,expected",
- [
- pytest.param("true", None, "registered", id="config-only-multiplex"),
- pytest.param("true", "false", "started", id="env-false-overrides-config"),
- ],
-)
-def test_boot_honors_config_multiplex_profiles(
- tmp_path: Path,
- monkeypatch: pytest.MonkeyPatch,
- config_value: str,
- env_value: str | None,
- expected: str,
+ assert (svc / "down").exists(), "a named slot must not boot itself"
+ # The root profile's slot is the ONE gateway and keeps its run intent.
+ default = next(a for a in actions if a.profile == "default")
+ assert default.action == "started"
+
+
[email protected]("config_value,env_value", [
+ pytest.param("false", None, id="config-false"),
+ pytest.param("true", "false", id="env-false-overrides-config"),
+])
+def test_the_retired_opt_out_cannot_boot_a_second_gateway_in_the_container(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, config_value: str, env_value: str | None,
) -> None:
- """Container boot must resolve multiplex_profiles like the gateway does:
- config.yaml opt-in honored (#85413), env override keeps precedence."""
+ """`gateway.multiplex_profiles: false` (and its env override) is retired as a topology switch.
+ It used to decide whether s6 booted the per-profile slots; reading it here is what shipped the
+ opt-out topology by accident on the UNSET default. The slot stays down either way."""
scandir = tmp_path / "run-service"
scandir.mkdir()
_make_profile(tmp_path, "coder", state="running")
- (tmp_path / "config.yaml").write_text(
- f"multiplex_profiles: {config_value}\n",
- encoding="utf-8",
- )
+ (tmp_path / "config.yaml").write_text(f"multiplex_profiles: {config_value}\n", encoding="utf-8")
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
if env_value is None:
monkeypatch.delenv("GATEWAY_MULTIPLEX_PROFILES", raising=False)
else:
monkeypatch.setenv("GATEWAY_MULTIPLEX_PROFILES", env_value)
- actions = reconcile_profile_gateways(
- hermes_home=tmp_path,
- scandir=scandir,
- dry_run=False,
- )
+ actions = reconcile_profile_gateways(hermes_home=tmp_path, scandir=scandir, dry_run=False)
assert _named_actions(actions) == [ReconcileAction(
- profile="coder",
- prior_state="running",
- action=expected,
- )]
- assert (scandir / "gateway-coder" / "down").exists() is (expected == "registered")
+ profile="coder", prior_state="running", action="registered")]
+ assert (scandir / "gateway-coder" / "down").exists()
def test_registered_profile_has_finish_script(tmp_path: Path) -> None:
diff --git a/tests/hermes_cli/test_gateway_migrate_multiplex.py b/tests/hermes_cli/test_gateway_migrate_multiplex.py
index c81075487f3..4445b77eb64 100644
--- a/tests/hermes_cli/test_gateway_migrate_multiplex.py
+++ b/tests/hermes_cli/test_gateway_migrate_multiplex.py
@@ -118,14 +118,14 @@ def test_dry_run_and_blocked_preflight_change_nothing(fleet, capsys):
assert not plan.blocked and plan.eligible_for_migration()
assert [p.name for p in plan.standalone_secondaries] == ["coder", "ops"]
- gm.cmd_migrate(SimpleNamespace(multiplex=True, standalone=False, dry_run=True, yes=True)) # returns; no exit
+ gm.cmd_migrate(SimpleNamespace(multiplex=True, dry_run=True, yes=True)) # returns; no exit
assert "dry run" in capsys.readouterr().out
# Blocked: coder reuses the default's Telegram token -> the gateway's own fingerprint says duplicate.
(fleet.root / "profiles/coder/.env").write_text("TELEGRAM_BOT_TOKEN=111111:default-token\n", encoding="utf-8")
blocked = gm.build_migration_plan()
assert blocked.blocked and "profile_routes" in blocked.blockers[0] and "'coder'" in blocked.blockers[0]
with pytest.raises(SystemExit) as exc:
- gm.cmd_migrate(SimpleNamespace(multiplex=True, standalone=False, dry_run=False, yes=True))
+ gm.cmd_migrate(SimpleNamespace(multiplex=True, dry_run=False, yes=True))
assert exc.value.code == 1
assert fleet.ops == [] and fleet.services == {"coder": ("systemd", False), "ops": ("systemd", False)}
assert fleet.pids == {"coder": 4101, "ops": 4102} and _config_flag(fleet.root) is None
@@ -133,10 +133,31 @@ def test_dry_run_and_blocked_preflight_change_nothing(fleet, capsys):
assert "nothing will be changed" in capsys.readouterr().out
-def test_apply_records_manifest_flips_flag_and_rollback_restores(fleet, capsys):
+def _apply_capturing_manifest(plan, *, served_wait=5.0, restore=False):
+ """Apply, returning (ok, manifest-as-written). A CONFIRMED convergence deletes the manifest
+ (manifest present == unfinished), so the only way to inspect it is to read it mid-flight."""
+ seen = {}
+ real_wait = gm._wait_for_served
+
+ def _wait(default_home, expected, timeout):
+ seen["manifest"] = json.loads((default_home / gm.MANIFEST_NAME).read_text(encoding="utf-8"))
+ return real_wait(default_home, expected, timeout)
+
+ gm._wait_for_served = _wait
+ try:
+ ok = gm.apply_migration(plan, served_wait=served_wait)
+ finally:
+ gm._wait_for_served = real_wait
+ if restore: # put it back to drive the compensator, which only ever runs on an UNfinished apply
+ gm._write_manifest(plan.default_home, seen["manifest"])
+ return ok, seen["manifest"]
+
+
+def test_apply_clears_the_manifest_on_success_and_the_compensator_restores(fleet, capsys):
plan = gm.build_migration_plan()
- assert gm.apply_migration(plan, served_wait=5.0) is True
- manifest = json.loads((fleet.root / gm.MANIFEST_NAME).read_text(encoding="utf-8"))
+ ok, manifest = _apply_capturing_manifest(plan)
+ assert ok is True
+ assert not (fleet.root / gm.MANIFEST_NAME).exists(), "a confirmed migration is not 'interrupted'"
assert {s["profile"] for s in manifest["secondaries"]} == {"coder", "ops"}
assert all(s["service"] == {"kind": "systemd", "system": False} for s in manifest["secondaries"])
assert _config_flag(fleet.root) is True
@@ -158,6 +179,7 @@ def test_apply_records_manifest_flips_flag_and_rollback_restores(fleet, capsys):
}
runtime_path.write_text(json.dumps(runtime), encoding="utf-8")
fleet.ops.clear()
+ gm._write_manifest(fleet.root, manifest) # the compensator only ever runs on a FAILED apply
assert gm.rollback_migration(fleet.root) is True
assert _config_flag(fleet.root) is False
assert fleet.services == {"default": ("systemd", False), "coder": ("systemd", False), "ops": ("systemd", False)}
@@ -205,7 +227,8 @@ def test_migration_preserves_root_system_service_user_for_default_install(fleet,
def test_rollback_with_failed_secondary_still_restarts_default_and_keeps_manifest(fleet, monkeypatch):
- assert gm.apply_migration(gm.build_migration_plan(), served_wait=5.0) is True
+ ok, _manifest = _apply_capturing_manifest(gm.build_migration_plan(), restore=True)
+ assert ok is True
fleet.ops.clear()
real_op = gm._service_op
@@ -241,45 +264,6 @@ def test_malformed_manifest_is_refused_before_any_mutation(fleet, capsys):
assert gm.rollback_migration(fleet.root) is False
assert _config_flag(fleet.root) is None and fleet.ops == []
assert "fix or delete the manifest" in capsys.readouterr().out
- gm.cmd_migrate(SimpleNamespace(multiplex=False, standalone=True, dry_run=True, yes=True))
- assert "fix or delete the manifest" in capsys.readouterr().out
-
-
-def test_rollback_plan_and_execution_agree_on_a_secondary_with_nothing_recorded(fleet, capsys):
- gm._write_manifest(fleet.root, {"version": 1, "flag_was": False, "default": {"service": None}, "secondaries": [
- {"profile": "coder", "home": str(fleet.root / "profiles/coder"), "pid": None, "service": None}]})
- fleet.services.clear()
- fleet.pids.clear()
- plan = "\n".join(gm.format_rollback_plan(fleet.root, gm._read_manifest(fleet.root), dry_run=True))
- assert gm.rollback_migration(fleet.root) is True
- out = capsys.readouterr().out
- # The plan must not promise an action the run never performs: both name the same outcome.
- plan_line = next(line.split("coder: ", 1)[1] for line in plan.splitlines() if "coder: " in line)
- assert plan_line in out and "restore" not in plan_line.split(";")[0]
- assert fleet.ops == []
-
-
-def test_standalone_dry_run_prints_rollback_plan_without_mutation(fleet, capsys):
- assert gm.apply_migration(gm.build_migration_plan(), served_wait=5.0) is True
- capsys.readouterr()
- fleet.ops.clear()
- before = {
- path: path.read_bytes()
- for path in (
- fleet.root / "config.yaml",
- fleet.root / gm.MANIFEST_NAME,
- fleet.root / "gateway_state.json",
- )
- }
- services_before = dict(fleet.services)
- pids_before = dict(fleet.pids)
-
- gm.cmd_migrate(SimpleNamespace(multiplex=False, standalone=True, dry_run=True, yes=True))
-
- out = capsys.readouterr().out
- assert "Rollback plan (dry run" in out and "coder" in out and "ops" in out
- assert all(path.read_bytes() == contents for path, contents in before.items())
- assert fleet.services == services_before and fleet.pids == pids_before and fleet.ops == []
def test_secondary_port_binder_is_notice_with_ingress_and_blocker_without(fleet, monkeypatch):
@@ -316,11 +300,11 @@ def test_update_hook_migrates_when_unblocked_and_only_warns_when_blocked(fleet,
gm.maybe_auto_migrate_after_update()
out = capsys.readouterr().out
assert "Migrating per-profile gateways" in out and "serves 3 profiles" in out
- assert _config_flag(fleet.root) is True and (fleet.root / gm.MANIFEST_NAME).exists()
+ assert _config_flag(fleet.root) is True and not (fleet.root / gm.MANIFEST_NAME).exists()
# Blocked fleet: warning block with the fix + one-liner; nothing changes.
for f in ("gateway.pid", "gateway_state.json", gm.MANIFEST_NAME):
- (fleet.root / f).unlink()
+ (fleet.root / f).unlink(missing_ok=True)
(fleet.root / "config.yaml").write_text("model:\n default: x\n", encoding="utf-8")
fleet.services.update({"coder": ("systemd", False), "default": ("systemd", False)})
fleet.pids.update({"coder": 4101}); fleet.ops.clear()
@@ -372,7 +356,7 @@ def test_update_hook_refuses_to_cross_service_user_or_home_boundary(
plan = gm.build_migration_plan()
assert not plan.blocked and any(expected in n for n in plan.notices)
- gm.cmd_migrate(SimpleNamespace(multiplex=True, standalone=False, dry_run=True, yes=True))
+ gm.cmd_migrate(SimpleNamespace(multiplex=True, dry_run=True, yes=True))
assert expected in capsys.readouterr().out
@@ -420,9 +404,9 @@ def test_auto_multiplex_migration_false_opts_out_of_the_update_hook_but_not_the_
(fleet.root / "config.yaml").write_text(
"model:\n default: x\ngateway:\n auto_multiplex_migration: false\n", encoding="utf-8")
with pytest.raises(SystemExit) as exc:
- gm.cmd_migrate(SimpleNamespace(multiplex=True, standalone=False, dry_run=False, yes=True))
+ gm.cmd_migrate(SimpleNamespace(multiplex=True, dry_run=False, yes=True))
assert exc.value.code == 0
- assert _config_flag(fleet.root) is True and (fleet.root / gm.MANIFEST_NAME).exists()
+ assert _config_flag(fleet.root) is True and not (fleet.root / gm.MANIFEST_NAME).exists()
def test_explicit_migrate_with_no_standalone_secondaries_still_flips_flag_and_restarts_default(fleet, capsys, monkeypatch):
@@ -439,17 +423,24 @@ def test_explicit_migrate_with_no_standalone_secondaries_still_flips_flag_and_re
return True
monkeypatch.setattr(gm, "_spawn_detached_gateway", _detached)
assert not gm.build_migration_plan().standalone_secondaries
+ seen = {}
+ real_wait = gm._wait_for_served
+ monkeypatch.setattr(gm, "_wait_for_served", lambda home, exp, t: (
+ seen.setdefault("m", json.loads((home / gm.MANIFEST_NAME).read_text(encoding="utf-8"))),
+ real_wait(home, exp, t))[1])
with pytest.raises(SystemExit) as exc:
- gm.cmd_migrate(SimpleNamespace(multiplex=True, standalone=False, dry_run=False, yes=True))
+ gm.cmd_migrate(SimpleNamespace(multiplex=True, dry_run=False, yes=True))
assert exc.value.code == 0
+ manifest = seen["m"]
assert fleet.services.pop("default-detached") is True
assert _config_flag(fleet.root) is True
- manifest = json.loads((fleet.root / gm.MANIFEST_NAME).read_text(encoding="utf-8"))
+ assert not (fleet.root / gm.MANIFEST_NAME).exists()
assert manifest["secondaries"] == [] and manifest["flag_was"] is False
assert ("default", "install") not in fleet.ops
out = capsys.readouterr().out
assert "serves 3 profiles" in out
- # The same manifest rolls it back: flag restored, nothing to reinstall.
+ # That same manifest is what the compensator would have used: flag restored, nothing to reinstall.
+ gm._write_manifest(fleet.root, manifest)
assert gm.rollback_migration(fleet.root) is True and _config_flag(fleet.root) is False
@@ -466,7 +457,7 @@ def test_failed_default_bringup_rolls_back_to_per_profile_gateways(fleet, monkey
monkeypatch.setattr(gm, "_service_op", _refusing)
assert gm.apply_migration(gm.build_migration_plan(), served_wait=0.1) is False
out = capsys.readouterr().out
- assert "Rolling back" in out and "Rolled back" in out
+ assert "Restoring the per-profile gateways" in out and "Restored the per-profile gateways" in out
assert _config_flag(fleet.root) is False
assert fleet.services == {"coder": ("systemd", False), "ops": ("systemd", False)}
assert not (fleet.root / gm.MANIFEST_NAME).exists()
@@ -508,9 +499,9 @@ def test_every_installed_unit_of_a_secondary_is_removed_and_restored(fleet, caps
plan = gm.build_migration_plan()
coder = next(p for p in plan.standalone_secondaries if p.name == "coder")
assert coder.services == [("systemd", False), ("systemd", True)]
- assert gm.apply_migration(plan, served_wait=5.0) is True
+ ok, manifest = _apply_capturing_manifest(plan, restore=True)
+ assert ok is True
assert "coder" not in fleet.services
- manifest = json.loads((fleet.root / gm.MANIFEST_NAME).read_text(encoding="utf-8"))
coder_rec = next(r for r in manifest["secondaries"] if r["profile"] == "coder")
assert [(s["kind"], s["system"]) for s in coder_rec["services"]] == [("systemd", False), ("systemd", True)]
capsys.readouterr()
@@ -634,7 +625,7 @@ def test_failure_anywhere_in_the_destructive_phase_restores_the_removed_secondar
lambda home, value: (_ for _ in ()).throw(OSError("read-only config")) if value else real_flag(home, value))
assert gm.apply_migration(gm.build_migration_plan(), served_wait=0.1) is False
out = capsys.readouterr().out
- assert "Rolling back" in out and "Rolled back" in out
+ assert "Restoring the per-profile gateways" in out and "Restored the per-profile gateways" in out
assert _config_flag(fleet.root) is not True
assert fleet.services == {"coder": ("systemd", False), "ops": ("systemd", False)}
assert not (fleet.root / gm.MANIFEST_NAME).exists()
@@ -687,3 +678,127 @@ def test_unknown_default_system_principal_blocks_the_update_hook(fleet, tmp_path
assert auto_migration_blockers(gm.build_migration_plan()) == []
monkeypatch.setattr(gm, "_gateway_identity", lambda home, pid, services: (0 if _name(home) == "default" else 1000, home))
assert any("UNIX privilege boundary" in b for b in auto_migration_blockers(gm.build_migration_plan()))
+
+
+# --------------------------------------------------------------------------- multiplex-only convergence
+
+
+def test_migrate_leaves_exactly_one_host_unit_serving_every_profile_and_is_idempotent(fleet, capsys):
+ """(a) Two per-profile units in, ONE host unit out, and a second run changes nothing.
+
+ The unit count is the contract: multiplex-only means one supervisor unit per host, not one per
+ profile, and the host gateway must report every profile as served.
+ """
+ fleet.services["default"] = ("systemd", False)
+ assert len(fleet.services) == 3 # default + the two per-profile units
+ with pytest.raises(SystemExit) as exc:
+ gm.cmd_migrate(SimpleNamespace(multiplex=True, dry_run=False, yes=True))
+ assert exc.value.code == 0
+ assert fleet.services == {"default": ("systemd", False)}
+ assert fleet.pids == {}
+ served = json.loads((fleet.root / "gateway_state.json").read_text(encoding="utf-8"))["served_profiles"]
+ assert sorted(served) == ["coder", "default", "ops"]
+ capsys.readouterr()
+
+ fleet.ops.clear()
+ plan = gm.build_migration_plan()
+ assert plan.already_multiplexed and not plan.standalone_secondaries
+ gm.cmd_migrate(SimpleNamespace(multiplex=True, dry_run=False, yes=True)) # returns, no exit
+ assert fleet.ops == [] and fleet.services == {"default": ("systemd", False)}
+ assert "already multiplexing" in capsys.readouterr().out
+
+
+def test_half_migrated_host_converges_on_a_re_run(fleet, capsys):
+ """(b) Flag already on, a per-profile unit + live gateway still there: the re-run must converge.
+
+ This is the upgrade shape — a migration that died after the flag write, or a unit an operator
+ reinstalled by hand. Reading the FLAG as "already multiplexed" made the re-run a no-op on
+ exactly the host that still had two gateways.
+ """
+ (fleet.root / "config.yaml").write_text(
+ "model:\n default: x\ngateway:\n multiplex_profiles: true\n", encoding="utf-8")
+ fleet.services = {"default": ("systemd", False), "coder": ("systemd", False)}
+ fleet.pids = {"coder": 4101}
+
+ plan = gm.build_migration_plan()
+ assert plan.multiplex_flag_on is True
+ assert not plan.already_multiplexed, "a host with a live per-profile gateway is not converged"
+ assert [p.name for p in plan.standalone_secondaries] == ["coder"]
+
+ with pytest.raises(SystemExit) as exc:
+ gm.cmd_migrate(SimpleNamespace(multiplex=True, dry_run=False, yes=True))
+ assert exc.value.code == 0
+ assert fleet.services == {"default": ("systemd", False)} and fleet.pids == {}
+ out = capsys.readouterr().out
+ assert "Half-migrated host" in out and "serves 3 profiles" in out
+ assert gm.build_migration_plan().already_multiplexed
+
+
+def test_plan_names_every_process_it_will_sigterm_before_it_signals_anything(fleet, capsys):
+ """A running gateway is never stopped silently: the dry run names the pids and changes nothing."""
+ gm.cmd_migrate(SimpleNamespace(multiplex=True, dry_run=True, yes=True))
+ out = capsys.readouterr().out
+ assert "SIGTERM" in out and "coder (pid 4101)" in out and "ops (pid 4102)" in out
+ assert fleet.ops == [] and fleet.pids == {"coder": 4101, "ops": 4102}
+
+
+def test_there_is_no_standalone_rollback_command(fleet):
+ """(3) ``--standalone`` is gone from the parser: per-profile gateways are not a supported target."""
+ import argparse
+ from hermes_cli.subcommands.gateway import build_gateway_parser
+ parser = argparse.ArgumentParser()
+ build_gateway_parser(parser.add_subparsers(dest="command"),
+ cmd_gateway=lambda a: None, cmd_proxy=lambda a: None,
+ cmd_gateway_enroll=lambda a: None)
+ with pytest.raises(SystemExit):
+ parser.parse_args(["gateway", "migrate", "--standalone"])
+ args = parser.parse_args(["gateway", "migrate", "--multiplex", "--dry-run"])
+ assert args.multiplex and args.dry_run and not hasattr(args, "standalone")
+
+
+def test_a_windows_scheduled_task_secondary_is_detected_and_removed(fleet, monkeypatch, capsys):
+ """Windows was refused outright ("not migrated automatically"), which left Windows users with
+ no convergence path at all. The task (or its Startup-folder fallback) counts as an installed
+ per-profile gateway, and is removed through the same service seam as a systemd unit."""
+ from hermes_cli import gateway as gw
+ monkeypatch.setattr(gw, "is_windows", lambda: True)
+ monkeypatch.setattr(gw, "is_macos", lambda: False)
+ monkeypatch.setattr(gw, "is_linux", lambda: False)
+
+ fleet.services = {"coder": ("windows", False), "ops": ("windows", False)}
+ plan = gm.build_migration_plan()
+ assert [p.service_label() for p in plan.standalone_secondaries] == [
+ "Windows scheduled task", "Windows scheduled task"]
+ assert "Windows scheduled task" in "\n".join(gm.format_plan(plan, dry_run=True))
+
+ assert gm.apply_migration(plan, served_wait=5.0) is True
+ assert fleet.services == {"default": ("windows", False)}, "one host task, both secondaries gone"
+ assert ("coder", "uninstall") in fleet.ops and ("ops", "uninstall") in fleet.ops
+ assert "serves 3 profiles" in capsys.readouterr().out
+
+
+def test_windows_task_detection_reads_both_the_task_and_the_startup_fallback(monkeypatch):
+ """`hermes gateway install` falls back to a Startup-folder entry when it cannot register a
+ task; a migration that removed only the task would leave that entry launching a second
+ gateway at the next logon."""
+ from hermes_cli import gateway_windows as gww
+ for task, startup, expected in ((True, False, True), (False, True, True), (False, False, False)):
+ monkeypatch.setattr(gww, "is_task_registered", lambda t=task: t)
+ monkeypatch.setattr(gww, "is_startup_entry_installed", lambda s=startup: s)
+ assert gm._windows_task_installed() is expected
+ # A schtasks failure is not evidence of a second gateway: fail closed to "not installed".
+ monkeypatch.setattr(gww, "is_task_registered", lambda: (_ for _ in ()).throw(OSError("schtasks")))
+ assert gm._windows_task_installed() is False
+
+
+def test_windows_is_migratable_and_only_s6_is_refused(monkeypatch):
+ """The host predicate: Windows used to be a flat refusal with hand-migration instructions.
+ s6 stays refused -- its per-profile gateways are slots the container's own boot registers."""
+ from hermes_cli import gateway as gw
+ monkeypatch.setattr(gw, "_running_under_s6", lambda: False)
+ assert gm._host_supports_migration() is None
+
+ monkeypatch.setattr(gw, "_running_under_s6", lambda: True)
+ reason = gm._host_supports_migration()
+ assert reason is not None and "Restart the container" in reason
+ assert "nothing on this host was changed" in reason
diff --git a/tests/hermes_cli/test_gateway_multiplex_mode.py b/tests/hermes_cli/test_gateway_multiplex_mode.py
index 73b22323f57..ca295cd69b7 100644
--- a/tests/hermes_cli/test_gateway_multiplex_mode.py
+++ b/tests/hermes_cli/test_gateway_multiplex_mode.py
@@ -94,7 +94,7 @@ def test_preflight_blocker_and_single_profile_keep_the_unset_default_standalone(
assert decision == mode.MultiplexDecision(False, "guard", mode.SINGLE_PROFILE_REASON)
-def test_explicit_flag_is_never_second_guessed(fleet, monkeypatch):
+def test_explicit_true_is_never_second_guessed_and_explicit_false_is_retired(fleet, monkeypatch):
root, _services, pids = fleet
pids["coder"] = 4101
(root / "config.yaml").write_text("gateway:\n multiplex_profiles: true\n", encoding="utf-8")
@@ -103,13 +103,23 @@ def test_explicit_flag_is_never_second_guessed(fleet, monkeypatch):
assert cfg.multiplex_profiles is True
assert mode.explicit_multiplex_flag(root) is True
+ # RETIRED opt-out: `false` still parses, but it can no longer pin a second gateway onto this
+ # host — with nothing blocking, the process multiplexes and says the key was ignored.
monkeypatch.setenv("GATEWAY_MULTIPLEX_PROFILES", "false")
pids.clear()
cfg = load_gateway_config()
- assert mode.resolve_multiplex_mode(cfg) == mode.MultiplexDecision(False, "config")
- assert cfg.multiplex_profiles is False
+ decision = mode.resolve_multiplex_mode(cfg)
+ assert decision.enabled is True and decision.source == "retired-opt-out"
+ assert cfg.multiplex_profiles is True
assert mode.explicit_multiplex_flag(root) is False
+ # ...and it still cannot force a fold that would double-bind: a secondary that owns a live
+ # gateway keeps this process standalone, with the blocker named (never a silent second bind).
+ pids["coder"] = 4101
+ cfg = load_gateway_config()
+ guarded = mode.resolve_multiplex_mode(cfg)
+ assert guarded.enabled is False and guarded.source == "guard" and "coder" in guarded.reason
+
def test_migration_plan_treats_the_unset_default_as_not_yet_multiplexed(fleet):
"""The fleet the boot guard refuses is exactly the one ``hermes gateway migrate --multiplex`` folds:
diff --git a/tui_gateway/launch_profile_policy.py b/tui_gateway/launch_profile_policy.py
index 6b1b3dc6121..53bc2650aa7 100644
--- a/tui_gateway/launch_profile_policy.py
+++ b/tui_gateway/launch_profile_policy.py
@@ -51,28 +51,6 @@ def activate_multi_profile_hosting() -> None:
set_multiplex_active(True)
-def _multiplex_disabled_explicitly() -> bool:
- """True when this host has deliberately turned multiplexing OFF.
-
- ``profiles_to_serve(multiplex=True)`` takes the flag as an argument and never reads config, so
- the eager gate must consult the operator's setting itself or it arms the fail-closed guard on
- hosts that pinned ``gateway.multiplex_profiles: false`` to keep per-profile gateways. Same
- precedence the gateway boot uses: ``GATEWAY_MULTIPLEX_PROFILES`` over config.yaml; unset means
- "not disabled" (the default is on, and the lazy backstop still fires either way).
- """
- from gateway.config import _coerce_bool, _env_multiplex_profiles_override
- env_override = _env_multiplex_profiles_override()
- if env_override is not None:
- return not env_override
- from hermes_cli.config import load_config
- cfg = load_config() or {}
- value = cfg.get("multiplex_profiles")
- gateway_cfg = cfg.get("gateway")
- if value is None and isinstance(gateway_cfg, dict):
- value = gateway_cfg.get("multiplex_profiles")
- return value is not None and not _coerce_bool(value, True)
-
-
def _servable_profile_homes() -> set:
"""Resolved homes this host could be asked to serve: the launch home plus every profile dir
carrying a real servability marker.
@@ -102,21 +80,19 @@ def activate_multi_profile_hosting_eagerly() -> bool:
boot step: the frozen snapshot is the only source for launch keys with no ``.env`` to rebuild
from, so every credential the boot still injects must already be in ``os.environ``.
+ ``gateway.multiplex_profiles: false`` is deliberately NOT consulted: it is retired as a
+ topology opt-out, and a multi-home host that skipped activation because of a stale ``false``
+ would serve a second profile with the LAUNCH profile's credentials — the exact fail-open this
+ guard exists to prevent.
+
A genuinely single-profile host still never activates (byte-identical behaviour, ``os.environ``
- precedence preserved), and so does one that pinned ``gateway.multiplex_profiles: false``. An
- unreadable profiles directory fails CLOSED: we cannot prove the host is single-profile, and the
- lazy backstop only fires once a request has already been answered. Returns True when this call
- activated hosting.
+ precedence preserved). An unreadable profiles directory fails CLOSED: we cannot prove the host
+ is single-profile, and the lazy backstop only fires once a request has already been answered.
+ Returns True when this call activated hosting.
"""
from agent.secret_scope import is_multiplex_active
if is_multiplex_active():
return False
- try:
- if _multiplex_disabled_explicitly():
- return False
- except Exception:
- logger.warning("Could not read gateway.multiplex_profiles; continuing with the profile probe",
- exc_info=True)
try:
homes = _servable_profile_homes()
except Exception: