Skip to content

The agent that grows with you

refactor(cron): trim the scope-degrade dispatch to its invariants

kshitijk4poorf003e449be7f
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 22031b6bb2a..6206ad81017 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -39,7 +39,7 @@ from hermes_constants import get_hermes_home
from cron.env_settings import cron_env_setting
from hermes_cli._subprocess_compat import windows_hide_flags
from hermes_cli.config import (
- _expand_env_vars, load_config, resolve_cron_model_drift_defaults)
+ _expand_env_vars, load_config, load_config_readonly, resolve_cron_model_drift_defaults)
from hermes_cli.fallback_config import get_fallback_chain
from hermes_time import now as _hermes_now
from agent.interrupt_compat import request_hard_interrupt
@@ -3052,15 +3052,11 @@ def _wait_for_external_cron_worker(
def _launch_external_cron_worker(job: dict) -> bool:
"""Launch *job* outside the managed gateway process when required.
- Returns ``False`` when the caller is not a managed systemd gateway and the
- existing in-process path should be used. In managed topology the job is
- always handed to an external worker with the #101940 ownership handoff:
- either inside a transient user scope (isolated) or - when no user D-Bus
- session exists and ``cron.require_restart_safe_scope`` is false (the
- default) - as a direct subprocess (process separation without cgroup
- isolation). Setting ``cron.require_restart_safe_scope: true`` restores
- fail-closed. Falling back to in-process in managed topology would
- recreate the restart interruption this handoff exists to prevent.
+ Returns ``False`` outside a managed systemd gateway (in-process path). In
+ managed topology the job always goes to an external worker with the #101940
+ ownership handoff: in a transient user scope, or — when no user D-Bus
+ session exists and ``cron.require_restart_safe_scope`` is false — as a
+ direct subprocess (process separation kept, cgroup isolation lost).
"""
execution_id = str(job["execution_id"])
job_id = str(job["id"])
@@ -3090,12 +3086,12 @@ def _launch_external_cron_worker(job: dict) -> bool:
systemd_user_bus_env,
)
- cfg = load_config() or {}
- require_restart_safe_scope = bool(
- ((cfg.get("cron") or {}) if isinstance(cfg, dict) else {}).get(
- "require_restart_safe_scope", False
+ try:
+ require_restart_safe_scope = bool(
+ (load_config_readonly().get("cron") or {}).get("require_restart_safe_scope", False)
)
- )
+ except Exception:
+ require_restart_safe_scope = False
multiplex_active = is_multiplex_active()
dispatch = restart_safe_gateway_child_argv(
command,
@@ -3103,16 +3099,7 @@ def _launch_external_cron_worker(job: dict) -> bool:
require_restart_safe_scope=require_restart_safe_scope,
)
if dispatch.mode == "in_process":
- # Not a managed systemd gateway: keep the existing in-process path.
return False
- # "scoped" AND "degraded" both launch an external worker with the same
- # #101940 ownership handoff below. Degraded only differs in isolation:
- # the direct command runs in the gateway cgroup (documented in the
- # warning), so a mid-job gateway restart kills it — but the execution
- # ledger still records exactly what happened (failed/unknown) instead of
- # the job silently never running. Never fall back to in-process here:
- # that would recreate the restart-interruption edge #101940 closed.
- launch_command = dispatch.argv
if mark_execution_handoff_pending(execution_id) is None:
raise RuntimeError(
@@ -3155,7 +3142,7 @@ def _launch_external_cron_worker(job: dict) -> bool:
worker_env = systemd_user_bus_env(worker_env)
try:
process = subprocess.Popen(
- launch_command,
+ dispatch.argv,
cwd=str(Path(__file__).resolve().parent.parent),
env=worker_env,
stdin=subprocess.DEVNULL,
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index d89e66d3682..7f850a54236 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -1705,12 +1705,9 @@ DEFAULT_CONFIG = {
# (long TTS audio, big exports) need more than 30s. Env: HERMES_CRON_MEDIA_SEND_TIMEOUT.
# Keep in sync with cron.scheduler._DEFAULT_MEDIA_SEND_TIMEOUT.
"media_send_timeout_seconds": 300,
- # Restart-safety policy when the managed gateway has no user systemd session
- # (containers/LXCs without linger): false (default) degrades cron jobs to a direct
- # external subprocess with a once-per-process warning - process separation kept,
- # cgroup isolation lost, a mid-job gateway restart kills the worker. True fails
- # closed with the enable-linger remedy. The Kanban dispatcher always requires a
- # scope regardless (see #102431).
+ # Managed systemd gateway with no user session (containers, no linger): false runs
+ # cron jobs as a direct external subprocess (warns once; no cgroup isolation), true
+ # fails closed with the enable-linger remedy. Kanban always requires a scope.
"require_restart_safe_scope": False,
},
# Kanban multi-agent coordination. The dispatcher ticks every N seconds, reclaims stale claims,
diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.py
index 6ab9ea83cc0..4312d9ccb9f 100644
--- a/hermes_cli/kanban_db_dispatch.py
+++ b/hermes_cli/kanban_db_dispatch.py
@@ -2148,10 +2148,8 @@ def _open_worker_log(task: Task, board: Optional[str]):
def _restart_safe_worker_argv(task: Task, command: list[str]) -> list[str]:
"""Wrap a managed-gateway worker in the shared restart-safe scope.
- Kanban workers are long-lived agentic runs, so unlike bounded cron jobs
- they are never dispatched in the degraded (unsupervised) mode: a managed
- gateway with no user systemd session fails closed through the shared
- helper's raise (remedy text included). See #102431.
+ Kanban workers are long-lived agentic runs, so they never take cron's
+ degraded mode: ``require_restart_safe_scope=True`` makes the helper raise.
"""
from tools.process_registry import restart_safe_gateway_child_argv
@@ -2164,7 +2162,7 @@ def _restart_safe_worker_argv(task: Task, command: list[str]) -> list[str]:
unit_suffix=f"kanban-{task.id}-run-missing",
require_restart_safe_scope=True,
)
- if dispatch.mode == "scoped":
+ if dispatch.mode != "in_process":
raise RuntimeError(
"cannot create restart-safe systemd scope for Kanban worker: "
"the claimed task has no current run id"
diff --git a/tests/cron/test_restart_safe_worker.py b/tests/cron/test_restart_safe_worker.py
index 6b6df0a381d..446384f4059 100644
--- a/tests/cron/test_restart_safe_worker.py
+++ b/tests/cron/test_restart_safe_worker.py
@@ -94,53 +94,26 @@ def test_restart_safe_gateway_child_fails_closed_when_required(monkeypatch):
@pytest.mark.linux_only
-def test_restart_safe_gateway_child_degrades_without_scope(monkeypatch):
- """Managed gateway + no user bus degrades to a distinguishable state.
-
- The degraded dispatch must NOT be identical to the in-process passthrough:
- the scheduler launches it as an external subprocess (with the #101940
- ownership handoff), never in-process. See #102431 review.
- """
+def test_restart_safe_gateway_child_degrades_without_scope(monkeypatch, caplog):
+ """Managed gateway + no user bus degrades to a mode distinct from the
+ in-process passthrough, and warns once per process, not per dispatch."""
import tools.process_registry as process_registry
monkeypatch.setattr(process_registry, "_is_supervised_gateway_process", lambda: True)
monkeypatch.setenv("INVOCATION_ID", "managed-service")
monkeypatch.setattr(process_registry, "_systemd_run_user_scope_available", lambda: False)
+ monkeypatch.setattr(process_registry, "_scope_degraded_warned", False)
command = ["python", "worker.py"]
- dispatch = process_registry.restart_safe_gateway_child_argv(
- command, unit_suffix="cron-job-1", require_restart_safe_scope=False
- )
+ with caplog.at_level("WARNING", logger=process_registry.logger.name):
+ for _ in range(2):
+ dispatch = process_registry.restart_safe_gateway_child_argv(
+ command, unit_suffix="cron-job-1", require_restart_safe_scope=False
+ )
assert dispatch.mode == "degraded"
assert dispatch.argv == command
- assert dispatch.reason == "no-user-bus"
-
-
-def test_restart_safe_gateway_child_scoped_and_in_process_modes(monkeypatch):
- import tools.process_registry as process_registry
-
- command = ["python", "worker.py"]
- # Managed + working bus -> scoped wrapper.
- monkeypatch.setattr(process_registry, "_is_supervised_gateway_process", lambda: True)
- monkeypatch.setenv("INVOCATION_ID", "managed-service")
- monkeypatch.setattr(process_registry, "_systemd_run_user_scope_available", lambda: True)
- monkeypatch.setattr(
- process_registry, "_build_systemd_scope_argv",
- lambda cmd, unit_suffix: ["scope", "--", *cmd],
- )
- scoped = process_registry.restart_safe_gateway_child_argv(
- command, unit_suffix="cron-job-1", require_restart_safe_scope=False
- )
- assert scoped.mode == "scoped"
- assert scoped.argv == ["scope", "--", "python", "worker.py"]
- # Outside managed topology -> in-process passthrough (identity preserved).
- monkeypatch.setattr(process_registry, "_is_supervised_gateway_process", lambda: False)
- passthrough = process_registry.restart_safe_gateway_child_argv(
- command, unit_suffix="cron-job-1", require_restart_safe_scope=False
- )
- assert passthrough.mode == "in_process"
- assert passthrough.argv is command
+ warnings = [r for r in caplog.records if "without restart-safe cgroup isolation" in r.getMessage()]
+ assert len(warnings) == 1
def test_restart_safe_gateway_child_is_unchanged_outside_managed_gateway(monkeypatch):
@@ -240,28 +213,11 @@ def test_external_worker_refuses_to_run_without_durable_ownership(
assert not ack.exists()
-def test_launch_external_worker_uses_restart_safe_scope_and_acknowledges(
- tmp_path, monkeypatch
-):
- import cron.scheduler as scheduler
- from tools.env_passthrough import clear_env_passthrough, register_env_passthrough
-
- job = {"id": "job-1", "execution_id": "exec-1", "prompt": "work"}
- monkeypatch.setattr(scheduler, "_get_hermes_home", lambda: tmp_path)
- (tmp_path / ".env").write_text(
- "SERVICE_TOKEN=target-profile-token\n", encoding="utf-8"
- )
- register_env_passthrough(["SERVICE_TOKEN"])
- wrapped_commands = []
- from tools.process_registry import GatewayChildDispatch
+def _stub_external_worker_launch(scheduler, monkeypatch):
+ """Fake Popen that acks the handoff and reports running -> completed.
- def wrap(command, *, unit_suffix, require_restart_safe_scope=False):
- wrapped_commands.append((command, unit_suffix))
- return GatewayChildDispatch("scoped", ["scope", "--", *command])
-
- monkeypatch.setattr(
- "tools.process_registry.restart_safe_gateway_child_argv", wrap
- )
+ Returns ``(spawned, payloads, handoff, get)`` for the caller's assertions.
+ """
class FakeProcess:
returncode = None
@@ -275,7 +231,6 @@ def test_launch_external_worker_uses_restart_safe_scope_and_acknowledges(
return self.returncode
spawned = []
-
payloads = []
def popen(command, **kwargs):
@@ -300,6 +255,33 @@ def test_launch_external_worker_uses_restart_safe_scope_and_acknowledges(
)
get = Mock(side_effect=lambda _execution_id: next(observed_statuses))
monkeypatch.setattr(scheduler, "get_execution", get)
+ return spawned, payloads, handoff, get
+
+
+def test_launch_external_worker_uses_restart_safe_scope_and_acknowledges(
+ tmp_path, monkeypatch
+):
+ import cron.scheduler as scheduler
+ from tools.env_passthrough import clear_env_passthrough, register_env_passthrough
+
+ job = {"id": "job-1", "execution_id": "exec-1", "prompt": "work"}
+ monkeypatch.setattr(scheduler, "_get_hermes_home", lambda: tmp_path)
+ (tmp_path / ".env").write_text(
+ "SERVICE_TOKEN=target-profile-token\n", encoding="utf-8"
+ )
+ register_env_passthrough(["SERVICE_TOKEN"])
+ wrapped_commands = []
+ from tools.process_registry import GatewayChildDispatch
+
+ def wrap(command, *, unit_suffix, require_restart_safe_scope=False):
+ wrapped_commands.append((command, unit_suffix))
+ return GatewayChildDispatch("scoped", ["scope", "--", *command])
+
+ monkeypatch.setattr(
+ "tools.process_registry.restart_safe_gateway_child_argv", wrap
+ )
+
+ spawned, payloads, handoff, get = _stub_external_worker_launch(scheduler, monkeypatch)
monkeypatch.setenv("ANTHROPIC_API_KEY", "should-not-cross-profile")
monkeypatch.setenv("SERVICE_TOKEN", "default-profile-token")
from agent.secret_scope import set_multiplex_active
@@ -394,159 +376,29 @@ def test_launch_external_worker_stays_in_process_outside_managed_gateway(
popen.assert_not_called()
-def test_launch_external_worker_dispatches_degraded_case_as_external_subprocess(
- tmp_path, monkeypatch,
-):
- """Managed gateway + no user bus: the job MUST still Popen externally.
-
- Regression for the #102431 review blocker: the degraded dispatch must
- take the external-worker path (payload written, handoff fenced, Popen
- called with the direct command) — never silently fall back in-process.
- """
- import cron.scheduler as scheduler
- from tools.process_registry import GatewayChildDispatch
-
- job = {"id": "job-1", "execution_id": "exec-1", "prompt": "work"}
- monkeypatch.setattr(scheduler, "_get_hermes_home", lambda: tmp_path)
-
- def degraded(command, *, unit_suffix, require_restart_safe_scope=False):
- assert unit_suffix == "cron-job-1-exec-exec-1"
- return GatewayChildDispatch("degraded", command, "no-user-bus")
-
- monkeypatch.setattr(
- "tools.process_registry.restart_safe_gateway_child_argv", degraded
- )
-
- class FakeProcess:
- returncode = None
-
- def poll(self):
- return self.returncode
-
- def wait(self, timeout=None):
- if self.returncode is None:
- raise subprocess.TimeoutExpired(cmd="worker", timeout=timeout)
- return self.returncode
-
- spawned = []
-
- def popen(command, **kwargs):
- spawned.append((command, kwargs))
- assert command[0:2] == [sys.executable, "-m"], command[:3]
- assert "--external-worker-file" in command
- payload_index = command.index("--external-worker-file") + 1
- payload = json.loads(Path(command[payload_index]).read_text())
- assert payload["job"]["id"] == "job-1"
- ack_index = command.index("--ack-file") + 1
- Path(command[ack_index]).write_text(
- json.dumps({"pid": 4321, "execution_id": "exec-1"}),
- encoding="utf-8",
- )
- return FakeProcess()
-
- handoff = Mock(return_value={"id": "exec-1", "handoff_pending": 1})
- monkeypatch.setattr(scheduler, "mark_execution_handoff_pending", handoff)
- monkeypatch.setattr(scheduler.subprocess, "Popen", popen)
- observed_statuses = iter(
- [
- {"id": "exec-1", "status": "running"},
- {"id": "exec-1", "status": "completed"},
- ]
- )
- get = Mock(side_effect=lambda _execution_id: next(observed_statuses))
- monkeypatch.setattr(scheduler, "get_execution", get)
-
- assert scheduler._launch_external_cron_worker(job) is True
- # Direct command, NOT a systemd-run wrapper — but still an external Popen.
- assert "systemd-run" not in " ".join(spawned[0][0])
- assert spawned[0][1]["start_new_session"] is True
- handoff.assert_called_once_with("exec-1")
- assert not (tmp_path / "cron/external-workers/exec-1.json").exists()
-
-
-def test_launch_external_worker_fails_closed_when_config_requires_scope(monkeypatch):
- """cron.require_restart_safe_scope=true restores the fail-closed raise
- through the real helper (config plumbing, not a stubbed dispatch)."""
- import cron.scheduler as scheduler
- import tools.process_registry as process_registry
-
- monkeypatch.setattr(
- scheduler, "load_config",
- lambda: {"cron": {"require_restart_safe_scope": True}},
- )
- monkeypatch.setattr(process_registry, "_is_supervised_gateway_process", lambda: True)
- monkeypatch.setenv("INVOCATION_ID", "managed-service")
- monkeypatch.setattr(process_registry, "_systemd_run_user_scope_available", lambda: False)
- popen = Mock()
- monkeypatch.setattr(scheduler.subprocess, "Popen", popen)
-
- with pytest.raises(RuntimeError, match="systemd-run --user --scope is unavailable"):
- scheduler._launch_external_cron_worker(
- {"id": "job-1", "execution_id": "exec-1", "prompt": "work"}
- )
- popen.assert_not_called()
-
-
def test_launch_external_worker_degrades_by_default_with_real_helper(
tmp_path, monkeypatch,
):
- """Managed gateway + no bus + default config (key absent): the real helper
- degrades and the job still Popens externally with the #101940 handoff.
-
- Exercises the config default end-to-end (cron.require_restart_safe_scope
- defaults to false), not a stubbed dispatch.
- """
+ """Managed gateway + no bus, through the real helper and real config
+ plumbing: the default still Popens the job externally with the #101940
+ handoff (never in-process)."""
import cron.scheduler as scheduler
import tools.process_registry as process_registry
job = {"id": "job-1", "execution_id": "exec-1", "prompt": "work"}
monkeypatch.setattr(scheduler, "_get_hermes_home", lambda: tmp_path)
- monkeypatch.setattr(scheduler, "load_config", lambda: {})
+ monkeypatch.setattr(scheduler, "load_config_readonly", lambda: {})
monkeypatch.setattr(process_registry, "_is_supervised_gateway_process", lambda: True)
monkeypatch.setenv("INVOCATION_ID", "managed-service")
monkeypatch.setattr(process_registry, "_systemd_run_user_scope_available", lambda: False)
-
- class FakeProcess:
- returncode = None
-
- def poll(self):
- return self.returncode
-
- def wait(self, timeout=None):
- if self.returncode is None:
- raise subprocess.TimeoutExpired(cmd="worker", timeout=timeout)
- return self.returncode
-
- spawned = []
-
- def popen(command, **kwargs):
- spawned.append((command, kwargs))
- payload_index = command.index("--external-worker-file") + 1
- payload = json.loads(Path(command[payload_index]).read_text())
- assert payload["job"]["id"] == "job-1"
- ack_index = command.index("--ack-file") + 1
- Path(command[ack_index]).write_text(
- json.dumps({"pid": 4321, "execution_id": "exec-1"}),
- encoding="utf-8",
- )
- return FakeProcess()
-
- handoff = Mock(return_value={"id": "exec-1", "handoff_pending": 1})
- monkeypatch.setattr(scheduler, "mark_execution_handoff_pending", handoff)
- monkeypatch.setattr(scheduler.subprocess, "Popen", popen)
- observed_statuses = iter(
- [
- {"id": "exec-1", "status": "running"},
- {"id": "exec-1", "status": "completed"},
- ]
- )
- get = Mock(side_effect=lambda _execution_id: next(observed_statuses))
- monkeypatch.setattr(scheduler, "get_execution", get)
+ spawned, payloads, handoff, _get = _stub_external_worker_launch(scheduler, monkeypatch)
assert scheduler._launch_external_cron_worker(job) is True
# Direct command, NOT a systemd-run wrapper — but still an external Popen.
assert "systemd-run" not in " ".join(spawned[0][0])
assert spawned[0][1]["start_new_session"] is True
+ assert payloads[0]["job"]["id"] == "job-1"
handoff.assert_called_once_with("exec-1")
assert not (tmp_path / "cron/external-workers/exec-1.json").exists()
diff --git a/tools/process_registry.py b/tools/process_registry.py
index d1a9b2efa87..40e733a335b 100644
--- a/tools/process_registry.py
+++ b/tools/process_registry.py
@@ -291,62 +291,37 @@ def _build_systemd_scope_argv(shell_argv: List[str], unit_suffix: str) -> List[s
return _systemd_scope_argv(binary, f"hermes-worker-{unit_suffix}", *shell_argv)
-# --- restart-safe gateway child dispatch --------------------------------------
-# A systemd-supervised gateway restart kills every process in the service cgroup, so
-# children that must survive it are launched outside that cgroup via a transient user
-# scope (systemd-run --user --scope) when one can be created. Hosts with no user
-# systemd session at all (containers, LXCs without linger) cannot create scopes; the
-# callers set policy explicitly through ``require_restart_safe_scope`` (cron reads
-# ``cron.require_restart_safe_scope`` from config.yaml; kanban always requires a scope).
-
_scope_degraded_warned = False
-def _warn_scope_degraded_once(unit_suffix: str) -> None:
- """Emit the degrade warning once per process.
-
- The scope-availability verdict is cached, so without this guard the warning
- would fire on every dispatch (every cron fire on a bus-less host).
- """
+def _warn_scope_degraded_once(unit_suffix: str, detail: str) -> None:
+ """Warn once per process: the probe verdict is cached, so this would otherwise
+ fire on every cron dispatch on a bus-less host."""
global _scope_degraded_warned
if _scope_degraded_warned:
return
_scope_degraded_warned = True
logger.warning(
- "%s: systemd-run --user --scope is unavailable (no user D-Bus session at "
- "/run/user/%d/bus); dispatching the gateway child as a direct external "
- "subprocess without restart-safe cgroup isolation. The job still runs "
- "outside the gateway process, but will be killed if the gateway restarts "
- "mid-job. Remediate with `sudo loginctl enable-linger <gateway-user>` (plus "
- "XDG_RUNTIME_DIR/DBUS_SESSION_BUS_ADDRESS in the service unit), or set "
- "cron.require_restart_safe_scope=true in config.yaml to fail closed instead.",
- unit_suffix, os.getuid(),
+ "%s: %s; dispatching the gateway child as a direct external subprocess "
+ "without restart-safe cgroup isolation (killed if the gateway restarts mid-job). "
+ "Set cron.require_restart_safe_scope=true in config.yaml to fail closed instead.",
+ unit_suffix, detail,
)
class GatewayChildDispatch(NamedTuple):
- """How a managed-gateway child should be launched.
-
- Three mutually exclusive topologies - the whole point of this type is
- that (1) and (3) must never collapse into the same value:
-
- - ``"in_process"`` - not a managed systemd gateway (standalone process,
- non-systemd supervisor, non-Linux host). The caller keeps its existing
- in-process path. ``argv is command`` holds, preserving the historical
- passthrough contract.
- - ``"scoped"`` - managed gateway with a working user bus. ``argv`` is the
- ``systemd-run --user --scope`` wrapper; the caller launches it as an
- external worker with the #101940 ownership handoff.
- - ``"degraded"`` - managed gateway WITHOUT a user bus. ``argv`` is the
- direct command, but the caller MUST still launch it as an external
- subprocess (same ownership handoff as ``"scoped"``) - never fall back
- to the in-process path, which would recreate the restart-interruption
- edge #101940 closed. Isolation is lost but process separation is kept.
+ """How a managed-gateway child is launched.
+
+ ``in_process``: not a managed systemd gateway, ``argv is command``, the caller
+ keeps its in-process path. ``scoped``: ``argv`` is the systemd-run wrapper.
+ ``degraded``: no user scope could be created; ``argv`` is the direct command but
+ the caller MUST still launch it as an external subprocess — the distinct mode
+ exists so this case can never collapse into ``in_process`` and recreate the
+ restart interruption #101940 closed.
"""
mode: Literal["in_process", "scoped", "degraded"]
argv: List[str]
- reason: str = ""
def restart_safe_gateway_child_argv(
@@ -354,51 +329,35 @@ def restart_safe_gateway_child_argv(
) -> GatewayChildDispatch:
"""Place a managed-systemd gateway child outside the gateway cgroup.
- Returns a :class:`GatewayChildDispatch` distinguishing three topologies -
- never the bare command list, so callers cannot mistake a degraded dispatch
- for "not managed, stay in-process".
-
- Children that must survive an intentional gateway restart cannot rely on
- ``start_new_session`` alone: systemd still kills every process in the
- service cgroup. In that topology, prefer a transient user scope.
-
- When a user systemd session is genuinely absent (containers, minimal LXCs,
- macOS-style supervisors) the scope cannot be created, but hard failing takes
- down every scheduled job on the host - a silent cron outage with no
- operator-visible symptom beyond skipped executions (the #101940 durability
- contract covers the restart case, not the never-had-a-bus case). Callers
- therefore state their policy explicitly: ``require_restart_safe_scope=True``
- raises when no scope can be established (fail-closed, the kanban contract);
- ``False`` degrades to a direct external subprocess with a once-per-process
- warning (the cron default behind ``cron.require_restart_safe_scope``).
-
- Standalone processes, non-systemd supervisors, and non-Linux hosts return
- ``mode == "in_process"`` - the caller keeps its existing in-process path.
+ A systemd-supervised gateway restart kills every process in the service
+ cgroup, so children that must survive it run in a transient user scope.
+ Hosts with no user systemd session (containers, LXCs without linger) cannot
+ create one; hard-failing there is a silent cron outage, so callers state the
+ policy: ``require_restart_safe_scope=True`` raises (kanban's long-lived
+ workers), ``False`` degrades to a direct external subprocess with a
+ once-per-process warning (cron, behind ``cron.require_restart_safe_scope``).
"""
if not _IS_LINUX:
return GatewayChildDispatch("in_process", command)
if not _is_supervised_gateway_process() or not os.environ.get("INVOCATION_ID"):
return GatewayChildDispatch("in_process", command)
- if not _systemd_run_user_scope_available():
+
+ def _degrade(detail: str) -> GatewayChildDispatch:
if require_restart_safe_scope:
# Stored as the cron execution's error and shown on the job row: name the remedy.
- raise RuntimeError(
- "cannot create restart-safe systemd scope for gateway child: "
- "systemd-run --user --scope is unavailable (usually no reachable user D-Bus session at "
- f"/run/user/{os.getuid()}/bus). On a system-level service install, run " # windows-footgun: ok — behind the _IS_LINUX return above
- "`sudo loginctl enable-linger <gateway-user>` and restart the gateway."
- )
- _warn_scope_degraded_once(unit_suffix)
- return GatewayChildDispatch("degraded", command, "no-user-bus")
+ raise RuntimeError(f"cannot create restart-safe systemd scope for gateway child: {detail}")
+ _warn_scope_degraded_once(unit_suffix, detail)
+ return GatewayChildDispatch("degraded", command)
+
+ if not _systemd_run_user_scope_available():
+ return _degrade(
+ "systemd-run --user --scope is unavailable (usually no reachable user D-Bus session at "
+ f"/run/user/{os.getuid()}/bus). On a system-level service install, run " # windows-footgun: ok — behind the _IS_LINUX return above
+ "`sudo loginctl enable-linger <gateway-user>` and restart the gateway."
+ )
scoped = _build_systemd_scope_argv(command, unit_suffix=unit_suffix)
if scoped == command:
- if require_restart_safe_scope:
- raise RuntimeError(
- "cannot create restart-safe systemd scope for gateway child: "
- "systemd-run disappeared after the availability probe"
- )
- _warn_scope_degraded_once(unit_suffix)
- return GatewayChildDispatch("degraded", command, "scope-binary-vanished")
+ return _degrade("systemd-run disappeared after the availability probe")
return GatewayChildDispatch("scoped", scoped)
diff --git a/website/docs/user-guide/features/cron.md b/website/docs/user-guide/features/cron.md
index 4ad4bc28275..a49dc7ec033 100644
--- a/website/docs/user-guide/features/cron.md
+++ b/website/docs/user-guide/features/cron.md
@@ -329,6 +329,19 @@ On each tick Hermes:
A file lock at `~/.hermes/cron/.tick.lock` prevents overlapping scheduler ticks from double-running the same job batch.
+### Restart-safe workers under systemd
+
+When the gateway runs as a systemd service, each due job is handed to an external worker process launched in a transient user scope (`systemd-run --user --scope`), so restarting the gateway mid-job does not kill the job. Creating that scope needs a user systemd session; hosts without one (containers, minimal LXCs, a service user without linger) cannot provide it.
+
+By default cron then **degrades**: the job still runs as a separate external process with the same execution handoff, but without cgroup isolation, so a gateway restart during the job kills it (the execution ledger records that). One warning is logged per gateway process. To fail closed instead — skip the job and record the error on the job row — set:
+
+```yaml
+cron:
+ require_restart_safe_scope: true
+```
+
+The lasting fix is a user session for the gateway user: `sudo loginctl enable-linger <gateway-user>` (and `XDG_RUNTIME_DIR` / `DBUS_SESSION_BUS_ADDRESS` in the unit for system-level installs), then restart the gateway. Kanban workers always require a scope and fail closed regardless of this key.
+
### Execution history
Hermes records each claimed cron attempt in the profile-local