Skip to content

The agent that grows with you

fix(cron): one host ticker owns every profile's cron, per profile

teknium1cb647a018ff4
diff --git a/cron/AGENTS.md b/cron/AGENTS.md
index cddd8e5fc64..9a2af919a1e 100644
--- a/cron/AGENTS.md
+++ b/cron/AGENTS.md
@@ -38,6 +38,19 @@ Hardening invariants — each guards a real failure; don't weaken without answer
serves, re-enumerate when a profile dir appears or is tombstoned) is per served home, not per
process. Why: a store opened before the scope was entered wrote a secondary profile's run
records into the launch profile's `jobs.json`.
+- **Cron ownership is not gated on `gateway.multiplex_profiles`.** That flag gates ADAPTERS; one
+ host gateway process ticks EVERY profile's store either way (`run.py::_cron_tick_profile_homes`).
+ Gating the tick set on it left every non-launch profile's jobs in a store no ticker visited.
+- **Per-profile process assumptions are the bug class.** One process ticks N homes, so anything
+ keyed on "this process's profile" is wrong: in-flight state (`_running_job_ids`,
+ `_running_since`, `_running_futures`, `_running_worker_pids`, `_running_fire_owners`,
+ `_interrupted_job_ids`) is keyed by `_inflight_key(job_id)` = `(home key, job id)` — two
+ profiles legitimately carry a `daily-brief`; the parallel pool is keyed by home
+ (`cron.max_parallel_jobs` is per profile); and the stale-code yield gate asks
+ `scheduler_ownership.owns_cron_tick_for(home)` / `live_gateway_ticking(home)` instead of the
+ process-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.
- 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 the
reply-facing conversation: origin, origin-less home fallback, user-written bare-platform home,
diff --git a/cron/scheduler.py b/cron/scheduler.py
index c8b20ea9346..b0b0af49b7d 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -29,7 +29,7 @@ except ImportError:
except ImportError:
msvcrt = None
from pathlib import Path
-from typing import Any, Callable, Dict, List, Optional, Protocol
+from typing import Any, Callable, Dict, List, Optional, Protocol, Union
# Must precede repo-level imports: standalone invocations (e.g. module reload after
# `hermes update`) otherwise fail with ModuleNotFoundError for hermes_time et al.
@@ -207,15 +207,23 @@ _last_yield_log: dict[str, object] = {}
def _should_yield_tick_to_fresh_gateway() -> tuple[str, str] | None:
- """``(boot_rev, disk_rev)`` when this tick must yield to a fresher gateway, else None. Yields
- only when ALL hold: code skew, we don't own the runtime lock, another process holds it, and
- the home-shared runtime status record reports a fresh heartbeat on the disk revision. Every
- probe failure returns None — yielding is a certainty claim, never a guess.
+ """``(boot_rev, disk_rev)`` when THIS profile's tick must yield to a fresher gateway, else None.
+
+ Yields only when ALL hold: code skew, this process is not the cron owner for the profile being
+ ticked, and another live host gateway whose served set covers that profile reports a fresh
+ heartbeat on the disk revision. Every probe failure returns None — yielding is a certainty
+ claim, never a guess.
+
+ The question is asked PER PROFILE. One process multiplexes every profile, so "do I own the
+ runtime lock" (process-global, stamped at boot for the launch home) cannot answer it: a
+ stale multiplexer that holds the lock must still keep ticking the profiles nobody else ticks,
+ and must still yield the ones a fresher gateway serves.
``gateway_state.json`` is per-HOME and last-writer-wins, not per-process: during a
``--replace`` takeover both the stale and the fresh gateway stamp it, so which one this
- predicate reads is write-order dependent. The pid equality below is what binds the record to
- the current lock holder; the takeover window itself fails open (no yield) by design."""
+ predicate reads is write-order dependent. The pid equality in ``live_gateway_ticking`` is what
+ binds the record to the current lock holder; the takeover window itself fails open (no yield).
+ """
skew = _detect_gateway_code_skew()
if skew is None:
return None
@@ -223,28 +231,13 @@ def _should_yield_tick_to_fresh_gateway() -> tuple[str, str] | None:
if disk_sha is None:
return None
try:
- from gateway import status as _gateway_status
- except Exception:
- return None
- try:
- if _gateway_status.owns_gateway_runtime_lock():
+ from cron.scheduler_ownership import live_gateway_ticking, owns_cron_tick_for
+
+ home = _get_hermes_home()
+ if owns_cron_tick_for(home):
return None
- if not _gateway_status.is_gateway_runtime_lock_active():
- return None
- holder_pid = _gateway_status.get_running_pid(cleanup_stale=False)
- holder_status = _gateway_status.read_runtime_status()
- # `get_running_pid(pid_path=None)` can itself fall back to
- # `get_runtime_status_running_pid()`, which derives the pid FROM this same record — in
- # that branch the equality is tautological and the real proof is
- # `runtime_status_is_stale` + `code_sha`. Kept because in the common branch (a live
- # gateway.pid/gateway.lock) it is the only thing tying the record to the lock holder.
- if (
- holder_pid is None
- or not isinstance(holder_status, dict)
- or holder_status.get("pid") != holder_pid
- or _gateway_status.runtime_status_is_stale(holder_status)
- or holder_status.get("code_sha") != disk_sha
- ):
+ holder_status = live_gateway_ticking(home)
+ if holder_status is None or holder_status.get("code_sha") != disk_sha:
return None
except Exception:
return None
@@ -561,23 +554,41 @@ def _is_cron_silence_response(text: str) -> bool:
return is_autonomous_silence_response(text)
# Persistent pool for parallel cron jobs: tick() submits and returns; long jobs never block it.
-_parallel_pool: Optional[concurrent.futures.ThreadPoolExecutor] = None
-_parallel_pool_max_workers: Optional[int] = None
+# Keyed by profile home: one host gateway multiplexes every profile, and ``max_parallel_jobs`` is a
+# per-profile config key — a single process-global pool is sized by whichever profile ticked first
+# and then imposes that limit on all the others.
+_parallel_pools: Dict[str, concurrent.futures.ThreadPoolExecutor] = {}
+_parallel_pool_max_workers: Dict[str, Optional[int]] = {}
+
+
+def _inflight_key(job_id: str, home: Optional[Union[Path, str]] = None) -> tuple:
+ """``(home key, job id)`` — the identity of one in-flight cron run.
+
+ ONE gateway process ticks every profile, so a job id alone is not unique: two profiles
+ routinely carry identically named jobs (``daily-brief``) and sharing a key made the second
+ profile's run read as a duplicate of the first and get skipped. ``home`` defaults to the
+ active cron scope's home, which the ticker binds per profile for the whole tick.
+ """
+ return (hermes_home_key(home) if home is not None else hermes_home_key(_get_hermes_home()), job_id)
+
+
+# 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()
-_running_fire_owners: dict[str, dict[object, tuple[Optional[str], Path]]] = {}
+_running_fire_owners: dict[tuple, dict[object, tuple[Optional[str], Path]]] = {}
# Parent gateway threads synchronously waiting on restart-safe scope workers.
# Shutdown must not misclassify these as ownerless in-process runs: the tool
# process sweep cannot reach the worker's transient scope.
-_restart_safe_waiter_job_ids: set[str] = set()
-# job_id -> pid of the restart-safe external worker executing it (absent for in-process runs), so a
-# drain observer can name the process holding the gateway open.
-_running_worker_pids: dict[str, int] = {}
+_restart_safe_waiter_job_ids: set = set()
+# in-flight key -> pid of the restart-safe external worker executing it (absent for in-process
+# runs), so a drain observer can name the process holding the gateway open.
+_running_worker_pids: dict[tuple, int] = {}
_running_lock = threading.Lock()
# Per in-flight id: time.time() claim instant + the future owning its release (``_FUTURE_PENDING``
# until pool.submit returns). Past-allowance with no live future = leak; the sweep force-releases.
_running_since: dict = {}
-# job_id -> stale-inflight allowance (s), resolved once per run by get_wedged_job_ids.
+# in-flight key -> stale-inflight allowance (s), resolved once per run by get_wedged_job_ids.
_running_allowance_s: dict = {}
_running_futures: dict = {}
@@ -639,7 +650,7 @@ def get_running_job_ids() -> "frozenset[str]":
entirely outside that dict, so without this the drain is structurally blind to them (#60432).
"""
with _running_lock:
- return frozenset(_running_job_ids | _running_fire_owners.keys())
+ return frozenset(key[1] for key in _running_job_ids | _running_fire_owners.keys())
def get_running_job_details() -> list[dict]:
@@ -648,9 +659,10 @@ def get_running_job_details() -> list[dict]:
now = time.time()
with _running_lock:
return [
- {"job_id": jid, "elapsed_s": round(now - _running_since[jid], 1) if jid in _running_since else None,
- "worker_pid": _running_worker_pids.get(jid)}
- for jid in sorted(_running_job_ids | _running_fire_owners.keys())
+ {"job_id": key[1],
+ "elapsed_s": round(now - _running_since[key], 1) if key in _running_since else None,
+ "worker_pid": _running_worker_pids.get(key)}
+ for key in sorted(_running_job_ids | _running_fire_owners.keys())
]
@@ -663,29 +675,34 @@ def get_wedged_job_ids() -> "frozenset[str]":
"""
now = time.time()
with _running_lock:
- ages = {jid: now - started for jid, started in _running_since.items() if jid in _running_job_ids}
- allowances = {jid: _running_allowance_s[jid] for jid in ages if jid in _running_allowance_s}
+ ages = {key: now - started for key, started in _running_since.items() if key in _running_job_ids}
+ allowances = {key: _running_allowance_s[key] for key in ages if key in _running_allowance_s}
if not ages:
return frozenset()
floor_seconds = _inflight_min_allowance_minutes() * 60.0
- unresolved = [jid for jid in ages if jid not in allowances]
+ unresolved = [key for key in ages if key not in allowances]
if unresolved:
# One jobs.json parse per run, not per tick per job: the restart drain polls this every
# 0.1 s on the event loop for the whole wait, and get_job() re-reads the file each call.
+ # ``load_jobs`` reads the ACTIVE scope's store, so only claims from that home can have
+ # their interval resolved; a claim from another profile falls back to the floor.
by_id: dict = {}
with contextlib.suppress(Exception):
from cron.jobs import load_jobs
by_id = {j.get("id"): j for j in load_jobs()}
+ local_home = hermes_home_key(_get_hermes_home())
with _running_lock:
- for job_id in unresolved:
+ for key in unresolved:
allowance = floor_seconds
- interval_minutes = _job_interval_minutes(by_id.get(job_id) or {})
+ local_job = by_id.get(key[1]) if key[0] == local_home else None
+ interval_minutes = _job_interval_minutes(local_job or {})
if interval_minutes:
allowance = max(allowance, 2.0 * interval_minutes * 60.0)
- allowances[job_id] = allowance
- if job_id in _running_job_ids: # released meanwhile -> don't resurrect the entry
- _running_allowance_s[job_id] = allowance
- return frozenset(jid for jid, age in ages.items() if age >= max(allowances[jid], floor_seconds))
+ allowances[key] = allowance
+ if key in _running_job_ids: # released meanwhile -> don't resurrect the entry
+ _running_allowance_s[key] = allowance
+ return frozenset(
+ key[1] for key, age in ages.items() if age >= max(allowances[key], floor_seconds))
def try_register_running_job(job_id: str) -> bool:
@@ -698,29 +715,32 @@ def try_register_running_job(job_id: str) -> bool:
routinely outlived by real jobs, after which a manual ``cronjob(action='run')`` would claim successfully
and run the same job concurrently (idea from #53395 by @izumi0uu).
Registration also makes the run visible to ``get_running_job_ids`` (the gateway shutdown drain, #60432)
- and ``mark_running_jobs_interrupted``.
+ and ``mark_running_jobs_interrupted``. Dedupe is per PROFILE: the key carries the active cron
+ scope's home, so one multiplexing process never treats two profiles' same-named jobs as one.
"""
from hermes_cli.backend_retirement import retirement
+ key = _inflight_key(job_id)
with retirement.work() as admitted, _running_lock:
- if not admitted or job_id in _running_job_ids:
+ if not admitted or key in _running_job_ids:
return False
- _running_job_ids.add(job_id)
+ _running_job_ids.add(key)
# Same critical section as the add: no window where an in-flight id lacks an age the sweep
# can bound. Sentinel is replaced by the real future once ``pool.submit`` returns.
- _running_since[job_id] = time.time()
- _running_futures[job_id] = _FUTURE_PENDING
+ _running_since[key] = time.time()
+ _running_futures[key] = _FUTURE_PENDING
return True
def release_running_job(job_id: str) -> None:
- """Remove ``job_id`` from the in-flight running set (idempotent)."""
+ """Remove ``job_id`` (in the active profile scope) from the in-flight running set (idempotent)."""
+ key = _inflight_key(job_id)
with _running_lock:
- _running_job_ids.discard(job_id)
- _running_since.pop(job_id, None)
- _running_allowance_s.pop(job_id, None)
- _running_futures.pop(job_id, None)
- _running_worker_pids.pop(job_id, None)
+ _running_job_ids.discard(key)
+ _running_since.pop(key, None)
+ _running_allowance_s.pop(key, None)
+ _running_futures.pop(key, None)
+ _running_worker_pids.pop(key, None)
def _inflight_min_allowance_minutes() -> float:
@@ -798,10 +818,10 @@ def get_inflight_guard_stats() -> dict:
now = time.time()
with _running_lock:
return {
- "running": sorted(_running_job_ids),
+ "running": sorted(key[1] for key in _running_job_ids),
"running_ages_seconds": {
- jid: round(now - started, 1)
- for jid, started in _running_since.items()
+ key[1]: round(now - started, 1)
+ for key, started in _running_since.items()
},
"forced_releases": _forced_release_count,
"recent_forced_releases": list(_forced_releases)}
@@ -830,9 +850,16 @@ def _record_forced_release(job_id: str, name: str, age_seconds: float, allowance
def _latest_executions_for_releasable_claims() -> dict:
"""Latest durable execution per releasable-looking claim (missing/pending/done future), one
indexed query so the healthy path pays no DB work. Snapshot under _running_lock — iterating
- the set while try_register/release mutate it raises RuntimeError."""
+ the set while try_register/release mutate it raises RuntimeError.
+
+ Scoped to the ACTIVE profile's claims: the executions ledger it queries is that home's.
+ """
+ local_home = hermes_home_key(_get_hermes_home())
with _running_lock:
- claim_futures = {job_id: _running_futures.get(job_id) for job_id in _running_job_ids}
+ claim_futures = {
+ key[1]: _running_futures.get(key)
+ for key in _running_job_ids if key[0] == local_home
+ }
candidates = [
job_id for job_id, fut in claim_futures.items()
if fut is None or fut is _FUTURE_PENDING or fut.done()
@@ -913,22 +940,24 @@ def sweep_stale_inflight(due_jobs: Optional[list] = None) -> list:
from cron.executions import _TERMINAL_STATES as _terminal_states
_latest = _latest_executions_for_releasable_claims()
+ _local_home = hermes_home_key(_get_hermes_home())
# Compute intervals OUTSIDE _running_lock so croniter doesn't block try_register/release.
_intervals = {jid: _job_interval_minutes(j) for jid, j in by_id.items()}
with _running_lock:
- for job_id in list(_running_job_ids):
- started = _running_since.get(job_id)
+ for key in [k for k in _running_job_ids if k[0] == _local_home]:
+ job_id = key[1]
+ started = _running_since.get(key)
if started is None:
# Claim predates this guard — adopt it; sweepable one allowance from now.
- _running_since[job_id] = now
+ _running_since[key] = now
continue
age = now - started
interval_minutes = _intervals.get(job_id)
allowance = floor_seconds
if interval_minutes:
allowance = max(allowance, 2.0 * interval_minutes * 60.0)
- fut = _running_futures.get(job_id)
+ fut = _running_futures.get(key)
if fut is _FUTURE_PENDING:
# Submit path hung before ``pool.submit`` returned — the wedge class; release it.
pass
@@ -948,10 +977,10 @@ def sweep_stale_inflight(due_jobs: Optional[list] = None) -> list:
reason = "age"
else:
continue
- _running_job_ids.discard(job_id)
- _running_since.pop(job_id, None)
- _running_allowance_s.pop(job_id, None)
- _running_futures.pop(job_id, None)
+ _running_job_ids.discard(key)
+ _running_since.pop(key, None)
+ _running_allowance_s.pop(key, None)
+ _running_futures.pop(key, None)
_forced_release_count += 1
stale.append((job_id, age, allowance, fut, reason))
@@ -973,27 +1002,30 @@ def mark_running_jobs_interrupted(
with _running_lock:
restart_safe_waiters = set(_restart_safe_waiter_job_ids)
active_fires = [
- (token, job_id, owner, profile_home)
- for job_id, executions in _running_fire_owners.items()
- if job_id not in restart_safe_waiters
+ (token, key, owner, profile_home)
+ for key, executions in _running_fire_owners.items()
+ if key not in restart_safe_waiters
for token, (owner, profile_home) in executions.items()
]
if only_owners is not None:
- active_fires = [fire for fire in active_fires if (fire[1], fire[2]) in only_owners]
- registered_ids = {job_id for _t, job_id, _o, _p in active_fires}
+ active_fires = [fire for fire in active_fires if (fire[1][1], fire[2]) in only_owners]
+ 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``.
active_fires.extend(
- (None, job_id, None, _get_hermes_home())
- for job_id in (
- _running_job_ids - registered_ids - restart_safe_waiters
+ (None, key, None, Path(key[0]))
+ for key in (
+ _running_job_ids - registered_keys - restart_safe_waiters
)
)
_interrupted_job_ids.update(
- token if token is not None else job_id
- for token, job_id, _owner, _profile_home in active_fires
+ token if token is not None else key
+ for token, key, _owner, _profile_home in active_fires
)
marked = []
- for _token, job_id, fire_owner, profile_home in active_fires:
+ for _token, key, fire_owner, profile_home in active_fires:
+ job_id = key[1]
if not fire_owner:
logger.warning(
"Job '%s' interrupted before its durable fire owner was registered; "
@@ -1018,22 +1050,24 @@ def _is_interrupted(job_id: str, token: Optional[object] = None) -> bool:
"""Non-destructive peek: has shutdown marked THIS execution interrupted? Used before deciding
what to deliver; does not clear the flag (the authoritative pre-``last_status`` check needs it).
``token`` scopes to one execution so a fresh run reusing the job ID isn't poisoned."""
+ key = _inflight_key(job_id)
with _running_lock:
if token is not None and token in _interrupted_job_ids:
return True
- return job_id in _interrupted_job_ids
+ return key in _interrupted_job_ids
def _consume_interrupted_flag(job_id: str, token: Optional[object] = None) -> bool:
"""Return True and clear the flag if shutdown marked THIS execution interrupted. Called right
before ``last_status`` is written; consuming stops the flag leaking into a later run."""
+ key = _inflight_key(job_id)
with _running_lock:
hit = False
if token is not None and token in _interrupted_job_ids:
_interrupted_job_ids.discard(token)
hit = True
- if job_id in _interrupted_job_ids:
- _interrupted_job_ids.discard(job_id)
+ if key in _interrupted_job_ids:
+ _interrupted_job_ids.discard(key)
hit = True
return hit
@@ -1077,24 +1111,30 @@ def _cron_inactivity_seconds() -> float:
def _get_parallel_pool(max_workers: Optional[int]) -> concurrent.futures.ThreadPoolExecutor:
- """Return (or create) the persistent parallel pool."""
- global _parallel_pool, _parallel_pool_max_workers
- if _parallel_pool is None or _parallel_pool_max_workers != max_workers:
- if _parallel_pool is not None:
- _parallel_pool.shutdown(wait=False, cancel_futures=False)
- _parallel_pool = concurrent.futures.ThreadPoolExecutor(
+ """Return (or create) the persistent parallel pool for the ACTIVE profile.
+
+ Pools are per profile home because ``cron.max_parallel_jobs`` is a per-profile config key:
+ a single process-global pool is created by whichever profile the multiplexing gateway ticks
+ first and then silently imposes that profile's limit on every other profile.
+ """
+ home = hermes_home_key(_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:
+ pool.shutdown(wait=False, cancel_futures=False)
+ pool = concurrent.futures.ThreadPoolExecutor(
max_workers=max_workers, thread_name_prefix="cron-parallel")
- _parallel_pool_max_workers = max_workers
- return _parallel_pool
+ _parallel_pools[home] = pool
+ _parallel_pool_max_workers[home] = max_workers
+ return pool
def _shutdown_parallel_pool() -> None:
- """Shut down the persistent pool on process exit."""
- global _parallel_pool, _parallel_pool_max_workers
- if _parallel_pool is not None:
- _parallel_pool.shutdown(wait=True, cancel_futures=False)
- _parallel_pool = None
- _parallel_pool_max_workers = None
+ """Shut down every profile's persistent pool on process exit."""
+ for pool in list(_parallel_pools.values()):
+ pool.shutdown(wait=True, cancel_futures=False)
+ _parallel_pools.clear()
+ _parallel_pool_max_workers.clear()
atexit.register(_shutdown_parallel_pool)
@@ -2631,8 +2671,9 @@ def run_one_job(
fire_owner = str(claim.get("by") or "") if isinstance(claim, dict) else ""
execution_token = object()
profile_home = _get_hermes_home().resolve()
+ _fire_key = _inflight_key(job["id"])
with _running_lock:
- _running_fire_owners.setdefault(job["id"], {})[execution_token] = (
+ _running_fire_owners.setdefault(_fire_key, {})[execution_token] = (
fire_owner or None, profile_home)
try:
with self_removal_delivery_scope(job["id"]):
@@ -2649,11 +2690,11 @@ def run_one_job(
execution_token=execution_token))
finally:
with _running_lock:
- executions = _running_fire_owners.get(job["id"])
+ executions = _running_fire_owners.get(_fire_key)
if executions is not None:
executions.pop(execution_token, None)
if not executions:
- _running_fire_owners.pop(job["id"], None)
+ _running_fire_owners.pop(_fire_key, None)
_OWNERSHIP_LOST_INTERRUPTED = "Interrupted by shutdown before terminal completion."
@@ -3300,7 +3341,7 @@ def _wait_for_external_cron_worker(
finally:
if job_id is not None:
with _running_lock:
- _restart_safe_waiter_job_ids.discard(job_id)
+ _restart_safe_waiter_job_ids.discard(_inflight_key(job_id))
# The execution is terminal or its worker is dead: nobody will read a
# payload or acknowledgement left behind by a late/unread handoff.
for stale in handoff_files:
@@ -3440,7 +3481,7 @@ def _launch_external_cron_worker(job: dict) -> bool:
raise
with _running_lock:
- _restart_safe_waiter_job_ids.add(job_id)
+ _restart_safe_waiter_job_ids.add(_inflight_key(job_id))
# Same window the dead-owner recovery ledger grants a pending handoff: a cold
# worker start (imports + secret hydration) measures ~10-12s in the field, and
@@ -3487,7 +3528,8 @@ def _launch_external_cron_worker(job: dict) -> bool:
execution_id,
)
with _running_lock, contextlib.suppress(TypeError, ValueError):
- _running_worker_pids[job_id] = int(acknowledgement.get("pid") or process.pid)
+ _running_worker_pids[_inflight_key(job_id)] = int(
+ acknowledgement.get("pid") or process.pid)
return _wait_for_external_cron_worker(
process,
execution_id=execution_id,
@@ -3497,7 +3539,7 @@ def _launch_external_cron_worker(job: dict) -> bool:
returncode = process.poll()
if returncode is not None:
with _running_lock:
- _restart_safe_waiter_job_ids.discard(job_id)
+ _restart_safe_waiter_job_ids.discard(_inflight_key(job_id))
payload_path.unlink(missing_ok=True)
from cron.scheduler_diagnostics import external_worker_stderr_tail
stderr_tail = external_worker_stderr_tail(stderr_path)
@@ -3848,11 +3890,12 @@ def _maybe_reap_dead_owners() -> None:
def _sweep_stale_inflight_for_tick(due_jobs: list) -> None:
"""Bound the in-flight set BEFORE the dedup guard so a leaked claim is force-released now
rather than eating every later fire until restart. Skipped when nothing is in flight."""
- if not _running_job_ids:
+ _local_home = hermes_home_key(_get_hermes_home())
+ if not any(key[0] == _local_home for key in _running_job_ids):
return
_sweep_jobs = due_jobs
with contextlib.suppress(Exception):
- _inflight_ids = set(_running_job_ids)
+ _inflight_ids = {key[1] for key in _running_job_ids if key[0] == _local_home}
_due_ids = {j.get("id") for j in due_jobs if isinstance(j, dict)}
if not _inflight_ids <= _due_ids:
from cron.jobs import load_jobs as _load_all_jobs
@@ -3987,8 +4030,9 @@ def _submit_with_guard(job: dict, pool: concurrent.futures.ThreadPoolExecutor, p
return None
with _running_lock:
- if job_id in _running_job_ids:
- _running_futures[job_id] = fut
+ _submit_key = _inflight_key(job_id)
+ if _submit_key in _running_job_ids:
+ _running_futures[_submit_key] = fut
return fut
diff --git a/cron/scheduler_ownership.py b/cron/scheduler_ownership.py
new file mode 100644
index 00000000000..67052703ec5
--- /dev/null
+++ b/cron/scheduler_ownership.py
@@ -0,0 +1,126 @@
+"""Which profile homes THIS process ticks, and who owns the cron tick for a given home.
+
+One gateway process per host multiplexes every profile, so "does a gateway own cron for profile
+X" stopped being answerable from the launch home alone: ``gateway.status.owns_gateway_runtime_lock``
+is a process-global boolean set once at boot, and every path resolver behind
+``is_gateway_runtime_lock_active`` goes through ``get_process_hermes_home()``, which ignores the
+per-tick ``_profile_cron_scope`` override. Both therefore answer about the LAUNCH home while the
+ticker is scoped to some other profile.
+
+The two predicates here keep those questions apart:
+
+* :func:`owns_cron_tick_for` — this process is the host gateway AND ticks that home.
+* :func:`live_gateway_ticking` — a DIFFERENT, live host gateway holds the runtime lock and its
+ published served set covers that home.
+
+Every probe failure answers "no": ownership claims are certainties, never guesses.
+"""
+
+from __future__ import annotations
+
+import threading
+from pathlib import Path
+from typing import Any, Optional, Union
+
+from hermes_constants import get_hermes_home, hermes_home_key
+
+# Home key -> home path for every profile this process ticks, republished each ticker cycle so a
+# profile created or tombstoned mid-run is reflected without a restart.
+_ticked_homes: dict[str, Path] = {}
+_ticked_lock = threading.Lock()
+
+
+def register_ticked_homes(homes) -> None:
+ """Publish the set of profile homes this process's cron ticker owns this cycle."""
+ resolved = {}
+ for home in homes:
+ path = Path(home)
+ resolved[hermes_home_key(path)] = path
+ with _ticked_lock:
+ _ticked_homes.clear()
+ _ticked_homes.update(resolved)
+
+
+def ticked_homes() -> dict:
+ """Snapshot of ``home key -> home`` for the profiles this process ticks."""
+ with _ticked_lock:
+ return dict(_ticked_homes)
+
+
+def serves_profile(home: Optional[Union[Path, str]] = None) -> bool:
+ """True when THIS process's cron ticker owns ``home`` (default: the active cron scope)."""
+ key = hermes_home_key(home if home is not None else get_hermes_home())
+ with _ticked_lock:
+ return key in _ticked_homes
+
+
+def owns_cron_tick_for(home: Optional[Union[Path, str]] = None) -> bool:
+ """True when this process is the host gateway multiplexer AND ticks ``home``.
+
+ The runtime lock alone is not enough: it proves only that this process is the host gateway,
+ not that its ticker visits the profile whose store is being ticked right now.
+ """
+ try:
+ from gateway import status as gateway_status
+
+ if not gateway_status.owns_gateway_runtime_lock():
+ return False
+ except Exception:
+ return False
+ return serves_profile(home)
+
+
+def record_serves_profile(record: Any, home: Optional[Union[Path, str]] = None) -> bool:
+ """True when a gateway runtime-status ``record``'s served set covers ``home``.
+
+ The record is read from the holder's own home, so it always proves that home — that is the
+ pre-multiplex meaning, and a single-profile gateway publishes an EMPTY ``served_profiles``.
+ Other profiles need an explicit entry in the published served set.
+ """
+ if not isinstance(record, dict):
+ return False
+ from gateway.status import (
+ _get_process_hermes_home, _profile_label_for_home, _same_hermes_home)
+
+ try:
+ target = Path(home) if home is not None else get_hermes_home()
+ record_home = record.get("hermes_home")
+ if not isinstance(record_home, str) or not record_home.strip():
+ record_home = _get_process_hermes_home()
+ if _same_hermes_home(record_home, target):
+ return True
+ except Exception:
+ return False
+ served = record.get("served_profiles")
+ if not isinstance(served, list):
+ return False
+ label = _profile_label_for_home(target)
+ return label is not None and label in served
+
+
+def live_gateway_ticking(home: Optional[Union[Path, str]] = None) -> Optional[dict]:
+ """Runtime-status record of ANOTHER live host gateway that ticks ``home``, else None.
+
+ ``None`` covers every "we cannot prove it" case: this process holds the lock itself, no lock
+ is held, the record does not belong to the lock holder, its heartbeat is stale, or its served
+ set does not name ``home``.
+ """
+ try:
+ from gateway import status as gateway_status
+
+ if gateway_status.owns_gateway_runtime_lock():
+ return None
+ if not gateway_status.is_gateway_runtime_lock_active():
+ return None
+ holder_pid = gateway_status.get_running_pid(cleanup_stale=False)
+ record = gateway_status.read_runtime_status()
+ if (
+ holder_pid is None
+ or not isinstance(record, dict)
+ or record.get("pid") != holder_pid
+ or gateway_status.runtime_status_is_stale(record)
+ ):
+ return None
+ except Exception:
+ return None
+ return record if record_serves_profile(record, home) else None
diff --git a/cron/scheduler_provider.py b/cron/scheduler_provider.py
index a80e80cfe91..1431191cd07 100644
--- a/cron/scheduler_provider.py
+++ b/cron/scheduler_provider.py
@@ -418,6 +418,8 @@ class InProcessCronScheduler(CronScheduler):
from cron.scheduler import CronTickYielded
from cron.scheduler import tick as cron_tick
from cron.jobs import clear_ticker_error, record_ticker_error, record_ticker_heartbeat
+ from cron.scheduler_ownership import register_ticked_homes
+ from hermes_constants import get_process_hermes_home
logger.info("In-process cron scheduler started (interval=%ds)", interval)
@@ -435,6 +437,9 @@ class InProcessCronScheduler(CronScheduler):
)
return
+ # Single-profile ticker: the launch home is the only home this process owns cron for.
+ register_ticked_homes([get_process_hermes_home()])
+
# Startup recovery and the initial heartbeat run before the guarded loop; a broken
# store here must not take the whole ticker thread down (#111010) — the loop's own
# per-tick handling logs, persists the reason and keeps the thread alive.
@@ -515,8 +520,10 @@ class InProcessCronScheduler(CronScheduler):
SharedRouteAdapters, _primary_profile_routes_for_current_home,
)
from cron.jobs import clear_ticker_error, record_ticker_error, record_ticker_heartbeat
+ from cron.scheduler_ownership import register_ticked_homes
initial_homes = _existing_profile_homes(profile_homes)
+ register_ticked_homes([_profile_entry(entry)[1] for entry in initial_homes])
logger.info(
"Multiplex cron scheduler started for %d profile(s): %s%s",
len(initial_homes),
@@ -573,6 +580,10 @@ class InProcessCronScheduler(CronScheduler):
if profile_gate is not None:
enumerated = [(name, home) for name, home in enumerated if profile_gate(name, home)]
cycle_homes = enumerated
+ # Republish the owned set BEFORE any tick: the per-profile yield gate asks
+ # "do I own cron for this home?" and a profile added or gated out this cycle
+ # must be reflected in that answer, not one cycle late.
+ register_ticked_homes([home for _name, home in cycle_homes])
except BaseException as e:
logger.error("Cron profile enumeration error: %s", e, exc_info=True)
_tick_error = f"{type(e).__name__}: {e}"
diff --git a/gateway/run.py b/gateway/run.py
index 06913a21050..64616de3943 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -1672,10 +1672,11 @@ def _multiplex_profile_homes(config: object) -> list[tuple[str, "Path"]]:
def _cron_tick_profile_homes(config: object) -> list[tuple[str, "Path"]]:
- """Profile homes the in-process ticker visits under multiplex: the served set PLUS the
- process-active profile: ``profiles_to_serve`` lists default + every live named profile, but a
- ``--profile <name>`` multiplexer's own profile may sit outside ``profiles/`` (custom
- HERMES_HOME). Adapter startup already skips ``active``."""
+ """Profile homes the in-process ticker visits: the served set PLUS the process-active
+ profile: ``profiles_to_serve`` lists default + every live named profile, but a ``--profile
+ <name>`` gateway's own profile may sit outside ``profiles/`` (custom HERMES_HOME). One host
+ process ticks all of them regardless of ``gateway.multiplex_profiles``. Adapter startup
+ already skips ``active``."""
from hermes_cli.profiles import get_active_profile_name, get_profile_dir
homes = _multiplex_profile_homes(config)
@@ -5284,31 +5285,35 @@ def _start_gateway_start_cron_and_housekeeping(runner):
from cron.scheduler_provider import (
InProcessCronScheduler, resolve_cron_scheduler, scheduler_for_profile_mode)
cron_stop = threading.Event()
- multiplex_cron = bool(getattr(runner.config, "multiplex_profiles", False))
+ # ONE gateway process per host multiplexes every profile, so its cron ticker owns EVERY
+ # profile's store — `gateway.multiplex_profiles` gates adapters, not cron. Gating the tick set
+ # on that flag left every non-launch profile's jobs in a store no ticker visited: they
+ # silently never fired.
+ try:
+ cron_profile_homes = _cron_tick_profile_homes(runner.config)
+ except Exception as exc:
+ logger.warning("Could not resolve profile homes for cron: %s", exc)
+ cron_profile_homes = []
+ # External providers own one unscoped remote registry, so they can only serve a single home.
cron_provider = scheduler_for_profile_mode(
- resolve_cron_scheduler(), multiplex_profiles=multiplex_cron)
+ resolve_cron_scheduler(), multiplex_profiles=len(cron_profile_homes) > 1)
cron_start_kwargs: Dict[str, Any] = {"adapters": runner.adapters, "loop": asyncio.get_running_loop()}
- # Multiplex: tell the ticker which profile homes to tick (else secondary profiles' jobs never
- # run, #69377), including a ``--profile <name>`` multiplexer's OWN store.
- if isinstance(cron_provider, InProcessCronScheduler) and multiplex_cron:
- try:
- profile_homes = _cron_tick_profile_homes(runner.config)
- if profile_homes:
- # Live enumerator: the ticker re-reads profiles/ every cycle so a profile created while
- # the multiplexer runs gets its jobs fired without a restart (hot-serve).
- cron_start_kwargs["profile_homes"] = lambda: _cron_tick_profile_homes(runner.config)
- # Per-profile adapters so each profile's cron output goes via its own bot, not the default's.
- cron_start_kwargs["profile_adapters"] = getattr(runner, "_profile_adapters", None)
- # runner.adapters belongs to the LAUNCH profile (``default``, or the ``--profile``
- # name); naming it keeps the ticker from routing a secondary's cron through that bot
- # and lets a named multiplexer's own jobs reuse its live adapters.
- cron_start_kwargs["default_profile"] = runner._primary_profile_name
- logger.info(
- "Cron scheduler will tick %d profile(s) under multiplex: %s", len(profile_homes),
- [p[0] if isinstance(p, tuple) else p for p in profile_homes])
- except Exception as exc:
- logger.warning("Could not resolve profile homes for multiplex cron: %s", exc)
+ if isinstance(cron_provider, InProcessCronScheduler) and cron_profile_homes:
+ # 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)
+ # 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.
+ cron_start_kwargs["profile_adapters"] = getattr(runner, "_profile_adapters", None)
+ # runner.adapters belongs to the LAUNCH profile (``default``, or the ``--profile``
+ # name); naming it keeps the ticker from routing a secondary's cron through that bot
+ # and lets a named multiplexer's own jobs reuse its live adapters.
+ cron_start_kwargs["default_profile"] = runner._primary_profile_name
+ logger.info(
+ "Cron scheduler will tick %d profile(s): %s", len(cron_profile_homes),
+ [p[0] if isinstance(p, tuple) else p for p in cron_profile_homes])
# Only the in-process ticker polls local due jobs, so only it gets the external-drain dispatch gate.
if isinstance(cron_provider, InProcessCronScheduler):
diff --git a/tests/cron/test_cleanup_timeout.py b/tests/cron/test_cleanup_timeout.py
index 02758d98cf7..9fcc97b43c1 100644
--- a/tests/cron/test_cleanup_timeout.py
+++ b/tests/cron/test_cleanup_timeout.py
@@ -132,8 +132,8 @@ def test_dispatch_guard_releases_after_sessiondb_finalization_hang(tmp_path):
"next_run_at": "2020-01-01T00:00:00",
"deliver": "local",
}
- sched._parallel_pool = None
- sched._parallel_pool_max_workers = None
+ sched._parallel_pools.clear()
+ sched._parallel_pool_max_workers.clear()
sched._running_job_ids.clear()
try:
@@ -159,5 +159,5 @@ def test_dispatch_guard_releases_after_sessiondb_finalization_hang(tmp_path):
assert sched.tick(verbose=False) == 1
finally:
release.set()
- sched._running_job_ids.discard("cleanup-guard-hang")
+ sched._running_job_ids.discard(sched._inflight_key("cleanup-guard-hang"))
sched._shutdown_parallel_pool()
diff --git a/tests/cron/test_cron_multiplex_tick_ownership.py b/tests/cron/test_cron_multiplex_tick_ownership.py
new file mode 100644
index 00000000000..193a73d4c31
--- /dev/null
+++ b/tests/cron/test_cron_multiplex_tick_ownership.py
@@ -0,0 +1,143 @@
+"""One host process ticks every profile: cron ownership and state must be per profile.
+
+Three invariants, each broken before the multiplex-scope fix:
+
+(a) Two profiles carrying an identically named job, ticked by ONE process, are two jobs: the
+ in-flight dedupe guard keyed them by bare job id, so the second profile's run was skipped as
+ a duplicate and its release cleared the first profile's claim.
+(b) The stale-code yield gate is asked per served profile. It resolved ownership through the
+ process-global runtime-lock boolean and the LAUNCH home's lock, so one answer covered every
+ profile the ticker visited.
+(c) The worker pool is sized by the profile being ticked, not by whichever profile ticked first.
+"""
+
+from __future__ import annotations
+
+import cron.scheduler as sched
+import cron.scheduler_ownership as ownership
+from hermes_constants import (
+ hermes_home_key,
+ 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 _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 TestPerProfileInflightState:
+ def test_same_job_id_in_two_profiles_does_not_collide(self, tmp_path):
+ """(a) Both profiles' ``daily-brief`` register, and releasing one leaves the other."""
+ 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
+ with _Scope(home_b):
+ assert sched.try_register_running_job(job_id) is True, (
+ "a second profile's same-named job must not read as a duplicate"
+ )
+ # Within one profile the dedupe guard still holds.
+ assert sched.try_register_running_job(job_id) is False
+ with _Scope(home_a):
+ sched.release_running_job(job_id)
+ assert sched._inflight_key(job_id, home_b) in sched._running_job_ids, (
+ "profile A's release must not drop profile B's claim"
+ )
+ # The host-wide accessor keeps reporting bare job ids for the shutdown drain.
+ assert job_id in sched.get_running_job_ids()
+ finally:
+ for home in (home_a, home_b):
+ with _Scope(home):
+ sched.release_running_job(job_id)
+
+
+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."""
+ home_a, home_b = _two_homes(tmp_path)
+ boot, disk = "a" * 40, "b" * 40
+ monkeypatch.setattr(
+ sched, "_detect_gateway_code_skew", lambda: (boot[:10], disk[:10]))
+ monkeypatch.setattr(sched, "_current_gateway_code_sha", lambda: disk)
+ # A live foreign gateway holding the runtime lock, serving profile A's home only.
+ from gateway import status as gateway_status
+
+ monkeypatch.setattr(gateway_status, "owns_gateway_runtime_lock", lambda: False)
+ monkeypatch.setattr(
+ gateway_status, "is_gateway_runtime_lock_active", lambda lock_path=None: True)
+ monkeypatch.setattr(gateway_status, "get_running_pid", lambda **_k: 4321)
+ monkeypatch.setattr(gateway_status, "runtime_status_is_stale", lambda _r: False)
+ monkeypatch.setattr(
+ gateway_status,
+ "read_runtime_status",
+ lambda: {"pid": 4321, "code_sha": disk, "hermes_home": str(home_a)},
+ )
+ ownership.register_ticked_homes([home_a, home_b])
+ try:
+ with _Scope(home_a):
+ assert sched._should_yield_tick_to_fresh_gateway() is not None
+ with _Scope(home_b):
+ assert sched._should_yield_tick_to_fresh_gateway() is None, (
+ "profile B has no fresher ticker; yielding would stop its cron entirely"
+ )
+ finally:
+ ownership.register_ticked_homes([])
+
+ 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."""
+ home_a, home_b = _two_homes(tmp_path)
+ boot, disk = "a" * 40, "b" * 40
+ monkeypatch.setattr(
+ sched, "_detect_gateway_code_skew", lambda: (boot[:10], disk[:10]))
+ monkeypatch.setattr(sched, "_current_gateway_code_sha", lambda: disk)
+ from gateway import status as gateway_status
+
+ monkeypatch.setattr(gateway_status, "owns_gateway_runtime_lock", lambda: True)
+ ownership.register_ticked_homes([home_a])
+ try:
+ with _Scope(home_a):
+ assert ownership.owns_cron_tick_for(home_a) is True
+ assert sched._should_yield_tick_to_fresh_gateway() is None
+ with _Scope(home_b):
+ assert ownership.owns_cron_tick_for(home_b) is False
+ finally:
+ ownership.register_ticked_homes([])
+
+
+class TestPerProfileWorkerPool:
+ def test_pool_is_sized_by_the_ticked_profile(self, tmp_path):
+ """(c) The first profile ticked must not size every other profile's pool."""
+ home_a, home_b = _two_homes(tmp_path)
+ try:
+ with _Scope(home_a):
+ pool_a = sched._get_parallel_pool(1)
+ with _Scope(home_b):
+ pool_b = sched._get_parallel_pool(4)
+ assert pool_a is not pool_b
+ assert pool_a._max_workers == 1
+ assert pool_b._max_workers == 4
+ with _Scope(home_a):
+ # Profile A keeps its own pool; B's larger budget did not replace it.
+ assert sched._get_parallel_pool(1) is pool_a
+ finally:
+ sched._shutdown_parallel_pool()
diff --git a/tests/cron/test_inflight_stale_guard.py b/tests/cron/test_inflight_stale_guard.py
index c84b2994941..3085fb388d8 100644
--- a/tests/cron/test_inflight_stale_guard.py
+++ b/tests/cron/test_inflight_stale_guard.py
@@ -97,7 +97,7 @@ def _job(job_id="wedged", minutes=60, kind="interval", cron_expr=None,
return job
-def _inject_stale_claim(job_id: str) -> None:
+def _inject_stale_claim(job_id: str, home) -> None:
"""Simulate the leak exactly as the incident left it: the job id is in
the running set but no future was ever installed, so the release path in
the worker's ``finally`` can never run.
@@ -108,10 +108,10 @@ def _inject_stale_claim(job_id: str) -> None:
``max(2 * 60m interval, 30m floor)`` — so the claim is past its
allowance on the first sweep.
"""
- sched._running_job_ids.add(job_id)
+ sched._running_job_ids.add(sched._inflight_key(job_id, home))
running_since = getattr(sched, "_running_since", None)
if running_since is not None:
- running_since[job_id] = time.time() - 6 * 60 * 60 # 6h old
+ running_since[sched._inflight_key(job_id, home)] = time.time() - 6 * 60 * 60 # 6h old
class TestStaleInflightLeak:
@@ -124,7 +124,7 @@ class TestStaleInflightLeak:
process restarts."""
job = _job(job_id="board-pm-triage-wedged", minutes=60)
job_id = job["id"]
- _inject_stale_claim(job_id)
+ _inject_stale_claim(job_id, tmp_path)
with caplog.at_level("WARNING"), \
patch.object(sched, "_get_hermes_home", return_value=tmp_path), \
@@ -159,7 +159,7 @@ class TestStaleInflightLeak:
long-running jobs. Passes on both the red and the fixed code."""
job = _job(job_id="young", minutes=60)
job_id = job["id"]
- sched._running_job_ids.add(job_id)
+ sched._running_job_ids.add(sched._inflight_key(job_id, tmp_path))
running_since = getattr(sched, "_running_since", None)
if running_since is not None:
running_since[job_id] = time.time() - 60 # 1 minute old
@@ -212,8 +212,8 @@ class TestStaleInflightSweep:
def test_allowance_is_at_least_two_intervals(self, tmp_path):
"""A slow-but-healthy 6h job is not clipped by the 30m floor."""
job = _job(minutes=360)
- sched._running_job_ids.add(job["id"])
- sched._running_since[job["id"]] = time.time() - 4 * 60 * 60 # 4h < 12h
+ sched._running_job_ids.add(sched._inflight_key(job["id"], tmp_path))
+ sched._running_since[sched._inflight_key(job["id"], tmp_path)] = time.time() - 4 * 60 * 60 # 4h < 12h
with patch.object(sched, "_get_hermes_home", return_value=tmp_path):
assert sched.sweep_stale_inflight([job]) == []
@@ -223,8 +223,8 @@ class TestStaleInflightSweep:
"""The real guide-curator row (4320m) gets a 144h allowance, not the
30m floor — the Blocker-1 regression against the live store shape."""
job = _job(job_id="guide-curator", minutes=4320)
- sched._running_job_ids.add(job["id"])
- sched._running_since[job["id"]] = time.time() - 4 * 60 * 60 # 4h ≪ 144h
+ sched._running_job_ids.add(sched._inflight_key(job["id"], tmp_path))
+ sched._running_since[sched._inflight_key(job["id"], tmp_path)] = time.time() - 4 * 60 * 60 # 4h ≪ 144h
with patch.object(sched, "_get_hermes_home", return_value=tmp_path):
assert sched.sweep_stale_inflight([job]) == []
@@ -234,8 +234,8 @@ class TestStaleInflightSweep:
"""A weekly cron job (cadence 10080m) is not clipped at 30m: a 24h
claim is still healthy (allowance 20160m)."""
job = _job(job_id="weekly", kind="cron", cron_expr="0 9 * * 1")
- sched._running_job_ids.add(job["id"])
- sched._running_since[job["id"]] = time.time() - 24 * 60 * 60
+ sched._running_job_ids.add(sched._inflight_key(job["id"], tmp_path))
+ sched._running_since[sched._inflight_key(job["id"], tmp_path)] = time.time() - 24 * 60 * 60
with patch.object(sched, "_get_hermes_home", return_value=tmp_path):
assert sched.sweep_stale_inflight([job]) == []
@@ -248,9 +248,9 @@ class TestStaleInflightSweep:
job = _job()
fut: concurrent.futures.Future = concurrent.futures.Future()
- sched._running_job_ids.add(job["id"])
- sched._running_since[job["id"]] = time.time() - 10 * 60 * 60
- sched._running_futures[job["id"]] = fut
+ sched._running_job_ids.add(sched._inflight_key(job["id"], tmp_path))
+ sched._running_since[sched._inflight_key(job["id"], tmp_path)] = time.time() - 10 * 60 * 60
+ sched._running_futures[sched._inflight_key(job["id"], tmp_path)] = fut
with patch.object(sched, "_get_hermes_home", return_value=tmp_path):
assert sched.sweep_stale_inflight([job]) == []
@@ -266,9 +266,9 @@ class TestStaleInflightSweep:
"""A claim whose submit path hung stays _FUTURE_PENDING past its
allowance (the SessionDB-init wedge class) and must be released."""
job = _job()
- sched._running_job_ids.add(job["id"])
- sched._running_since[job["id"]] = time.time() - 5 * 60 * 60
- sched._running_futures[job["id"]] = sched._FUTURE_PENDING
+ sched._running_job_ids.add(sched._inflight_key(job["id"], tmp_path))
+ sched._running_since[sched._inflight_key(job["id"], tmp_path)] = time.time() - 5 * 60 * 60
+ sched._running_futures[sched._inflight_key(job["id"], tmp_path)] = sched._FUTURE_PENDING
with patch.object(sched, "mark_job_run") as mark, \
patch.object(sched, "_get_hermes_home", return_value=tmp_path):
@@ -278,9 +278,9 @@ class TestStaleInflightSweep:
def test_pending_sentinel_young_claim_is_not_released(self, tmp_path):
"""A young pending claim (submit still in flight) is safe."""
job = _job()
- sched._running_job_ids.add(job["id"])
- sched._running_since[job["id"]] = time.time() - 60 # 1 minute
- sched._running_futures[job["id"]] = sched._FUTURE_PENDING
+ sched._running_job_ids.add(sched._inflight_key(job["id"], tmp_path))
+ sched._running_since[sched._inflight_key(job["id"], tmp_path)] = time.time() - 60 # 1 minute
+ sched._running_futures[sched._inflight_key(job["id"], tmp_path)] = sched._FUTURE_PENDING
with patch.object(sched, "mark_job_run") as mark, \
patch.object(sched, "_get_hermes_home", return_value=tmp_path):
@@ -292,8 +292,8 @@ class TestStaleInflightSweep:
"""A forced release must not consume a finite repeat budget or
auto-delete the row; the claim is released, the row untouched."""
job = _job(repeat={"times": 1, "completed": 0})
- sched._running_job_ids.add(job["id"])
- sched._running_since[job["id"]] = time.time() - 5 * 60 * 60
+ sched._running_job_ids.add(sched._inflight_key(job["id"], tmp_path))
+ sched._running_since[sched._inflight_key(job["id"], tmp_path)] = time.time() - 5 * 60 * 60
with patch.object(sched, "mark_job_run") as mark, \
patch.object(sched, "_get_hermes_home", return_value=tmp_path):
@@ -306,19 +306,19 @@ class TestStaleInflightSweep:
"""An id injected with no recorded start (pre-guard claim) must not be
released immediately, but must become sweepable."""
job = _job()
- sched._running_job_ids.add(job["id"])
+ sched._running_job_ids.add(sched._inflight_key(job["id"], tmp_path))
with patch.object(sched, "_get_hermes_home", return_value=tmp_path):
assert sched.sweep_stale_inflight([job]) == []
- assert job["id"] in sched._running_since
- sched._running_since[job["id"]] -= 5 * 60 * 60
+ assert sched._inflight_key(job["id"], tmp_path) in sched._running_since
+ sched._running_since[sched._inflight_key(job["id"], tmp_path)] -= 5 * 60 * 60
with patch.object(sched, "mark_job_run"):
assert sched.sweep_stale_inflight([job]) == [job["id"]]
def test_forced_release_logs_a_warning(self, tmp_path, caplog):
job = _job()
- sched._running_job_ids.add(job["id"])
- sched._running_since[job["id"]] = time.time() - 5 * 60 * 60
+ sched._running_job_ids.add(sched._inflight_key(job["id"], tmp_path))
+ sched._running_since[sched._inflight_key(job["id"], tmp_path)] = time.time() - 5 * 60 * 60
with caplog.at_level("WARNING"), \
patch.object(sched, "mark_job_run"), \
@@ -333,8 +333,8 @@ class TestWedgedJobRefiresWithoutRestart:
"""End-to-end symptom: before the fix, tick() returned 0 forever."""
job = dict(_job(), enabled=True, next_run_at="2020-01-01T00:00:00",
deliver="local")
- sched._running_job_ids.add(job["id"])
- sched._running_since[job["id"]] = time.time() - 6 * 60 * 60
+ sched._running_job_ids.add(sched._inflight_key(job["id"], tmp_path))
+ sched._running_since[sched._inflight_key(job["id"], tmp_path)] = time.time() - 6 * 60 * 60
with patch.object(sched, "_get_hermes_home", return_value=tmp_path), \
patch.object(sched, "get_due_jobs", return_value=[job]), \
@@ -384,12 +384,12 @@ class TestLedgerTerminalReconciliation:
time.time() + offset_seconds, tz=timezone.utc
).isoformat()
- def _inject_young_claim(self, job_id: str) -> None:
+ def _inject_young_claim(self, job_id: str, home) -> None:
"""Claim is YOUNG (inside the 30m floor) so only the ledger-terminal
path, never the age path, can release it."""
- sched._running_job_ids.add(job_id)
+ sched._running_job_ids.add(sched._inflight_key(job_id, home))
if hasattr(sched, "_running_since"):
- sched._running_since[job_id] = time.time() - 60 # 1 minute old
+ sched._running_since[sched._inflight_key(job_id, home)] = time.time() - 60 # 1 minute old
def test_young_claim_with_terminal_ledger_row_is_released(self, tmp_path):
"""RED/GREEN: a terminal ledger row from THIS claim's run proves the
@@ -398,7 +398,7 @@ class TestLedgerTerminalReconciliation:
would leave it)."""
job = _job(job_id="ledger-terminal", minutes=10)
job_id = job["id"]
- self._inject_young_claim(job_id)
+ self._inject_young_claim(job_id, tmp_path)
with patch.object(sched, "_get_hermes_home", return_value=tmp_path), \
patch("cron.executions.latest_executions", return_value={
@@ -423,7 +423,7 @@ class TestLedgerTerminalReconciliation:
would double-dispatch the job."""
job = _job(job_id="prev-run-terminal", minutes=10)
job_id = job["id"]
- self._inject_young_claim(job_id)
+ self._inject_young_claim(job_id, tmp_path)
with patch.object(sched, "_get_hermes_home", return_value=tmp_path), \
patch("cron.executions.latest_executions", return_value={
@@ -444,7 +444,7 @@ class TestLedgerTerminalReconciliation:
the age bound."""
job = _job(job_id="no-claimed-at", minutes=10)
job_id = job["id"]
- self._inject_young_claim(job_id)
+ self._inject_young_claim(job_id, tmp_path)
with patch.object(sched, "_get_hermes_home", return_value=tmp_path), \
patch("cron.executions.latest_executions", return_value={
@@ -462,7 +462,7 @@ class TestLedgerTerminalReconciliation:
ledger reconciliation must not release claims it cannot prove ended."""
job = _job(job_id="no-ledger-row", minutes=10)
job_id = job["id"]
- self._inject_young_claim(job_id)
+ self._inject_young_claim(job_id, tmp_path)
with patch.object(sched, "_get_hermes_home", return_value=tmp_path), \
patch("cron.executions.latest_executions", return_value={}), \
@@ -478,7 +478,7 @@ class TestLedgerTerminalReconciliation:
double-dispatch a healthy long-running job."""
job = _job(job_id="still-running", minutes=10)
job_id = job["id"]
- self._inject_young_claim(job_id)
+ self._inject_young_claim(job_id, tmp_path)
with patch.object(sched, "_get_hermes_home", return_value=tmp_path), \
patch("cron.executions.latest_executions", return_value={
@@ -495,9 +495,9 @@ class TestLedgerTerminalReconciliation:
path (one release) — it must not double-release or double-count."""
job = _job(job_id="old-terminal", minutes=10)
job_id = job["id"]
- sched._running_job_ids.add(job_id)
+ sched._running_job_ids.add(sched._inflight_key(job_id, tmp_path))
if hasattr(sched, "_running_since"):
- sched._running_since[job_id] = time.time() - 6 * 60 * 60 # 6h old
+ sched._running_since[sched._inflight_key(job_id, tmp_path)] = time.time() - 6 * 60 * 60 # 6h old
with patch.object(sched, "_get_hermes_home", return_value=tmp_path), \
patch("cron.executions.latest_executions", return_value={
diff --git a/tests/cron/test_parallel_pool.py b/tests/cron/test_parallel_pool.py
index 3f8a8df7071..4a7515655d3 100644
--- a/tests/cron/test_parallel_pool.py
+++ b/tests/cron/test_parallel_pool.py
@@ -20,8 +20,8 @@ class TestPersistentPool:
import cron.scheduler as sched
# Reset module state.
- sched._parallel_pool = None
- sched._parallel_pool_max_workers = None
+ sched._parallel_pools.clear()
+ sched._parallel_pool_max_workers.clear()
pool1 = sched._get_parallel_pool(4)
pool2 = sched._get_parallel_pool(4)
@@ -35,13 +35,13 @@ class TestPersistentPool:
"""_shutdown_parallel_pool resets state."""
import cron.scheduler as sched
- sched._parallel_pool = None
- sched._parallel_pool_max_workers = None
+ sched._parallel_pools.clear()
+ sched._parallel_pool_max_workers.clear()
sched._get_parallel_pool(2)
sched._shutdown_parallel_pool()
- assert sched._parallel_pool is None
- assert sched._parallel_pool_max_workers is None
+ assert not sched._parallel_pools
+ assert not sched._parallel_pool_max_workers
class TestRunningJobGuard:
@@ -52,8 +52,8 @@ class TestRunningJobGuard:
import cron.scheduler as sched
# Reset state.
- sched._parallel_pool = None
- sched._parallel_pool_max_workers = None
+ sched._parallel_pools.clear()
+ sched._parallel_pool_max_workers.clear()
sched._running_job_ids.clear()
job = {
@@ -67,7 +67,7 @@ class TestRunningJobGuard:
}
# Simulate the job already running.
- sched._running_job_ids.add("guard-job")
+ sched._running_job_ids.add(sched._inflight_key("guard-job"))
dispatched = []
monkeypatch.setattr(sched, "get_due_jobs", lambda: [job])
@@ -81,7 +81,7 @@ class TestRunningJobGuard:
assert n == 0 # skipped, not dispatched
assert dispatched == []
- sched._running_job_ids.discard("guard-job")
+ sched._running_job_ids.discard(sched._inflight_key("guard-job"))
sched._shutdown_parallel_pool()
@@ -132,15 +132,15 @@ class TestRunningJobGuard:
future.set_result(result)
assert claim_calls == [("queued-job", {"return_job": True})]
- assert "queued-job" not in sched._running_job_ids
+ assert sched._inflight_key("queued-job") not in sched._running_job_ids
def test_create_execution_failure_does_not_wedge_running_set(self, tmp_path, monkeypatch):
"""create_execution failures clear the running lock and still allow next jobs."""
import cron.scheduler as sched
- sched._parallel_pool = None
- sched._parallel_pool_max_workers = None
+ sched._parallel_pools.clear()
+ sched._parallel_pool_max_workers.clear()
sched._running_job_ids.clear()
failing_job = {
@@ -194,8 +194,8 @@ class TestRunningJobGuard:
assert n == 1
assert called == ["healthy-job"]
- assert "failing-job" not in sched._running_job_ids
- assert "healthy-job" not in sched._running_job_ids
+ assert sched._inflight_key("failing-job") not in sched._running_job_ids
+ assert sched._inflight_key("healthy-job") not in sched._running_job_ids
sched._shutdown_parallel_pool()
@@ -207,8 +207,8 @@ class TestSyncMode:
"""sync=True waits for jobs and returns actual results."""
import cron.scheduler as sched
- sched._parallel_pool = None
- sched._parallel_pool_max_workers = None
+ sched._parallel_pools.clear()
+ sched._parallel_pool_max_workers.clear()
sched._running_job_ids.clear()
jobs = [
@@ -234,8 +234,8 @@ class TestSyncMode:
"""sync=False returns before parallel jobs finish (optimistic count)."""
import cron.scheduler as sched
- sched._parallel_pool = None
- sched._parallel_pool_max_workers = None
+ sched._parallel_pools.clear()
+ sched._parallel_pool_max_workers.clear()
sched._running_job_ids.clear()
job = {
@@ -281,8 +281,8 @@ class TestWorkdirParallelPool:
"""sync=False returns immediately even when a workdir job is slow."""
import cron.scheduler as sched
- sched._parallel_pool = None
- sched._parallel_pool_max_workers = None
+ sched._parallel_pools.clear()
+ sched._parallel_pool_max_workers.clear()
sched._running_job_ids.clear()
job = {
@@ -324,8 +324,8 @@ class TestWorkdirParallelPool:
"""A workdir job already in _running_job_ids is skipped on next tick."""
import cron.scheduler as sched
- sched._parallel_pool = None
- sched._parallel_pool_max_workers = None
+ sched._parallel_pools.clear()
+ sched._parallel_pool_max_workers.clear()
sched._running_job_ids.clear()
job = {
@@ -340,7 +340,7 @@ class TestWorkdirParallelPool:
}
# Simulate the job already running.
- sched._running_job_ids.add("guard-seq")
+ sched._running_job_ids.add(sched._inflight_key("guard-seq"))
dispatched = []
monkeypatch.setattr(sched, "get_due_jobs", lambda: [job])
@@ -354,7 +354,7 @@ class TestWorkdirParallelPool:
assert n == 0 # skipped, not dispatched
assert dispatched == []
- sched._running_job_ids.discard("guard-seq")
+ sched._running_job_ids.discard(sched._inflight_key("guard-seq"))
sched._shutdown_parallel_pool()
class TestTickBatchAdvance:
@@ -366,8 +366,8 @@ class TestTickBatchAdvance:
def test_tick_calls_advance_next_runs_once_with_all_due_ids(self, tmp_path, monkeypatch):
import cron.scheduler as sched
- sched._parallel_pool = None
- sched._parallel_pool_max_workers = None
+ sched._parallel_pools.clear()
+ sched._parallel_pool_max_workers.clear()
sched._running_job_ids.clear()
jobs = [
diff --git a/tests/cron/test_recurring_wedge_selfheal.py b/tests/cron/test_recurring_wedge_selfheal.py
index fd0d6ababd7..99f98075796 100644
--- a/tests/cron/test_recurring_wedge_selfheal.py
+++ b/tests/cron/test_recurring_wedge_selfheal.py
@@ -94,8 +94,8 @@ class TestStaleInflightSelfHeal:
S._running_job_ids.clear()
S._running_since.clear()
S._running_futures.clear()
- S._running_job_ids.add(job_id)
- S._running_since[job_id] = time.time() - 6 * 60 * 60
+ S._running_job_ids.add(S._inflight_key(job_id))
+ S._running_since[S._inflight_key(job_id)] = time.time() - 6 * 60 * 60
# get_due_jobs is called inside tick BEFORE the sweep; we patch it to
# return the wedged job as due so the in-cycle sweep releases the claim
@@ -124,8 +124,8 @@ class TestStaleInflightSelfHeal:
S._running_job_ids.clear()
S._running_since.clear()
S._running_futures.clear()
- S._running_job_ids.add(job_id)
- S._running_since[job_id] = time.time() - 6 * 60 * 60
+ S._running_job_ids.add(S._inflight_key(job_id))
+ S._running_since[S._inflight_key(job_id)] = time.time() - 6 * 60 * 60
job = J.get_job(job_id)
with mock.patch("cron.jobs.load_jobs", return_value=[job]):
@@ -151,8 +151,8 @@ class TestStaleInflightSelfHeal:
S._running_job_ids.clear()
S._running_since.clear()
S._running_futures.clear()
- S._running_job_ids.add(env["job_id"])
- S._running_since[env["job_id"]] = time.time() - 6 * 60 * 60
+ S._running_job_ids.add(S._inflight_key(env["job_id"]))
+ S._running_since[S._inflight_key(env["job_id"])] = time.time() - 6 * 60 * 60
S.sweep_stale_inflight([J.get_job(env["job_id"])])
stats = S.get_inflight_guard_stats()
assert stats["forced_releases"] >= 1
diff --git a/tests/cron/test_restart_safe_worker.py b/tests/cron/test_restart_safe_worker.py
index 89042435a8f..af9881c1212 100644
--- a/tests/cron/test_restart_safe_worker.py
+++ b/tests/cron/test_restart_safe_worker.py
@@ -446,7 +446,7 @@ def test_launch_external_worker_honors_ack_within_adoption_grace(
assert scheduler._launch_external_cron_worker(job) is True
# The acknowledged path records the worker pid; the ownership-uncertain
# timeout path never does.
- assert scheduler._running_worker_pids == {"job-cold": 4321}
+ assert scheduler._running_worker_pids == {scheduler._inflight_key("job-cold"): 4321}
def test_worker_dying_before_ack_names_its_stderr_cause(tmp_path, monkeypatch):
@@ -717,15 +717,15 @@ def test_shutdown_does_not_interrupt_restart_safe_waiter():
import cron.scheduler as scheduler
job_id = "external-waiter"
- scheduler._running_job_ids.add(job_id)
- scheduler._restart_safe_waiter_job_ids.add(job_id)
+ scheduler._running_job_ids.add(scheduler._inflight_key(job_id))
+ scheduler._restart_safe_waiter_job_ids.add(scheduler._inflight_key(job_id))
try:
assert scheduler.mark_running_jobs_interrupted("gateway restart") == []
- assert job_id not in scheduler._interrupted_job_ids
+ assert scheduler._inflight_key(job_id) not in scheduler._interrupted_job_ids
finally:
- scheduler._restart_safe_waiter_job_ids.discard(job_id)
- scheduler._running_job_ids.discard(job_id)
- scheduler._interrupted_job_ids.discard(job_id)
+ scheduler._restart_safe_waiter_job_ids.discard(scheduler._inflight_key(job_id))
+ scheduler._running_job_ids.discard(scheduler._inflight_key(job_id))
+ scheduler._interrupted_job_ids.discard(scheduler._inflight_key(job_id))
def test_worker_delivery_queue_is_keyed_by_the_delivering_jobs_own_execution(
diff --git a/tests/cron/test_sessiondb_init_hang.py b/tests/cron/test_sessiondb_init_hang.py
index b2f0f464651..56c0c31982a 100644
--- a/tests/cron/test_sessiondb_init_hang.py
+++ b/tests/cron/test_sessiondb_init_hang.py
@@ -239,8 +239,8 @@ class TestDispatchGuardReleasedAfterHang:
import cron.scheduler as sched
monkeypatch.setenv("HERMES_CRON_SESSION_DB_TIMEOUT", "0.2")
- sched._parallel_pool = None
- sched._parallel_pool_max_workers = None
+ sched._parallel_pools.clear()
+ sched._parallel_pool_max_workers.clear()
sched._running_job_ids.clear()
job = {
@@ -291,7 +291,7 @@ class TestDispatchGuardReleasedAfterHang:
n2 = sched.tick(verbose=False)
assert n2 == 1
finally:
- sched._running_job_ids.discard("guard-sessiondb-hang")
+ sched._running_job_ids.discard(sched._inflight_key("guard-sessiondb-hang"))
sched._shutdown_parallel_pool()
diff --git a/tests/cron/test_shutdown_interrupt.py b/tests/cron/test_shutdown_interrupt.py
index 940beebab62..81571333d54 100644
--- a/tests/cron/test_shutdown_interrupt.py
+++ b/tests/cron/test_shutdown_interrupt.py
@@ -41,8 +41,8 @@ class TestGetRunningJobIds:
def test_reflects_in_flight_jobs(self):
import cron.scheduler as sched
- sched._running_job_ids.add("job-1")
- sched._running_job_ids.add("job-2")
+ sched._running_job_ids.add(sched._inflight_key("job-1"))
+ sched._running_job_ids.add(sched._inflight_key("job-2"))
result = sched.get_running_job_ids()
@@ -54,9 +54,9 @@ class TestGetRunningJobIds:
on this to safely count in a tight polling loop."""
import cron.scheduler as sched
- sched._running_job_ids.add("job-1")
+ sched._running_job_ids.add(sched._inflight_key("job-1"))
snapshot = sched.get_running_job_ids()
- sched._running_job_ids.add("job-2")
+ sched._running_job_ids.add(sched._inflight_key("job-2"))
assert snapshot == frozenset({"job-1"})
@@ -74,12 +74,13 @@ class TestMarkRunningJobsInterrupted:
def test_marks_every_in_flight_job(self):
import cron.scheduler as sched
- sched._running_job_ids.update({"job-1", "job-2"})
+ sched._running_job_ids.update(
+ {sched._inflight_key("job-1"), sched._inflight_key("job-2")})
profile_home = sched._get_hermes_home().resolve()
sched._running_fire_owners.update(
{
- "job-1": {object(): ("owner-1", profile_home)},
- "job-2": {object(): ("owner-2", profile_home)},
+ sched._inflight_key("job-1"): {object(): ("owner-1", profile_home)},
+ sched._inflight_key("job-2"): {object(): ("owner-2", profile_home)},
}
)
@@ -99,12 +100,12 @@ class TestMarkRunningJobsInterrupted:
def test_sets_interrupted_flag_for_consumption_by_run_one_job(self):
import cron.scheduler as sched
- sched._running_job_ids.add("job-1")
+ sched._running_job_ids.add(sched._inflight_key("job-1"))
with patch("cron.scheduler.mark_job_run"):
sched.mark_running_jobs_interrupted("shutdown")
- assert "job-1" in sched._interrupted_job_ids
+ assert sched._inflight_key("job-1") in sched._interrupted_job_ids
def test_one_job_marking_failure_does_not_block_the_others(self):
"""mark_job_run raising for one job (e.g. a jobs.json write race)
@@ -112,12 +113,13 @@ class TestMarkRunningJobsInterrupted:
shutdown, there's no retry window."""
import cron.scheduler as sched
- sched._running_job_ids.update({"job-1", "job-2"})
+ sched._running_job_ids.update(
+ {sched._inflight_key("job-1"), sched._inflight_key("job-2")})
profile_home = sched._get_hermes_home().resolve()
sched._running_fire_owners.update(
{
- "job-1": {object(): ("owner-1", profile_home)},
- "job-2": {object(): ("owner-2", profile_home)},
+ sched._inflight_key("job-1"): {object(): ("owner-1", profile_home)},
+ sched._inflight_key("job-2"): {object(): ("owner-2", profile_home)},
}
)
@@ -150,8 +152,8 @@ class TestMarkRunningJobsInterrupted:
replacement = {**claimed, "fire_claim": replacement_claim}
jobs.save_jobs([replacement])
- sched._running_job_ids.add(created["id"])
- sched._running_fire_owners[created["id"]] = {
+ sched._running_job_ids.add(sched._inflight_key(created["id"]))
+ sched._running_fire_owners[sched._inflight_key(created["id"])] = {
object(): (stale_owner, profile_home)
}
marked = sched.mark_running_jobs_interrupted("shutdown")
@@ -173,7 +175,7 @@ class TestRunningFireOwnerRegistry:
}
def _observe_registry(current_job, run):
- assert list(sched._running_fire_owners[current_job["id"]].values()) == [
+ assert list(sched._running_fire_owners[sched._inflight_key(current_job["id"])].values()) == [
("owner-1", sched._get_hermes_home().resolve())
]
return True
@@ -181,7 +183,7 @@ class TestRunningFireOwnerRegistry:
with patch("cron.scheduler._run_with_fire_claim_heartbeat", side_effect=_observe_registry):
assert sched.run_one_job(job) is True
- assert job["id"] not in sched._running_fire_owners
+ assert sched._inflight_key(job["id"]) not in sched._running_fire_owners
def test_shutdown_sees_all_concurrent_direct_fire_owners(self, monkeypatch):
"""Direct entry points and replacement owners share one token registry."""
@@ -229,7 +231,7 @@ class TestRunningFireOwnerRegistry:
profile_a = tmp_path / "a"
profile_b = tmp_path / "b"
observed = []
- sched._running_fire_owners["same-job"] = {
+ sched._running_fire_owners[sched._inflight_key("same-job")] = {
object(): ("owner-a", profile_a),
object(): ("owner-b", profile_b),
}
@@ -266,20 +268,20 @@ class TestIsInterrupted:
def test_true_when_marked(self):
import cron.scheduler as sched
- sched._interrupted_job_ids.add("job-1")
+ sched._interrupted_job_ids.add(sched._inflight_key("job-1"))
assert sched._is_interrupted("job-1") is True
def test_does_not_clear_the_flag(self):
import cron.scheduler as sched
- sched._interrupted_job_ids.add("job-1")
+ sched._interrupted_job_ids.add(sched._inflight_key("job-1"))
sched._is_interrupted("job-1")
# Still set -- the later, authoritative check before mark_job_run
# must still see it.
- assert "job-1" in sched._interrupted_job_ids
+ assert sched._inflight_key("job-1") in sched._interrupted_job_ids
assert sched._is_interrupted("job-1") is True
@@ -288,7 +290,7 @@ class TestConsumeInterruptedFlag:
def test_true_and_clears_when_marked(self):
import cron.scheduler as sched
- sched._interrupted_job_ids.add("job-1")
+ sched._interrupted_job_ids.add(sched._inflight_key("job-1"))
assert sched._consume_interrupted_flag("job-1") is True
# Consumed -- a second check (e.g. a later, unrelated fire of the
@@ -310,7 +312,7 @@ class TestExecutionScopedInterruption:
profile_home = sched._get_hermes_home().resolve()
old_token = object()
- sched._running_fire_owners["job-1"] = {
+ sched._running_fire_owners[sched._inflight_key("job-1")] = {
old_token: ("owner-1", profile_home),
}
@@ -330,8 +332,8 @@ class TestExecutionScopedInterruption:
profile_home = sched._get_hermes_home().resolve()
token_a, token_b = object(), object()
- sched._running_fire_owners["job-a"] = {token_a: ("owner-a", profile_home)}
- sched._running_fire_owners["job-b"] = {token_b: ("owner-b", profile_home)}
+ sched._running_fire_owners[sched._inflight_key("job-a")] = {token_a: ("owner-a", profile_home)}
+ sched._running_fire_owners[sched._inflight_key("job-b")] = {token_b: ("owner-b", profile_home)}
with patch("cron.scheduler.mark_job_run", return_value=True) as mock_mark:
marked = sched.mark_running_jobs_interrupted(
@@ -352,7 +354,7 @@ class TestExecutionScopedInterruption:
profile_home = sched._get_hermes_home().resolve()
stale_token = object()
- sched._running_fire_owners["job-1"] = {
+ sched._running_fire_owners[sched._inflight_key("job-1")] = {
stale_token: ("stale-owner", profile_home),
}
with patch("cron.scheduler.mark_job_run", return_value=True):
@@ -551,7 +553,7 @@ class TestRunOneJobHonoursInterruptedFlag:
import cron.scheduler as sched
job = self._make_job()
- sched._interrupted_job_ids.add(job["id"])
+ sched._interrupted_job_ids.add(sched._inflight_key(job["id"]))
with patch("cron.scheduler.claim_dispatch", return_value=True), \
patch("agent.secret_scope.set_secret_scope", return_value=None), \
@@ -573,7 +575,7 @@ class TestRunOneJobHonoursInterruptedFlag:
mock_mark.assert_not_called()
# Flag is consumed so a later, unrelated fire of the same job ID
# isn't permanently silenced.
- assert job["id"] not in sched._interrupted_job_ids
+ assert sched._inflight_key(job["id"]) not in sched._interrupted_job_ids
def test_interrupted_job_delivers_failure_summary_not_raw_response(self):
"""The status-write guard alone isn't enough: delivery happens
@@ -586,7 +588,7 @@ class TestRunOneJobHonoursInterruptedFlag:
import cron.scheduler as sched
job = self._make_job()
- sched._interrupted_job_ids.add(job["id"])
+ sched._interrupted_job_ids.add(sched._inflight_key(job["id"]))
with patch("cron.scheduler.claim_dispatch", return_value=True), \
patch("agent.secret_scope.set_secret_scope", return_value=None), \
@@ -620,7 +622,7 @@ class TestRunOneJobHonoursInterruptedFlag:
import cron.scheduler as sched
job = self._make_job()
- sched._interrupted_job_ids.add(job["id"])
+ sched._interrupted_job_ids.add(sched._inflight_key(job["id"]))
with patch("cron.scheduler.claim_dispatch", return_value=True), \
patch("agent.secret_scope.set_secret_scope", return_value=None), \
diff --git a/tests/gateway/test_api_server_active_work_drain.py b/tests/gateway/test_api_server_active_work_drain.py
index 04b67bda05c..f4c9765ed92 100644
--- a/tests/gateway/test_api_server_active_work_drain.py
+++ b/tests/gateway/test_api_server_active_work_drain.py
@@ -211,13 +211,13 @@ class TestDrainWaitsForApiWork:
runner, _adapter = make_restart_runner()
runner._running_agents = {"session-1": MagicMock()}
- sched._running_job_ids.add("job-1")
+ sched._running_job_ids.add(sched._inflight_key("job-1"))
runner.adapters = {Platform.API_SERVER: _make_api_adapter(queued_ids=["run-1"])}
async def finish_all():
await asyncio.sleep(0.12)
runner._running_agents.clear()
- sched._running_job_ids.discard("job-1")
+ sched._running_job_ids.discard(sched._inflight_key("job-1"))
runner.adapters[Platform.API_SERVER]._active_run_tasks.clear()
task = asyncio.create_task(finish_all())
@@ -225,7 +225,7 @@ class TestDrainWaitsForApiWork:
_snapshot, timed_out = await runner._drain_active_agents(2.0)
finally:
await task
- sched._running_job_ids.discard("job-1")
+ sched._running_job_ids.discard(sched._inflight_key("job-1"))
assert timed_out is False
diff --git a/tests/gateway/test_cron_active_work_drain.py b/tests/gateway/test_cron_active_work_drain.py
index 521819767eb..cdab7442ad9 100644
--- a/tests/gateway/test_cron_active_work_drain.py
+++ b/tests/gateway/test_cron_active_work_drain.py
@@ -62,11 +62,11 @@ class TestDrainWaitsForCronWork:
import cron.scheduler as sched
runner, _adapter = make_restart_runner()
- sched._running_job_ids.add("job-1")
+ sched._running_job_ids.add(sched._inflight_key("job-1"))
async def finish_job():
await asyncio.sleep(0.12)
- sched._running_job_ids.discard("job-1")
+ sched._running_job_ids.discard(sched._inflight_key("job-1"))
task = asyncio.create_task(finish_job())
_snapshot, timed_out = await runner._drain_active_agents(2.0)
@@ -91,8 +91,8 @@ class TestKillToolSubprocessesMarksCronInterrupted:
runner._cron_drain_timeout = 0.01 # ...past the cron floor too (#82161)
adapter.disconnect = _make_async_noop()
- sched._running_job_ids.add("job-1")
- sched._running_fire_owners["job-1"] = {
+ sched._running_job_ids.add(sched._inflight_key("job-1"))
+ sched._running_fire_owners[sched._inflight_key("job-1")] = {
object(): ("owner-1", sched._get_hermes_home().resolve())
}
diff --git a/tests/gateway/test_cron_ticks_every_profile.py b/tests/gateway/test_cron_ticks_every_profile.py
new file mode 100644
index 00000000000..67bba150380
--- /dev/null
+++ b/tests/gateway/test_cron_ticks_every_profile.py
@@ -0,0 +1,86 @@
+"""The host gateway's cron ticker visits every profile, flag or no flag.
+
+``gateway.multiplex_profiles`` gates ADAPTERS. Cron ownership is not optional: one gateway process
+per host ticks every profile's store, so a secondary profile's due job fires even when the flag is
+off. Before this, ``_start_gateway_start_cron_and_housekeeping`` only passed ``profile_homes`` when
+the flag was on and every non-launch profile's cron silently never fired.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import threading
+import types
+
+import pytest
+
+
+class _CapturedTicker:
+ """Stands in for ``SupervisedTickerThread``; records the ticker's start kwargs."""
+
+ captured: dict = {}
+
+ def __init__(self, target, *, args=(), kwargs=None, stop_event=None, name="cron"):
+ _CapturedTicker.captured = dict(kwargs or {})
+ self.restarts = 0
+
+ def start(self):
+ return None
+
+ def restart_if_dead(self):
+ return None
+
+ def is_alive(self):
+ return False
+
+
+def isolated_profiles(tmp_path, monkeypatch):
+ """A scratch HOME so profile enumeration can never read or write the live install."""
+ fake_home = tmp_path / "fakehome"
+ hermes_home = fake_home / ".hermes"
+ (hermes_home / "profiles" / "secondary").mkdir(parents=True)
+ # A dir is only a profile once it carries an identity marker.
+ (hermes_home / "profiles" / "secondary" / "config.yaml").write_text("{}\n")
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ from hermes_cli import profiles as profiles_mod
+
+ assert str(profiles_mod._get_profiles_root()).startswith(str(tmp_path))
+ return hermes_home
+
+
+def test_secondary_profile_is_ticked_with_multiplex_profiles_off(
+ isolated_profiles, monkeypatch
+):
+ from cron import scheduler_thread
+ from gateway import run as gateway_run
+
+ monkeypatch.setattr(scheduler_thread, "SupervisedTickerThread", _CapturedTicker)
+ monkeypatch.setattr(
+ gateway_run, "_start_gateway_housekeeping", lambda *_a, **_kw: None)
+
+ runner = types.SimpleNamespace(
+ config=types.SimpleNamespace(multiplex_profiles=False),
+ adapters={},
+ _profile_adapters=None,
+ _primary_profile_name="default",
+ _draining=False,
+ _external_drain_active=False,
+ )
+
+ async def _start():
+ return gateway_run._start_gateway_start_cron_and_housekeeping(runner)
+
+ cron_stop, _provider, _thread, housekeeping = asyncio.run(_start())
+ cron_stop.set()
+ if isinstance(housekeeping, threading.Thread):
+ housekeeping.join(timeout=5)
+
+ enumerate_homes = _CapturedTicker.captured.get("profile_homes")
+ assert enumerate_homes is not None, (
+ "the ticker must be given the profile set even with multiplex_profiles off"
+ )
+ served = {name for name, _home in enumerate_homes()}
+ assert "secondary" in served, "a secondary profile's cron must still be ticked"
diff --git a/tests/gateway/test_drain_active_work_report.py b/tests/gateway/test_drain_active_work_report.py
index 33d3c14b506..bc6b2be98a7 100644
--- a/tests/gateway/test_drain_active_work_report.py
+++ b/tests/gateway/test_drain_active_work_report.py
@@ -38,7 +38,7 @@ def test_draining_status_names_chat_and_cron_units_and_clears_when_running(tmp_p
assert sched.try_register_running_job("job-a")
try:
with sched._running_lock:
- sched._running_worker_pids["job-a"] = 4242
+ sched._running_worker_pids[sched._inflight_key("job-a")] = 4242
runner._update_runtime_status("draining")
flush_runtime_status()
record = json.loads((tmp_path / "gateway_state.json").read_text())
diff --git a/tests/gateway/test_restart_drain.py b/tests/gateway/test_restart_drain.py
index a524b8763d8..f9d0f191619 100644
--- a/tests/gateway/test_restart_drain.py
+++ b/tests/gateway/test_restart_drain.py
@@ -535,7 +535,7 @@ async def test_request_restart_skips_wait_for_cron_run_past_inflight_allowance(m
assert sched.try_register_running_job("hung-delivery-job")
try:
with sched._running_lock:
- sched._running_since["hung-delivery-job"] = time.time() - 702 * 60
+ sched._running_since[sched._inflight_key("hung-delivery-job")] = time.time() - 702 * 60
assert runner._wedged_agent_count() == 1 and runner._awaitable_work_count() == 0
cron_units = [u for u in runner._describe_active_work() if u["kind"] == "cron"]
assert cron_units[0]["job_id"] == "hung-delivery-job" and cron_units[0]["wedged"] is True
@@ -558,10 +558,10 @@ def test_wedged_cron_allowance_honours_young_runs_and_job_interval(monkeypatch,
try:
assert runner._wedged_agent_count() == 0 and runner._awaitable_work_count() == 1
with sched._running_lock:
- sched._running_since["six-hourly-job"] = time.time() - 11 * 3600 # past the 30m floor, inside 2 * 6h
+ sched._running_since[sched._inflight_key("six-hourly-job")] = time.time() - 11 * 3600 # past the 30m floor, inside 2 * 6h
assert runner._wedged_agent_count() == 0
with sched._running_lock:
- sched._running_since["six-hourly-job"] = time.time() - 13 * 3600
+ sched._running_since[sched._inflight_key("six-hourly-job")] = time.time() - 13 * 3600
assert runner._wedged_agent_count() == 1 and runner._awaitable_work_count() == 0
finally:
sched.release_running_job("six-hourly-job")
@@ -583,7 +583,7 @@ def test_wedged_cron_check_parses_jobs_once_per_run(monkeypatch, tmp_path):
assert sched.get_wedged_job_ids() == frozenset()
assert len(loads) == 1
with sched._running_lock:
- sched._running_since["job-b"] = time.time() - 13 * 3600
+ sched._running_since[sched._inflight_key("job-b")] = time.time() - 13 * 3600
assert sched.get_wedged_job_ids() == frozenset({"job-b"})
assert len(loads) == 1
finally:
diff --git a/tests/hermes_cli/test_web_server_idle_proof.py b/tests/hermes_cli/test_web_server_idle_proof.py
index 424423cec54..bb8b5908a91 100644
--- a/tests/hermes_cli/test_web_server_idle_proof.py
+++ b/tests/hermes_cli/test_web_server_idle_proof.py
@@ -47,13 +47,13 @@ def test_idle_proof_reads_the_real_cron_and_human_input_ledgers():
assert idle_proof()["idle"] is True
with scheduler._running_lock:
- scheduler._running_job_ids.add("idle-proof-live-job")
+ scheduler._running_job_ids.add(scheduler._inflight_key("idle-proof-live-job"))
try:
# The busy verdict names the ledger and the job, so a backend that will not retire is diagnosable.
assert idle_proof() == {"idle": False, "reason": "turn_in_flight", "detail": "cron:idle-proof-live-job"}
finally:
with scheduler._running_lock:
- scheduler._running_job_ids.discard("idle-proof-live-job")
+ scheduler._running_job_ids.discard(scheduler._inflight_key("idle-proof-live-job"))
from tools.approval_gateway_wait import _ApprovalEntry
@@ -129,7 +129,7 @@ def _spawn_desktop_child(tmp_path: Path, name: str, *, busy: bool) -> subprocess
hold = (
"import cron.scheduler as s\n"
"with s._running_lock:\n"
- " s._running_job_ids.add('live-idle-proof-job')\n"
+ " s._running_job_ids.add(s._inflight_key('live-idle-proof-job'))\n"
) if busy else ""
code = (
hold
diff --git a/website/docs/developer-guide/cron-internals.md b/website/docs/developer-guide/cron-internals.md
index f0d212b859c..1d9eac7383b 100644
--- a/website/docs/developer-guide/cron-internals.md
+++ b/website/docs/developer-guide/cron-internals.md
@@ -164,8 +164,12 @@ dropped silently. The mechanics, in the order the due scan applies them
One-shots and future instants recompute from now on resume.
The same store fields drive every topology: a standalone `hermes -p X gateway
-run` and a profile served by the default multiplexer (`_start_multiplex` ticks
-each home under `_profile_cron_scope`) evaluate the identical record.
+run` and a profile served by the host gateway (`_start_multiplex` ticks each
+home under `_profile_cron_scope`) evaluate the identical record. One gateway
+process per host ticks *every* profile's store — `gateway.multiplex_profiles`
+gates adapters, not cron — and per-run bookkeeping (in-flight claims, the
+parallel worker pool, the stale-code yield decision) is keyed by profile home,
+so two profiles may carry identically named jobs without colliding.
**Fire-claim lease during a run.** A firing run holds `fire_claim = {at, by}` and
a heartbeat thread refreshes `at` every 60 s (the lease is 300 s). A heartbeat