The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): release a profile's in-flight claim under the key it registered with
teknium19ecd22e5da7e
diff --git a/cron/AGENTS.md b/cron/AGENTS.mdindex 9a2af919a1e..6983cf3dfc6 100644--- a/cron/AGENTS.md+++ b/cron/AGENTS.md@@ -50,7 +50,26 @@ Hardening invariants — each guards a real failure; don't weaken without answer`scheduler_ownership.owns_cron_tick_for(home)` / `live_gateway_ticking(home)` instead of theprocess-global runtime-lock boolean. Public accessors (`get_running_job_ids`,`get_running_job_details`, `get_wedged_job_ids`) still report the host-wide union of bare job- ids for the shutdown drain.+ ids for the shutdown drain, but LIVENESS consumers (`jobs.py::_job_running_in_this_process`,+ `tools/cronjob_tools`) ask `is_job_running(job_id, home=...)` — the union made profile A's+ running `daily-brief` answer for profile B's idle one.+- **A claim is released under the key it was registered with.** The cron scope is a ContextVar:+ `try_register_running_job` runs on the ticker thread inside `_profile_cron_scope`, while the+ pool worker's `finally` sits OUTSIDE `ctx.run` and resolves the LAUNCH home. Pass the+ registering home (`release_running_job(job_id, home=...)`), or every secondary profile's claim+ leaks — the job skips a fire window until the force-release backstop sweeps it, and the drain+ sees phantom work. Never rebuild a home from a key half (`Path(key[0])`): `hermes_home_key`+ normcases, so use `_inflight_home_path`.+- **Ticked-home state is reclaimed when a home leaves the set.** `register_ticked_homes` is+ republished every cycle and reaps the departed homes' parallel pools; pools used to live until+ `atexit`, so each home ever ticked kept a ThreadPoolExecutor and its worker threads forever.+- **The host gateway stands down for a profile that runs its OWN gateway.** `run.py::+ _cron_profile_gate` (the same gate `hermes_cli/web_server.py` passes) keeps the launch process+ and a per-profile gateway off one store: the tick lock stops a simultaneous double-run but not+ the race, and when the launch process wins, delivery goes through `SharedRouteAdapters`/+ fail-closed instead of that profile's live adapters. The gate compares the liveness PID against+ `os.getpid()` — this process holds the launch `gateway.pid` AND publishes every served profile+ in `served_profiles`, so a bare liveness answer would stand cron down host-wide.- Cron sessions pass `skip_memory=True`; memory providers intentionally do not run during cron.- Cron execution has its own session. Eligible continuable deliveries may mirror or seed thereply-facing conversation: origin, origin-less home fallback, user-written bare-platform home,diff --git a/cron/jobs.py b/cron/jobs.pyindex 34eb29581b4..bd9be129cd4 100644--- a/cron/jobs.py+++ b/cron/jobs.py@@ -216,10 +216,13 @@ def _job_running_in_this_process(job_id: str) -> bool:"the claiming tick died" from "the run is alive but slow" — a run stalled on network I/O (or a laptopthat slept mid-run) legitimately outlives the TTL. The in-process ticker and the run share this process,so the scheduler's running set settles the common single-gateway case without any claim-age guesswork.++ Home-scoped: one process ticks every profile, so the host-wide union of bare job ids would let+ profile A's running ``daily-brief`` keep profile B's stale one-shot alive forever."""try:- from cron.scheduler import get_running_job_ids- return job_id in get_running_job_ids()+ from cron.scheduler import is_job_running+ return is_job_running(job_id)except Exception:logger.warning("Cron running-set liveness check failed for job %r; keeping the "diff --git a/cron/scheduler.py b/cron/scheduler.pyindex b0b0af49b7d..f2d2f9db0dc 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -572,6 +572,23 @@ def _inflight_key(job_id: str, home: Optional[Union[Path, str]] = None) -> tuplereturn (hermes_home_key(home) if home is not None else hermes_home_key(_get_hermes_home()), job_id)+# Home key -> the real home Path that produced it. ``hermes_home_key`` normcases (it lower-cases on+# Windows), so ``Path(key[0])`` is a case-folded path that matches nothing else on disk; bookkeeping+# that needs the profile home reads it here instead of reconstructing it from the key.+_inflight_home_paths: Dict[str, Path] = {}+++def _remember_inflight_home(home: Path) -> Path:+ """Record ``home`` under its key so a claim can be mapped back to a usable path."""+ _inflight_home_paths[hermes_home_key(home)] = home+ return home+++def _inflight_home_path(home_key: str) -> Path:+ """Real home Path for an in-flight key's home half (falls back to the key itself)."""+ return _inflight_home_paths.get(home_key) or Path(home_key)++# In-flight state below is keyed by ``_inflight_key``; the public accessors still report bare job# ids so host-wide consumers (shutdown drain, idle-exit, metrics) see the union across profiles._running_job_ids: set = set()@@ -705,6 +722,20 @@ def get_wedged_job_ids() -> "frozenset[str]":key[1] for key, age in ages.items() if age >= max(allowances[key], floor_seconds))+def is_job_running(job_id: str, home: Optional[Union[Path, str]] = None) -> bool:+ """True when THIS process has an in-flight run of ``job_id`` FOR ``home`` (default: the active+ cron scope's home).++ The bare-id accessors above report the host-wide union so the shutdown drain and metrics see+ every profile's work. Liveness consumers must not: one process ticks every profile, so a+ ``daily-brief`` running in profile A would otherwise report profile B's idle ``daily-brief``+ as running and keep B's stale one-shot alive as a "possibly live run".+ """+ key = _inflight_key(job_id, home)+ with _running_lock:+ return key in _running_job_ids or key in _running_fire_owners++def try_register_running_job(job_id: str) -> bool:"""Atomically add ``job_id`` to the in-flight set; False (caller must skip) if already mid-run.Single dedupe owner for ticker + manual runs (the fire claim's 300s TTL is outlived by real@@ -720,7 +751,7 @@ def try_register_running_job(job_id: str) -> bool:"""from hermes_cli.backend_retirement import retirement- key = _inflight_key(job_id)+ key = _inflight_key(job_id, _remember_inflight_home(_get_hermes_home()))with retirement.work() as admitted, _running_lock:if not admitted or key in _running_job_ids:return False@@ -732,9 +763,15 @@ def try_register_running_job(job_id: str) -> bool:return True-def release_running_job(job_id: str) -> None:- """Remove ``job_id`` (in the active profile scope) from the in-flight running set (idempotent)."""- key = _inflight_key(job_id)+def release_running_job(job_id: str, home: Optional[Union[Path, str]] = None) -> None:+ """Remove ``job_id`` from the in-flight running set (idempotent).++ ``home`` MUST be passed by any caller that does not run inside the same cron scope the claim+ was registered under. The scope is a ContextVar the ticker binds per profile: a pool worker+ releasing in a ``finally`` outside ``ctx.run`` resolves the default (launch) home instead, so+ the discard misses the real key and every secondary profile's claim leaks.+ """+ key = _inflight_key(job_id, home)with _running_lock:_running_job_ids.discard(key)_running_since.pop(key, None)@@ -1012,9 +1049,10 @@ def mark_running_jobs_interrupted(registered_keys = {key for _t, key, _o, _p in active_fires}if only_owners is None:# The key's home half IS the profile home this claim belongs to — the only record of- # it for a claim that never reached ``_running_fire_owners``.+ # it for a claim that never reached ``_running_fire_owners``. Read the real Path back+ # from the key, never ``Path(key[0])``: the key is normcased.active_fires.extend(- (None, key, None, Path(key[0]))+ (None, key, None, _inflight_home_path(key[0]))for key in (_running_job_ids - registered_keys - restart_safe_waiters)@@ -1117,7 +1155,7 @@ def _get_parallel_pool(max_workers: Optional[int]) -> concurrent.futures.ThreadPa single process-global pool is created by whichever profile the multiplexing gateway ticksfirst and then silently imposes that profile's limit on every other profile."""- home = hermes_home_key(_get_hermes_home())+ home = hermes_home_key(_remember_inflight_home(_get_hermes_home()))pool = _parallel_pools.get(home)if pool is None or _parallel_pool_max_workers.get(home) != max_workers:if pool is not None:@@ -1129,6 +1167,21 @@ def _get_parallel_pool(max_workers: Optional[int]) -> concurrent.futures.ThreadPreturn pool+def discard_parallel_pools(home_keys) -> None:+ """Drop the parallel pools of homes this process no longer ticks.++ Pools are per home and used to live until ``atexit``: a host that serves many profiles — or+ churns them — accumulated one ThreadPoolExecutor and its live ``cron-parallel`` threads per+ home ever ticked, and a deleted profile's pool was never reclaimed. ``wait=False`` so the+ ticker is never blocked; queued work still drains before the executor dies.+ """+ for key in list(home_keys):+ pool = _parallel_pools.pop(key, None)+ _parallel_pool_max_workers.pop(key, None)+ if pool is not None:+ pool.shutdown(wait=False, cancel_futures=False)++def _shutdown_parallel_pool() -> None:"""Shut down every profile's persistent pool on process exit."""for pool in list(_parallel_pools.values()):@@ -3996,6 +4049,10 @@ def _submit_with_guard(job: dict, pool: concurrent.futures.ThreadPoolExecutor, pif not try_register_running_job(job_id):logger.info("Job '%s' already running — skipping", job_label)return None+ # The home the claim was registered under. The pool worker's ``finally`` runs OUTSIDE+ # ``ctx.run``, where the per-profile cron scope is not bound, so releasing without it would+ # discard the LAUNCH home's key and leak every secondary profile's claim.+ _claim_home = _get_hermes_home()# Record the attempt before dispatch; recovery marks abandoned rows unknown (no retry).try:execution = create_execution(@@ -4004,22 +4061,22 @@ def _submit_with_guard(job: dict, pool: concurrent.futures.ThreadPoolExecutor, p_ctx = contextvars.copy_context()except Exception as execution_err:# Release the claim so the next tick retries instead of wedging "already running".- release_running_job(job_id)+ release_running_job(job_id, home=_claim_home)_clear_run_claim_best_effort()logger.exception("Job '%s' not dispatched: execution creation failed: %s", job_label, execution_err)return None- def _run_and_release(j=dispatched_job, ctx=_ctx):+ def _run_and_release(j=dispatched_job, ctx=_ctx, home=_claim_home):try:return ctx.run(process_job, j)finally:- release_running_job(j["id"])+ release_running_job(j["id"], home=home)try:fut = pool.submit(_run_and_release)except Exception as submit_err:- release_running_job(job_id)+ release_running_job(job_id, home=_claim_home)_clear_run_claim_best_effort()finish_execution(execution["id"], success=False, error=f"Executor dispatch failed: {submit_err}")@@ -4030,7 +4087,7 @@ def _submit_with_guard(job: dict, pool: concurrent.futures.ThreadPoolExecutor, preturn Nonewith _running_lock:- _submit_key = _inflight_key(job_id)+ _submit_key = _inflight_key(job_id, _claim_home)if _submit_key in _running_job_ids:_running_futures[_submit_key] = futreturn futdiff --git a/cron/scheduler_ownership.py b/cron/scheduler_ownership.pyindex 67052703ec5..3ace2a790f7 100644--- a/cron/scheduler_ownership.py+++ b/cron/scheduler_ownership.py@@ -31,14 +31,25 @@ _ticked_lock = threading.Lock()def register_ticked_homes(homes) -> None:- """Publish the set of profile homes this process's cron ticker owns this cycle."""+ """Publish the set of profile homes this process's cron ticker owns this cycle.++ A home that leaves the set also loses its cron worker pool: pools are per home and otherwise+ live until process exit, so serving (or churning) many profiles leaks one ThreadPoolExecutor+ and its worker threads per home ever ticked.+ """resolved = {}for home in homes:path = Path(home)resolved[hermes_home_key(path)] = pathwith _ticked_lock:+ departed = set(_ticked_homes) - set(resolved)_ticked_homes.clear()_ticked_homes.update(resolved)+ if departed:+ # Late import: cron.scheduler imports this module.+ from cron.scheduler import discard_parallel_pools++ discard_parallel_pools(departed)def ticked_homes() -> dict:diff --git a/gateway/run.py b/gateway/run.pyindex 64616de3943..188e776177b 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -1689,6 +1689,33 @@ def _cron_tick_profile_homes(config: object) -> list[tuple[str, "Path"]]:return homes+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.++ 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+ bare ``_check_gateway_running`` reports "running" for every home we serve — standing us down+ from all of them and stopping cron host-wide.+ """+ from gateway.status import get_running_pid, resolve_gateway_liveness++ try:+ liveness = resolve_gateway_liveness(+ profile_dir=Path(home), use_cache=False,+ pid_probe=lambda path: get_running_pid(path, cleanup_stale=False))+ except Exception as exc:+ logger.debug("Cron profile gate probe failed for %s (ticking it): %s", name, exc)+ return True+ return not (liveness.running and liveness.pid is not None and liveness.pid != os.getpid())++def _enable_multiplex_log_routing(config: object) -> bool:"""Route agent.log/errors.log/gateway.log records to their owning profile (inert single-profile).``setup_logging(mode="gateway")`` binds file handlers to the launch home, so under multiplexing@@ -5303,6 +5330,8 @@ def _start_gateway_start_cron_and_housekeeping(runner):# Live enumerator: the ticker re-reads profiles/ every cycle so a profile created while# the gateway runs gets its jobs fired without a restart (hot-serve).cron_start_kwargs["profile_homes"] = lambda: _cron_tick_profile_homes(runner.config)+ # Stand down, per tick, for a profile whose OWN gateway process ticks it.+ cron_start_kwargs["profile_gate"] = _cron_profile_gate# Per-profile adapters so each profile's cron output goes via its own bot, not the# default's. Absent (no multiplexed adapters), delivery for a secondary profile falls# back to the primary's routed adapters or fails closed — the job still FIRES.diff --git a/tests/cron/test_cron_multiplex_inflight_release.py b/tests/cron/test_cron_multiplex_inflight_release.pynew file mode 100644index 00000000000..806c0e268a2--- /dev/null+++ b/tests/cron/test_cron_multiplex_inflight_release.py@@ -0,0 +1,76 @@+"""One process ticks every profile: a claim must be released under the key it was registered with.++The cron home scope is a ContextVar the ticker binds per profile. ``_submit_with_guard`` registers+the claim on the TICKER thread inside that scope, but the pool worker's ``finally`` release sits+OUTSIDE ``ctx.run``, where the worker thread resolves the LAUNCH home instead. Releasing without+the registering home therefore discarded a key nothing holds and leaked every secondary profile's+claim: the job skipped its next fire window until the force-release backstop swept it, and the+shutdown drain plus ``hermes.cron.jobs.running`` saw phantom work.+"""++from __future__ import annotations++import concurrent.futures++import cron.scheduler as sched+from hermes_constants import reset_hermes_home_override, set_hermes_home_override+++class _Scope:+ """Bind the cron home scope the way ``_profile_cron_scope`` does for a tick."""++ def __init__(self, home):+ self._home = str(home)++ def __enter__(self):+ self._token = set_hermes_home_override(self._home)+ return self++ def __exit__(self, *_exc):+ reset_hermes_home_override(self._token)+ return False+++def test_pool_worker_release_clears_the_ticked_profiles_claim(tmp_path):+ """Dispatch a secondary profile's job through the real guard: no claim may survive the run."""+ launch_home, profile_b = tmp_path / "launch", tmp_path / "profile-b"+ launch_home.mkdir()+ profile_b.mkdir()+ job = {"id": "daily-brief", "name": "daily-brief", "schedule": {"kind": "interval"}}+ ran_in = {}++ def _process_job(j):+ # Runs via ctx.run, so it still sees profile B — only the release is unscoped.+ ran_in["home"] = str(sched._get_hermes_home())++ # The launch home is what an unscoped pool worker thread resolves to.+ with _Scope(launch_home), concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:+ with _Scope(profile_b):+ fut = sched._submit_with_guard(job, pool, _process_job)+ assert fut is not None, "the job must be dispatched"+ fut.result(timeout=30)++ assert ran_in["home"] == str(profile_b)+ assert sched.get_running_job_ids() == frozenset(), (+ "profile B's in-flight claim leaked: the worker released the LAUNCH home's key"+ )+ assert sched._inflight_key(job["id"], profile_b) not in sched._running_job_ids+++def test_a_profiles_release_never_clears_another_profiles_claim(tmp_path):+ """Control: the scope-defaulted release only ever reaches its OWN profile's claim."""+ home_a, home_b = tmp_path / "home-a", tmp_path / "home-b"+ home_a.mkdir()+ home_b.mkdir()+ job_id = "daily-brief"+ try:+ with _Scope(home_b):+ assert sched.try_register_running_job(job_id) is True+ with _Scope(home_a):+ sched.release_running_job(job_id)+ assert sched._inflight_key(job_id, home_b) in sched._running_job_ids+ sched.release_running_job(job_id, home=home_b)+ assert sched.get_running_job_ids() == frozenset()+ finally:+ sched.release_running_job(job_id, home=home_a)+ sched.release_running_job(job_id, home=home_b)diff --git a/tests/cron/test_cron_multiplex_liveness_and_pools.py b/tests/cron/test_cron_multiplex_liveness_and_pools.pynew file mode 100644index 00000000000..81bb19fadae--- /dev/null+++ b/tests/cron/test_cron_multiplex_liveness_and_pools.py@@ -0,0 +1,106 @@+"""Per-home cron liveness and worker-pool lifetime under one multiplexing process.++Two invariants that a host-wide, process-lifetime view of cron state gets wrong:++(a) Job liveness is per profile. One process ticks every profile, so the bare-id union that the+ shutdown drain needs would make profile A's running ``daily-brief`` answer for profile B's+ idle one — reporting B's job as running and keeping B's stale one-shot alive as a "possibly+ live run".+(b) A worker pool belongs to a home that is still ticked. Pools were created per home and dropped+ only on ``max_workers`` change or at ``atexit``, so every home ever ticked kept a+ ThreadPoolExecutor and its live ``cron-parallel`` threads for the process's lifetime.+"""++from __future__ import annotations++import cron.scheduler as sched+from hermes_constants import (+ hermes_home_key,+ reset_hermes_home_override,+ set_hermes_home_override,+)+++class _Scope:+ def __init__(self, home):+ self._home = str(home)++ def __enter__(self):+ self._token = set_hermes_home_override(self._home)+ return self++ def __exit__(self, *_exc):+ reset_hermes_home_override(self._token)+ return False+++def _two_homes(tmp_path):+ home_a, home_b = tmp_path / "home-a", tmp_path / "home-b"+ home_a.mkdir()+ home_b.mkdir()+ return home_a, home_b+++class TestPerProfileJobLiveness:+ def test_is_job_running_answers_for_the_asking_profile_only(self, tmp_path):+ """(a) A's run must not make B's same-named job report as running."""+ home_a, home_b = _two_homes(tmp_path)+ job_id = "daily-brief"+ try:+ with _Scope(home_a):+ assert sched.try_register_running_job(job_id) is True+ assert sched.is_job_running(job_id) is True+ with _Scope(home_b):+ assert sched.is_job_running(job_id) is False, (+ "profile B's idle job must not inherit profile A's run"+ )+ # The host-wide union still reports it for the shutdown drain.+ assert job_id in sched.get_running_job_ids()+ finally:+ with _Scope(home_a):+ sched.release_running_job(job_id)++ def test_stale_oneshot_liveness_is_scoped_to_its_own_home(self, tmp_path):+ """The store's stale-entry recovery consumer asks per home, not host-wide."""+ from cron.jobs import _job_running_in_this_process++ home_a, home_b = _two_homes(tmp_path)+ job_id = "daily-brief"+ try:+ with _Scope(home_a):+ assert sched.try_register_running_job(job_id) is True+ assert _job_running_in_this_process(job_id) is True+ with _Scope(home_b):+ assert _job_running_in_this_process(job_id) is False, (+ "B's stale one-shot would be kept alive forever by A's run"+ )+ finally:+ with _Scope(home_a):+ sched.release_running_job(job_id)+++class TestPoolReaping:+ def test_pool_of_an_unticked_home_is_reaped(self, tmp_path):+ """(b) Republishing the ticked set without a home drops that home's pool."""+ from cron.scheduler_ownership import register_ticked_homes++ home_a, home_b = _two_homes(tmp_path)+ try:+ register_ticked_homes([home_a, home_b])+ with _Scope(home_a):+ sched._get_parallel_pool(1)+ with _Scope(home_b):+ sched._get_parallel_pool(1)+ assert len(sched._parallel_pools) == 2++ # Profile B goes away (deleted / gated out); the served set is republished without it.+ register_ticked_homes([home_a])+ assert hermes_home_key(home_b) not in sched._parallel_pools, (+ "an unticked home's ThreadPoolExecutor leaked for the process's lifetime"+ )+ assert hermes_home_key(home_b) not in sched._parallel_pool_max_workers+ # The home still being ticked keeps its pool.+ assert hermes_home_key(home_a) in sched._parallel_pools+ finally:+ register_ticked_homes([])+ sched._shutdown_parallel_pool()diff --git a/tests/cron/test_cron_multiplex_tick_ownership.py b/tests/cron/test_cron_multiplex_tick_ownership.pyindex 193a73d4c31..53739f7d71c 100644--- a/tests/cron/test_cron_multiplex_tick_ownership.py+++ b/tests/cron/test_cron_multiplex_tick_ownership.py@@ -14,7 +14,6 @@ Three invariants, each broken before the multiplex-scope fix:from __future__ import annotationsimport cron.scheduler as sched-import cron.scheduler_ownership as ownershipfrom hermes_constants import (hermes_home_key,reset_hermes_home_override,@@ -74,6 +73,11 @@ class TestPerProfileInflightState:class TestPerProfileYieldGate:def test_yield_gate_is_answered_per_served_profile(self, tmp_path, monkeypatch):"""(b) A fresher gateway serving only profile A: A yields, B keeps ticking."""+ # Imported per test, not at module scope: a module-level import of a module that does not+ # exist on the base commit turns the whole file into a COLLECTION ERROR, which is not+ # behavioural red-on-base evidence for the invariants below.+ import cron.scheduler_ownership as ownership+home_a, home_b = _two_homes(tmp_path)boot, disk = "a" * 40, "b" * 40monkeypatch.setattr(@@ -105,6 +109,8 @@ class TestPerProfileYieldGate:def test_host_multiplexer_never_yields_a_home_it_ticks(self, tmp_path, monkeypatch):"""Owning the runtime lock only excuses the homes this process actually ticks."""+ import cron.scheduler_ownership as ownership+home_a, home_b = _two_homes(tmp_path)boot, disk = "a" * 40, "b" * 40monkeypatch.setattr(diff --git a/tests/gateway/test_cron_profile_gate.py b/tests/gateway/test_cron_profile_gate.pynew file mode 100644index 00000000000..df0e5cb7404--- /dev/null+++ b/tests/gateway/test_cron_profile_gate.py@@ -0,0 +1,102 @@+"""The gateway ticker stands down for a profile whose OWN gateway process ticks it.++The tick set is every profile regardless of ``gateway.multiplex_profiles``, but that flag also+selects the deployment where each profile runs its own gateway (the s6 per-profile services). With+no gate, profile B's gateway and the launch gateway both tick B's store: the per-home+``cron/.tick.lock`` stops a simultaneous double-run, but which process wins is a race, and when+the launch gateway wins, B's delivery leaves through ``SharedRouteAdapters``/fail-closed instead+of B's own live adapters.++The gate must compare against THIS process's pid: the launch gateway holds its own home's+``gateway.pid`` and publishes every served profile in ``served_profiles``, so a bare liveness+answer says "running" for every home it serves and would stand cron down host-wide.+"""++from __future__ import annotations++import asyncio+import os+import types++import gateway.run as gw_run+from gateway.status import GatewayLiveness+++def _liveness(monkeypatch, liveness):+ from gateway import status as gateway_status++ monkeypatch.setattr(gateway_status, "resolve_gateway_liveness", lambda **_kw: liveness)+++class TestCronProfileGate:+ def test_stands_down_for_a_profile_with_its_own_gateway(self, tmp_path, monkeypatch):+ """Another process owns this home's gateway -> this ticker must not visit it."""+ _liveness(monkeypatch, GatewayLiveness(running=True, pid=os.getpid() + 1, source="pid"))+ assert gw_run._cron_profile_gate("b", tmp_path / "home-b") is False++ def test_keeps_ticking_a_home_this_process_serves(self, tmp_path, monkeypatch):+ """Our OWN pid answering (launch home, or a served profile via the multiplexer rung) must+ never stand this ticker down — that would stop cron for every profile at once."""+ for source in ("pid", "multiplexer", "runtime_status"):+ _liveness(monkeypatch, GatewayLiveness(running=True, pid=os.getpid(), source=source))+ assert gw_run._cron_profile_gate("b", tmp_path / "home-b") is True, source++ def test_keeps_ticking_a_home_with_no_gateway(self, tmp_path, monkeypatch):+ _liveness(monkeypatch, GatewayLiveness(running=False, pid=None, source="none"))+ assert gw_run._cron_profile_gate("b", tmp_path / "home-b") is True++ def test_probe_failure_ticks_rather_than_silently_dropping_cron(self, tmp_path, monkeypatch):+ """A raising probe must not be read as "another gateway owns it"."""+ from gateway import status as gateway_status++ def _boom(**_kw):+ raise RuntimeError("probe exploded")++ monkeypatch.setattr(gateway_status, "resolve_gateway_liveness", _boom)+ assert gw_run._cron_profile_gate("b", tmp_path / "home-b") is True+++def test_gateway_passes_a_profile_gate_to_the_cron_ticker(tmp_path, monkeypatch):+ """Wiring: an unpassed gate gates nothing. Capture what the gateway hands the ticker."""+ from cron import scheduler_provider++ home_b = tmp_path / "home-b"+ home_b.mkdir()+ captured: dict = {}++ class _Thread:+ def __init__(self, target, args=(), kwargs=None, stop_event=None):+ captured.update(kwargs or {})++ def start(self):+ pass++ monkeypatch.setattr(+ gw_run, "_cron_tick_profile_homes", lambda _cfg: [("default", tmp_path), ("b", home_b)])+ monkeypatch.setattr(+ scheduler_provider, "scheduler_for_profile_mode",+ lambda _p, multiplex_profiles=False: scheduler_provider.InProcessCronScheduler())+ from cron import scheduler_thread++ monkeypatch.setattr(scheduler_thread, "SupervisedTickerThread", _Thread)+ monkeypatch.setattr(gw_run, "_start_gateway_housekeeping_thread", lambda *_a, **_k: None,+ raising=False)++ runner = types.SimpleNamespace(+ config={}, adapters={}, _profile_adapters=None, _primary_profile_name="default",+ _draining=False, _external_drain_active=False)++ async def _go():+ return gw_run._start_gateway_start_cron_and_housekeeping(runner)++ asyncio.run(_go())++ gate = captured.get("profile_gate")+ assert callable(gate), "the gateway must pass a profile_gate to the cron ticker"+ # And the gate it passes is the stand-down one, not a pass-everything stub.+ from gateway import status as gateway_status++ monkeypatch.setattr(+ gateway_status, "resolve_gateway_liveness",+ lambda **_kw: GatewayLiveness(running=True, pid=os.getpid() + 1, source="pid"))+ assert gate("b", home_b) is Falsediff --git a/tools/cronjob_tools.py b/tools/cronjob_tools.pyindex 8606373bd7f..c5c6f7f2330 100644--- a/tools/cronjob_tools.py+++ b/tools/cronjob_tools.py@@ -478,10 +478,11 @@ def _try_dispatch_background_run(return None# Early dedupe so a mid-run job reports in THIS response, not as a delayed error completion- # (authoritative check: try_register_running_job).+ # (authoritative check: try_register_running_job). Home-scoped: one process ticks every+ # profile, so the bare-id union would report another profile's same-named job as running.try:- from cron.scheduler import get_running_job_ids- if job_id in get_running_job_ids():+ from cron.scheduler import is_job_running+ if is_job_running(job_id):return {"claimed": False, "success": False, "error": _ALREADY_RUNNING_ERROR}except Exception:passdiff --git a/website/docs/developer-guide/cron-internals.md b/website/docs/developer-guide/cron-internals.mdindex 1d9eac7383b..15c8bd5f0ee 100644--- a/website/docs/developer-guide/cron-internals.md+++ b/website/docs/developer-guide/cron-internals.md@@ -169,7 +169,9 @@ home under `_profile_cron_scope`) evaluate the identical record. One gatewayprocess per host ticks *every* profile's store — `gateway.multiplex_profiles`gates adapters, not cron — and per-run bookkeeping (in-flight claims, theparallel worker pool, the stale-code yield decision) is keyed by profile home,-so two profiles may carry identically named jobs without colliding.+so two profiles may carry identically named jobs without colliding. A profile+that runs its own gateway is skipped per tick, so the two processes never race+its store and its deliveries always leave through its own live adapters.**Fire-claim lease during a run.** A firing run holds `fire_claim = {at, by}` anda heartbeat thread refreshes `at` every 60 s (the lease is 300 s). A heartbeat