Skip to content

The agent that grows with you

fix(cron): report acknowledged worker failures without losing diagnostics

unsupportedpastels9830058c00f8
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 443beec1b8e..8a04f805d54 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -2728,15 +2728,19 @@ def run_one_job(
external_owner = os.environ.get("_HERMES_CRON_EXTERNAL_WORKER") == execution_id
if not external_owner:
try:
- if _launch_external_cron_worker(job):
- return True
+ handed_off = _launch_external_cron_worker(job)
except Exception as handoff_error:
- # Past the handoff the worker may have adopted the row, run side effects
- # and sent its own notice: record bookkeeping only, never a false
- # "dispatch failed" incident/ping.
+ # Arbitrary waiter errors must not claim dispatch failure or resend
+ # a worker's notice. A recovered unknown execution is different:
+ # its worker never committed a terminal outcome.
post_handoff = isinstance(handoff_error, _ExternalWorkerPostHandoffError)
stage = "failed after handoff" if post_handoff else "dispatch failed"
error = f"Restart-safe cron worker {stage}: {handoff_error}"
+ if post_handoff:
+ from cron.scheduler_worker_failure import record_unknown_worker_outcome
+
+ if record_unknown_worker_outcome(job, error=str(handoff_error), adapters=adapters, loop=loop):
+ return True
logger.error("Job '%s': %s", job["id"], error)
claim = job.get("fire_claim")
owner = str(claim.get("by") or "") if isinstance(claim, dict) else ""
@@ -2761,6 +2765,11 @@ def run_one_job(
execution_id, success=False, error=error,
delivery_outcome=delivery_outcome)
return True
+ if handed_off:
+ from cron.scheduler_worker_failure import record_unknown_worker_outcome
+
+ record_unknown_worker_outcome(job, adapters=adapters, loop=loop)
+ return True
if extra_prompt is None:
# Gateway-forwarded manual run stamps its prompt on the job via trigger_job; the fire that
# consumes the manual occurrence picks it up here. Single-fire: mark_job_run clears it.
@@ -3415,22 +3424,6 @@ def _run_one_job_body(
reset_terminal_scope(_terminal_scope_token)
-def _external_worker_exited_reason(returncode: Optional[int]) -> str:
- """Cause for an attempt whose restart-safe worker this process watched exit.
-
- The generic dead-owner sweep can only say the owner vanished, so it names a
- scheduler restart — but this waiter never lost its scheduler: it handed the
- attempt to the external worker and then saw that worker exit with this status.
- The run is still ``unknown`` rather than ``failed`` (whether side effects ran is
- still unknown); only the cause becomes truthful (#128509).
- """
- return (
- f"Restart-safe cron worker exited with status {returncode} after adopting this "
- "execution, without writing a durable terminal state; whether side effects ran "
- "is unknown."
- )
-
-
def _wait_for_external_cron_worker_body(
process: subprocess.Popen,
*,
@@ -3466,7 +3459,8 @@ def _wait_for_external_cron_worker_body(
# The worker can commit its terminal row and exit between the first
# read and wait(). Re-read the exact attempt before declaring that
# it died without terminalizing.
- if _is_terminal():
+ current = get_execution(execution_id)
+ if current and current.get("status") in ("completed", "failed"):
return True
# If the adopted worker died without terminalizing, its owner is
# now provably gone. Recover to ``unknown`` rather than routing the
@@ -3479,21 +3473,23 @@ def _wait_for_external_cron_worker_body(
# mark_job_run entirely and the job's fire claim outlived its lost
# execution, refusing the next manual fire with "Job is already being
# fired" (#128509). Raising routes the existing post-handoff bookkeeping
- # instead — record the run, no dispatch incident, no crash notice.
- reason = _external_worker_exited_reason(returncode)
+ # instead: retire the claim and report the uncertain run, not a pre-dispatch failure.
+ from cron.scheduler_worker_failure import external_worker_exited_reason
+
+ reason = external_worker_exited_reason(returncode)
if not terminalize_dead_owner(execution_id, reason=reason):
recover_interrupted_executions()
- if _is_terminal():
+ # A concurrent sweep may have won the unknown transition. Still
+ # surface this waiter's exit code and stderr instead of discarding them.
+ current = get_execution(execution_id)
+ if current and current.get("status") in ("completed", "failed"):
return True
stderr_tail = ""
if stderr_path is not None:
from cron.scheduler_diagnostics import external_worker_stderr_tail
stderr_tail = external_worker_stderr_tail(stderr_path)
- raise RuntimeError(
- "cron external worker exited before durable recovery could terminalize "
- f"its execution state (exit {returncode}): {reason}{stderr_tail}"
- )
+ raise RuntimeError(f"{reason}{stderr_tail}")
class _ExternalWorkerPostHandoffError(RuntimeError):
@@ -3854,17 +3850,17 @@ def _run_external_worker_payload(payload_path: Path, ack_path: Path) -> bool:
old_external_execution = os.environ.get("_HERMES_CRON_EXTERNAL_WORKER")
os.environ["_HERMES_CRON_EXTERNAL_WORKER"] = execution_id
try:
- return run_one_job(job, adapters=None, loop=None, verbose=False)
+ completed = run_one_job(job, adapters=None, loop=None, verbose=False)
+ # Successful return: the worker recorded its outcome. If it raises,
+ # retain fd 2's pathname until the waiter consumes the traceback.
+ with contextlib.suppress(OSError):
+ ack_path.with_suffix(".stderr").unlink(missing_ok=True)
+ return completed
finally:
if old_external_execution is None:
os.environ.pop("_HERMES_CRON_EXTERNAL_WORKER", None)
else:
os.environ["_HERMES_CRON_EXTERNAL_WORKER"] = old_external_execution
- # Post-ack the gateway never reads the stderr capture (it only
- # serves the pre-ack death report) and may not outlive this run
- # in the restart-safe topology, so the worker removes its own.
- with contextlib.suppress(OSError):
- ack_path.with_suffix(".stderr").unlink(missing_ok=True)
finally:
if secret_token is not None:
reset_secret_scope(secret_token)
diff --git a/cron/scheduler_worker_failure.py b/cron/scheduler_worker_failure.py
new file mode 100644
index 00000000000..278510f5bc6
--- /dev/null
+++ b/cron/scheduler_worker_failure.py
@@ -0,0 +1,58 @@
+"""Job-level visibility for a recovered, acknowledged worker death."""
+
+
+def record_unknown_worker_outcome(
+ job: dict, *, error=None, adapters=None, loop=None
+) -> bool:
+ """Project only this fire's uncertain outcome, without retrying its side effects.
+
+ A terminal ledger row alone does not retire the job claim or notify its owner.
+ Fence the notice and bookkeeping together so recovery cannot overwrite a newer
+ fire or duplicate a failure the worker already recorded.
+ """
+ from cron import scheduler
+
+ execution = scheduler.get_execution(str(job["execution_id"]))
+ if not execution or execution.get("status") != "unknown":
+ return False
+ claim = job.get("fire_claim")
+ owner = str(claim.get("by") or "") if isinstance(claim, dict) else ""
+ if not owner:
+ return False
+ with scheduler.fire_claim_fence(job["id"], expected_owner=owner) as owns_claim:
+ if not owns_claim:
+ return True
+ error = error or execution["error"]
+ scheduler.logger.error("Job '%s': %s", job["id"], error)
+ scope_tokens = scheduler._install_fire_secret_scope()
+ delivery_error = None
+ try:
+ delivery_error, _ = scheduler._deliver_crash_failure(
+ job, error, adapters=adapters, loop=loop
+ )
+ finally:
+ scheduler._reset_fire_secret_scope(scope_tokens)
+ scheduler.mark_job_run(
+ job["id"],
+ False,
+ error,
+ delivery_error=delivery_error,
+ expected_fire_owner=owner,
+ )
+ return True
+
+
+def external_worker_exited_reason(returncode: int | None) -> str:
+ """Cause for an attempt whose restart-safe worker this process watched exit.
+
+ The generic dead-owner sweep can only say the owner vanished, so it names a
+ scheduler restart — but this waiter never lost its scheduler: it handed the
+ attempt to the external worker and then saw that worker exit with this status.
+ The run is still ``unknown`` rather than ``failed`` (whether side effects ran is
+ still unknown); only the cause becomes truthful (#128509).
+ """
+ return (
+ f"Restart-safe cron worker exited with status {returncode} after adopting this "
+ "execution, without writing a durable terminal state; whether side effects ran "
+ "is unknown."
+ )
diff --git a/tests/cron/test_restart_safe_worker.py b/tests/cron/test_restart_safe_worker.py
index 461a69ad2b2..c61eb0233ab 100644
--- a/tests/cron/test_restart_safe_worker.py
+++ b/tests/cron/test_restart_safe_worker.py
@@ -536,9 +536,8 @@ def test_external_worker_crash_recovers_uncertain_attempt(monkeypatch):
process.poll.return_value = 9
process.wait.return_value = 9
- assert scheduler._wait_for_external_cron_worker(
- process, execution_id="exec-1"
- ) is True
+ with pytest.raises(scheduler._ExternalWorkerPostHandoffError, match="status 9"):
+ scheduler._wait_for_external_cron_worker(process, execution_id="exec-1")
recover.assert_called_once_with()
assert get.call_count == 2
diff --git a/tests/cron/test_restart_safe_worker_death_evidence.py b/tests/cron/test_restart_safe_worker_death_evidence.py
index 116c9135d39..46e608870b1 100644
--- a/tests/cron/test_restart_safe_worker_death_evidence.py
+++ b/tests/cron/test_restart_safe_worker_death_evidence.py
@@ -1,131 +1,125 @@
-"""Durable evidence when a restart-safe cron worker dies AFTER adopting its attempt.
-
-Regression for #128509. A ``cronjob(action='run')`` fired inside a gateway agent turn
-returns ``executed=true / execution_mode=background``, then the attempt dies. The waiter
-learns the adopted worker exited and calls ``recover_interrupted_executions()``, which only
-knows "the owner is gone" and stamps the generic ``_OWNER_GONE_REASON`` -- "Scheduler
-restarted after this execution's owner exited" -- a restart that never happened. The waiter
-then returns success, so ``run_one_job`` short-circuits and never calls ``mark_job_run``:
-
-* the job's ``fire_claim`` is left behind, so the next manual fire is refused with
- "Job is already being fired by the scheduler" until the 300s lease expires, and
-* ``last_error`` stays empty, so the operator has no error and no cause anywhere.
-
-The worker is not in the calling turn's process group (``start_new_session=True`` plus a
-``systemd-run --user --scope`` cgroup), so turn teardown never signalled it: the child
-crashed on its own. What the gateway still owes the operator is a truthful cause and a
-released claim.
-"""
-
-from __future__ import annotations
+"""Post-adoption failure visibility (#128509, #129254), not the unknown crash cause."""
import json
-import subprocess
import sys
+import subprocess
import time
-from pathlib import Path
import pytest
-# A real worker process: it adopts the durable row (the ownership rewrite that makes the
-# reported status line reachable), publishes the acknowledgement, then dies on its own.
-# The sleep keeps the parent's ack poll (every 50ms) deterministically ahead of the exit.
-_WORKER_THAT_DIES_AFTER_ADOPTION = """
-import json, os, sys, time
-from pathlib import Path
-
-argv = sys.argv[1:]
-payload_path = Path(argv[argv.index("--external-worker-file") + 1])
-ack_path = Path(argv[argv.index("--ack-file") + 1])
-
-import cron.executions as executions
-job = json.loads(payload_path.read_text(encoding="utf-8-sig"))["job"]
-assert executions.adopt_claimed_execution(job["execution_id"]) is not None
-ack_path.write_text(
- json.dumps({"pid": os.getpid(), "execution_id": job["execution_id"]}),
- encoding="utf-8",
[email protected]("manual", [False, True])
+ "death", ["hard_exit", "payload_exception", "concurrent_recovery"]
)
-time.sleep(1.5)
-os._exit(9)
-"""
-
-
-def profile_store(tmp_path, monkeypatch):
- """A real profile-scoped cron store, ledger and scheduler home, all on one temp path."""
- from cron.jobs import create_job, use_cron_store
-
- home = tmp_path / "home"
- home.mkdir()
- monkeypatch.setenv("HERMES_HOME", str(home))
- import cron.executions as executions
- import cron.scheduler as scheduler
-
- monkeypatch.setattr(scheduler, "_hermes_home", home)
- monkeypatch.setattr(executions, "EXECUTIONS_FILE", home / "cron" / "executions.db")
- monkeypatch.setattr(scheduler, "load_config_readonly", lambda: {})
- return home
-
-
-def test_worker_dying_after_adoption_reports_its_cause_and_releases_the_claim(
- tmp_path, monkeypatch, profile_store
-):
- """The run is lost either way; the ledger must not blame a restart that never
- happened, the job must be claimable again, and the operator must get a cause."""
+def test_adopted_worker_failure_is_visible(tmp_path, monkeypatch, manual, death):
import cron.executions as executions
import cron.scheduler as scheduler
from cron.jobs import claim_job_for_fire, create_job, get_job, use_cron_store
from tools.process_registry import GatewayChildDispatch
- home = profile_store
- with use_cron_store(home):
- job = create_job(prompt="summarise the day", schedule="every 1h", name="daily brief")
- claimed = claim_job_for_fire(job["id"], manual=True, return_job=True)
- assert claimed, "the manual claim must succeed or this test proves nothing"
-
- worker = tmp_path / "worker_that_dies.py"
- worker.write_text(_WORKER_THAT_DIES_AFTER_ADOPTION, encoding="utf-8")
+ print("SCHEDULER", scheduler.__file__, flush=True)
+ home = tmp_path / "profile"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setattr(executions, "EXECUTIONS_FILE", home / "cron" / "executions.db")
+ monkeypatch.setattr(scheduler, "load_config_readonly", lambda: {})
+ if death == "concurrent_recovery":
+ terminalize = scheduler.terminalize_dead_owner
- def dispatch(command, *, unit_suffix, require_restart_safe_scope=False):
- # Keep the launcher's real payload/ack argv; swap only the child's body so the
- # spawn, the acknowledgement poll and the wait all run for real.
- flags = command[command.index("--external-worker-file"):]
- return GatewayChildDispatch(
- "degraded", [sys.executable, str(worker), *flags])
+ def sweep_first(*args, **kwargs):
+ executions.recover_interrupted_executions()
+ return terminalize(*args, **kwargs)
+ monkeypatch.setattr(scheduler, "terminalize_dead_owner", sweep_first)
+ delivered = []
monkeypatch.setattr(
- "tools.process_registry.restart_safe_gateway_child_argv", dispatch)
+ scheduler, "_deliver_result", lambda *a, **k: delivered.append(True)
+ )
+ worker = tmp_path / "worker.py"
+ worker.write_text(
+ """
+import json, os, sys, time
+from pathlib import Path
+import cron.scheduler as scheduler
+import cron.executions as executions
+args = sys.argv
+payload = Path(args[args.index("--external-worker-file") + 1])
+ack = Path(args[args.index("--ack-file") + 1])
+def fail(*args, **kwargs):
+ time.sleep(2)
+ raise RuntimeError("worker-probe-startup-sentinel")
+if DEATH == "payload_exception":
+ scheduler.run_one_job = fail
+ scheduler._run_external_worker_payload(payload, ack)
+else:
+ data = json.loads(payload.read_text())
+ eid = data["job"]["execution_id"]
+ assert executions.adopt_claimed_execution(eid)
+ ack.write_text(json.dumps({"pid": os.getpid(), "execution_id": eid}))
+ time.sleep(2)
+ sys.stderr.write("worker-probe-startup-sentinel\\n")
+ sys.stderr.flush()
+ os._exit(9)
+""".replace("DEATH", repr(death)),
+ encoding="utf-8",
+ )
- assert scheduler.run_one_job(claimed, adapters=None) is True
- execution_id = claimed["execution_id"]
+ def dispatch(command, **kwargs):
+ flags = command[command.index("--external-worker-file") :]
+ return GatewayChildDispatch("degraded", [sys.executable, str(worker), *flags])
+ monkeypatch.setattr(
+ "tools.process_registry.restart_safe_gateway_child_argv", dispatch
+ )
with use_cron_store(home):
+ job = create_job(prompt="Reply OK", schedule="every 1h", deliver="local")
+ claimed = claim_job_for_fire(job["id"], manual=True, return_job=True)
+ assert claimed
+ if not manual:
+ execution = executions.create_execution(job["id"], source="builtin")
+ claimed["execution_id"] = execution["id"]
+ assert scheduler.run_one_job(claimed)
record = get_job(job["id"])
- # The claim is what makes the next manual fire say "Job is already being fired";
- # only mark_job_run retires it, and the lost waiter used to never call it.
- assert record["fire_claim"] is None, "the fire claim outlived its lost execution"
- assert claim_job_for_fire(job["id"], manual=True) is True
-
- # A truthful cause: this waiter never lost its scheduler, it watched ITS worker
- # exit. The generic dead-owner sweep can only assert a restart.
- assert record["last_error"], "a lost run recorded no error at all"
- assert "Scheduler restarted" not in record["last_error"]
- assert "exit 9" in record["last_error"]
-
- # Still `unknown`, not a fabricated durable state: side effects really are unknown.
- row = executions.get_execution(execution_id)
- assert row["status"] == "unknown"
- assert "Scheduler restarted" not in (row["error"] or "")
+ row = executions.get_execution(claimed["execution_id"])
+ result = {
+ "manual": manual,
+ "death": death,
+ "state": row["status"],
+ "claim_released": record.get("fire_claim") is None,
+ "job_error": record.get("last_error"),
+ "ledger_error": row.get("error"),
+ "notice_calls": len(delivered),
+ }
+ print("PROBE", json.dumps(result), flush=True)
+ assert row["status"] == "unknown"
+ if death != "concurrent_recovery":
+ assert "Scheduler restarted" not in row["error"]
+ assert result["claim_released"], result
+ assert "worker-probe-startup-sentinel" in (result["job_error"] or ""), result
+ assert len(delivered) == 1, result
+ from cron.scheduler_worker_failure import record_unknown_worker_outcome
+
+ # Re-observing an old terminal row cannot notify twice or erase a newer fire.
+ record_unknown_worker_outcome(claimed)
+ assert len(delivered) == 1
+ assert claim_job_for_fire(job["id"], manual=True)
+ replacement = get_job(job["id"])["fire_claim"]
+ record_unknown_worker_outcome(claimed)
+ assert get_job(job["id"])["fire_claim"] == replacement
+ assert len(delivered) == 1
def test_terminalizer_refuses_an_attempt_whose_worker_is_still_alive(
- profile_store,
+ tmp_path,
+ monkeypatch,
):
"""The targeted terminalizer must not steal a LIVE worker's attempt: refusing a live
owner is what keeps the fix from becoming a second way to lose side effects."""
import cron.executions as executions
+ monkeypatch.setattr(executions, "EXECUTIONS_FILE", tmp_path / "executions.db")
+
script = (
"import sys, time\n"
"from pathlib import Path\n"
@@ -139,8 +133,8 @@ def test_terminalizer_refuses_an_attempt_whose_worker_is_still_alive(
record = executions.create_execution("job-live", source="direct")
assert executions.mark_execution_handoff_pending(record["id"]) is not None
live_worker = subprocess.Popen(
- [sys.executable, "-c", script, record["id"]],
- stdout=subprocess.PIPE, text=True)
+ [sys.executable, "-c", script, record["id"]], stdout=subprocess.PIPE, text=True
+ )
try:
deadline = time.monotonic() + 30.0
while time.monotonic() < deadline:
@@ -149,8 +143,7 @@ def test_terminalizer_refuses_an_attempt_whose_worker_is_still_alive(
time.sleep(0.05)
assert executions.get_execution(record["id"])["status"] == "running"
- assert executions.terminalize_dead_owner(
- record["id"], reason="exit 9") is False
+ assert executions.terminalize_dead_owner(record["id"], reason="exit 9") is False
assert executions.get_execution(record["id"])["status"] == "running"
finally:
live_worker.kill()