fix(cron): a restart-safe worker that dies before its ack reports its own stderr
`_launch_external_cron_worker` spawned the worker with `stderr=DEVNULL`, so a worker that crashed before publishing its acknowledgement — an import error, a module missing from the interpreter it was handed, a bad payload — surfaced only as "exited before ownership acknowledgement (exit 1)". #112729 shows the cost: the reporter, a claimant and a reviewer spent three rounds guessing at the mechanism (sys.executable symlinks — refuted) because the worker's actual traceback was thrown away. The worker's own log handler is installed only after `cron.scheduler` imports, so an import-time failure never reaches agent.log either. Capture stderr into `<home>/cron/external-workers/<execution_id>.stderr` (0o600), and on a pre-ack exit append a redacted tail of it to the dispatch error (which lands in `last_error`, the executions ledger and the gateway log). The file rides in `handoff_files` so every exit path removes it; the tail helper lives in `scheduler_diagnostics` next to the run-error redaction. Part of #112729
This commit is contained in:
1 parent
2452b882ad
commit
e094e25b26
3 files changed
+72
-15
No files matched your search
+25
-15
@@ -3140,6 +3140,8 @@ def _launch_external_cron_worker(job: dict) -> bool:
|
||||
handoff_dir = _get_hermes_home() / "cron" / "external-workers"
|
||||
payload_path = handoff_dir / f"{execution_id}.json"
|
||||
ack_path = handoff_dir / f"{execution_id}.ready"
|
||||
# Captured so a worker that dies before its acknowledgement can name the cause (#112729).
|
||||
stderr_path = handoff_dir / f"{execution_id}.stderr"
|
||||
command = [
|
||||
sys.executable,
|
||||
"-m",
|
||||
@@ -3229,18 +3231,23 @@ def _launch_external_cron_worker(job: dict) -> bool:
|
||||
):
|
||||
worker_env.pop(_presence_var, None)
|
||||
try:
|
||||
process = subprocess.Popen(
|
||||
dispatch.argv,
|
||||
cwd=str(Path(__file__).resolve().parent.parent),
|
||||
env=worker_env,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
start_new_session=True,
|
||||
creationflags=windows_hide_flags(),
|
||||
)
|
||||
stderr_fd = os.open(stderr_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
try:
|
||||
process = subprocess.Popen(
|
||||
dispatch.argv,
|
||||
cwd=str(Path(__file__).resolve().parent.parent),
|
||||
env=worker_env,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=stderr_fd,
|
||||
start_new_session=True,
|
||||
creationflags=windows_hide_flags(),
|
||||
)
|
||||
finally:
|
||||
os.close(stderr_fd)
|
||||
except BaseException:
|
||||
payload_path.unlink(missing_ok=True)
|
||||
stderr_path.unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
with _running_lock:
|
||||
@@ -3265,7 +3272,7 @@ def _launch_external_cron_worker(job: dict) -> bool:
|
||||
process,
|
||||
execution_id=execution_id,
|
||||
job_id=job_id,
|
||||
handoff_files=(payload_path,),
|
||||
handoff_files=(payload_path, stderr_path),
|
||||
)
|
||||
finally:
|
||||
ack_path.unlink(missing_ok=True)
|
||||
@@ -3282,7 +3289,7 @@ def _launch_external_cron_worker(job: dict) -> bool:
|
||||
process,
|
||||
execution_id=execution_id,
|
||||
job_id=job_id,
|
||||
handoff_files=(payload_path,),
|
||||
handoff_files=(payload_path, stderr_path),
|
||||
)
|
||||
logger.info(
|
||||
"Cron job '%s' handed to restart-safe worker pid=%s execution=%s",
|
||||
@@ -3296,13 +3303,16 @@ def _launch_external_cron_worker(job: dict) -> bool:
|
||||
process,
|
||||
execution_id=execution_id,
|
||||
job_id=job_id,
|
||||
handoff_files=(payload_path,),
|
||||
handoff_files=(payload_path, stderr_path),
|
||||
)
|
||||
returncode = process.poll()
|
||||
if returncode is not None:
|
||||
with _running_lock:
|
||||
_restart_safe_waiter_job_ids.discard(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)
|
||||
stderr_path.unlink(missing_ok=True)
|
||||
if dispatch.mode == "scoped" and scoped_spawn_lost_user_bus(worker_env):
|
||||
# systemd-run itself failed (stderr is DEVNULL): name the cause, not the exit code.
|
||||
raise RuntimeError(
|
||||
@@ -3313,7 +3323,7 @@ def _launch_external_cron_worker(job: dict) -> bool:
|
||||
)
|
||||
raise RuntimeError(
|
||||
f"cron external worker exited before ownership acknowledgement "
|
||||
f"(exit {returncode})"
|
||||
f"(exit {returncode}){stderr_tail}"
|
||||
)
|
||||
time.sleep(0.05)
|
||||
|
||||
@@ -3331,7 +3341,7 @@ def _launch_external_cron_worker(job: dict) -> bool:
|
||||
process,
|
||||
execution_id=execution_id,
|
||||
job_id=job_id,
|
||||
handoff_files=(payload_path, ack_path),
|
||||
handoff_files=(payload_path, ack_path, stderr_path),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
"""Private run-document diagnostics, kept separate from delivery summaries."""
|
||||
|
||||
from pathlib import Path
|
||||
from traceback import format_exception
|
||||
|
||||
from agent.redact import redact_sensitive_text
|
||||
|
||||
# Enough for a Python traceback's last frames plus the exception line.
|
||||
_WORKER_STDERR_TAIL_CHARS = 1500
|
||||
|
||||
|
||||
def format_run_error(exc: BaseException) -> str:
|
||||
"""Retain chained causes without capturing locals or exposing URL credentials."""
|
||||
@@ -11,3 +15,24 @@ def format_run_error(exc: BaseException) -> str:
|
||||
"".join(format_exception(exc)), force=True, redact_url_credentials=True,
|
||||
)
|
||||
return f"## Error\n\n```\n{traceback_text}\n```\n"
|
||||
|
||||
|
||||
def external_worker_stderr_tail(path: Path) -> str:
|
||||
"""Redacted tail of a restart-safe cron worker's captured stderr, as a message suffix.
|
||||
|
||||
The gateway used to spawn the worker with ``stderr=DEVNULL``, so a worker that died before
|
||||
publishing its acknowledgement (an import error, a missing module in the interpreter it was
|
||||
handed) only ever reported ``exit 1`` and the reporter had to guess the cause (#112729).
|
||||
Returns an empty string when nothing was captured.
|
||||
"""
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8", errors="replace").strip()
|
||||
except OSError:
|
||||
return ""
|
||||
if not text:
|
||||
return ""
|
||||
tail = text[-_WORKER_STDERR_TAIL_CHARS:]
|
||||
if len(text) > _WORKER_STDERR_TAIL_CHARS:
|
||||
tail = "…" + tail
|
||||
tail = redact_sensitive_text(tail, force=True, redact_url_credentials=True)
|
||||
return f"; worker stderr: {tail}"
|
||||
@@ -407,6 +407,28 @@ def test_launch_external_worker_honors_ack_within_adoption_grace(
|
||||
assert scheduler._running_worker_pids == {"job-cold": 4321}
|
||||
|
||||
|
||||
def test_worker_dying_before_ack_names_its_stderr_cause(tmp_path, monkeypatch):
|
||||
"""A worker that exits before acknowledging used to report only ``exit 1`` because its stderr
|
||||
went to DEVNULL (#112729); the dispatch error must carry the worker's own traceback and the
|
||||
capture file must not outlive the attempt."""
|
||||
import cron.scheduler as scheduler
|
||||
from tools.process_registry import GatewayChildDispatch
|
||||
|
||||
monkeypatch.setattr(scheduler, "_get_hermes_home", lambda: tmp_path)
|
||||
monkeypatch.setattr(scheduler, "mark_execution_handoff_pending", lambda execution_id: {"id": execution_id})
|
||||
monkeypatch.setattr(
|
||||
"tools.process_registry.restart_safe_gateway_child_argv",
|
||||
lambda command, *, unit_suffix, require_restart_safe_scope=False: GatewayChildDispatch(
|
||||
"direct", [sys.executable, "-c", "import cron_module_that_does_not_exist"]),
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError) as excinfo:
|
||||
scheduler._launch_external_cron_worker({"id": "job-1", "execution_id": "exec-1", "prompt": "work"})
|
||||
assert "exit 1" in str(excinfo.value)
|
||||
assert "No module named 'cron_module_that_does_not_exist'" in str(excinfo.value)
|
||||
assert not list((tmp_path / "cron" / "external-workers").glob("exec-1.*"))
|
||||
|
||||
|
||||
def test_external_worker_exit_rechecks_exact_execution_before_failure(monkeypatch):
|
||||
import cron.scheduler as scheduler
|
||||
|
||||
|
||||
Reference in new issue
Block a user