diff --git a/docs/plans/issue140_execution_failure_receipt_20260929.md b/docs/plans/issue140_execution_failure_receipt_20260929.md new file mode 100644 index 0000000000..ec762cd759 --- /dev/null +++ b/docs/plans/issue140_execution_failure_receipt_20260929.md @@ -0,0 +1,65 @@ +# #140: Execution failure visibility to ZMQ waiters + +**Status:** concrete inherited-signal repair qualified by real cancellation and a healthy new job on the same original server; historical investigation and exact limitations follow. **Historical pinned heads:** OpenHCS `main` `0c7b898f852a8bedc0e1bc38b93f36088d301808`, ZMQRuntime gitlink `1d3b32f4fcead23d5d2079c975eb2ae7646a1478`; issue observation at OpenHCS `fc1f946329cc74ffcd1b6a73d39591c259dea030` (same ZMQRuntime gitlink). Source was read at the pinned dependency SHA via GitHub; the isolated worktree's submodule content was not used or modified. + +## Actual evidence and counterevidence + +- #140 reports that a fork worker lane exception appears in the server log but `benchmark/openhcs_measured_run.py` stays in `client.wait_for_completion(execution_id)` for more than three minutes. This is a reported observation, not a clean reproduction at the current head. +- OpenHCS `openhcs/core/orchestrator/worker_execution.py:503–538` raises for a failed fork worker. `openhcs/runtime/zmq_execution_server.py:383–391,433–477` routes this request through the inherited server execution lifecycle. `benchmark/openhcs_measured_run.py:316–361` waits for the matching compile and execution IDs and requires a complete result. +- In the pinned ZMQRuntime, `src/zmqruntime/execution/server.py:276–313` catches exceptions from `execute_task` and calls `mark_failed(execution_id, str(e))`; `lifecycle.py:250–272` transitions nonterminal records under a lock; `wait_policy.py:53–98` returns an explicit FAILED result for a polled failed record. Thus **the observed hang is not explained by a simply missing FAILED branch**. It may involve a pre-terminal stall, control socket starvation, a different execution ID/process, failure outside the guarded region, or an unrelated poll behavior. None is proven. +- Pinned `wait_policy.py:100–133` retries poll errors indefinitely when a *known server process remains alive*; that is a plausible failure path to investigate, not proof it occurred. #157 presently changes `openhcs/runtime/zmq_execution_server.py` and needs crossing review. + +## Required answers / provisional ownership + +For one accepted execution ID, is the server record terminal, and can the client observe it within a bounded interval after a worker-side terminal exception? The execution lifecycle record in ZMQRuntime is the candidate determining owner of terminal status; the client waiter is a separate consumer and the benchmark converts an observed failure to a durable failed row. Do not make a benchmark-only timeout masquerade as server failure propagation. The remote server protocol and execution IDs are separate identities from a local process PID. `R*` is provisional: server-failure → matching record FAILED → waiter reports that same failure → benchmark row records its message; cancellation, delayed healthy work, and transient network loss require distinct answers. No class-family or behavioral-equivalence claim is admitted from this issue report alone. + +## Investigation and acceptance gates + +1. In an isolated pinned worktree with recorded dependency SHAs, inject a deterministic fork-worker exception through ordinary ZMQ submission. Capture execution ID, server lifecycle record transitions, status responses, progress sequence, server liveness and waiter outcome under one bounded external deadline; preserve logs. Reproduce the specific #140 hang or identify why current source behaves correctly before writing a fix. +2. If record stays RUNNING, locate the worker→server completion owner and fix its terminal transition. If record is FAILED but client cannot see it, locate the control/status transport owner. If polling throws while an alive server is stuck, determine a bounded retry/liveness policy without declaring long legitimate executions failed. Cross-check pinned ZMQRuntime source and tests before any dependency PR; no duplicate status cache in OpenHCS. +3. Test a worker failure, healthy long execution, explicit cancellation, transient status error, and server-process loss. Assert matching IDs, actionable error text, bounded waiter termination after actual terminal failure, and a durable failed benchmark row. Do not weaken genuine long-running support to pass a timeout test. +4. Reinspect PR #157's head for collisions. A full context NRA scan with `scan_status`, class-first syntax rows and raw record evidence is required before *prescribing a structural refactor*; no such scan was completed for this plan. A focused root `openhcs/runtime` census/overlay at this head has 18,078 code lines and heuristic findings, none of which proves this failure path. + +**Decision point:** if the injected failure already terminates correctly at the pinned head, document closure evidence instead of adding a redundant fix. If not, name the exact owner and open a separate implementation PR. This draft plan does not close #140. + +## Actual fork acceptance on 2026-10-06 + +The original fork-failure boundary now has a real ordinary-ZMQ witness on clean OpenHCS `56c3da776ccc12688b4566f7b0c0ef728e6bc7c6` with installed ZMQRuntime 0.4.1. A private importable, memory-declared pass-through callable ran in two genuine fork children and armed an exception after their ordinary `_release_runtime_resources` cleanup. No server status, waiter outcome, or benchmark row was manufactured. + +- Failure packet: `20261006/issue140-fork-acceptance-preparation-v1/actual-failure-v3`. Compile ID `101ff205-1167-4ba8-8d80-045bbb53d157`; execution ID `3ebcaee5-b209-4c7d-b636-d887febedad3`. Server PID 835048; fork children 835540 and 835542. The original waiter, queried lifecycle, and terminal progress snapshot agree on that execution's FAILED status. The original well-throughput CSV contains the actionable outer-cleanup traceback; all owned process incarnations were gone after disconnect. The external 240-second diagnostic deadline was not reached. +- Healthy control: `actual-healthy-v1` passed with the same public route, two fork children, finite ten-second work, COMPLETE status, and two successful wells. +- Cancellation control: `actual-cancel-v1` obtained the real public response `Cancelled - killed 2 workers`, but the diagnostic then failed with `Server was not writable for status request within 5000ms`; it retained only the compilation observation. No cancellation acceptance is claimed. All owned processes exited. The next investigation must separate the actual waiter outcome from the additional observation/status probe. +- Process-loss control has not run. Transient status-error acceptance also remains unproved. + +The first two private fixture attempts were rejected at compilation (a nonexistent catalog ID, then a missing memory declaration); neither reached fork execution. The accepted fixture uses the existing `ImportableFunctionReference` authority with its actual decorated callable metadata. Those preparation mistakes are not production failure evidence. + +**Current decision:** the original fork exception propagates correctly through the merged lifecycle owners, so no duplicate failure path is justified. Keep #140 open until the cancellation, transient status-error and process-loss controls are resolved; this evidence does not establish those separate behaviours. These diagnostics are not pipeline performance measurements. + +## Confirmed inherited-signal defect and candidate repair + +The follow-up controls preserve the original public waiter result before any independent status observation. Cancellation returns a matching CANCELLED record and terminal progress; the status failure is a separate endpoint loss, not a missing terminal waiter branch. + +The decisive `actual-cancel-ipc-witness-v4` packet records original server incarnation PID 947595, creation time 1791294744.97. Both genuine fork children, 948131 and 948133, inherit SIGTERM and SIGINT handler `zmqruntime.runner.serve_forever.._signal_handler`, whose closure captures `server`. Before public cancellation, IPC paths `openhcs-zmq-7777.sock` and `openhcs-zmq-8777.sock` exist with inodes 6056761 and 6056762. After the public response confirms two workers killed, both paths are absent while the same parent server remains alive. A fresh attach-only client cannot reach its endpoint. Installed ZMQRuntime's inherited handler calls `server.stop()`, which closes transport and removes those addresses; child termination therefore runs copied parent cleanup. + +Two remaining controls pass on unchanged `56c3da776` and installed ZMQRuntime 0.4.1: + +- `actual-server-loss-v1`: actual server SIGKILL after both fork workers enter. The original waiter returns CANCELLED without manufacturing a dead-server lifecycle record; its exact owned process-exit observation, original failed CSV and process cleanup are retained. +- `actual-transient-status-healthy-v2`: one private injected status transport TimeoutError and one malformed missing-execution-ID reply, each following a retained actual server poll. The original waiter continues and agrees with terminal progress and fresh status on COMPLETE, with two successful wells. The earlier protocol-ERROR injection remains a negative control: that declared error is intentionally definitive under the existing waiter policy and is not a transient polling exception. + +The candidate repair belongs to existing `WorkerExecutorResources.initialize_process_signals`: initialize child SIGTERM and SIGINT to SIG_DFL at the existing fork entry and pooled-process initializer. Parent, inline and threaded execution do not call it. The fork path keeps its inherited catalog, kernels, logging, environment, progress and resource state; it does not run spawn preparation. There is no cancellation-specific branch, timeout change, ignored termination, second status authority or new wrapper family. + +The existing lane/resource control module passes 38 controls. Its new real fork/SIGTERM control checks child defaults and actual signal exit, leaves a parent cleanup sentinel untouched, and verifies the parent's handlers remain installed. Production cancellation and same-server recovery are qualified below. No performance improvement is claimed. + +Local evidence root: `/home/ts/.local/state/openhcs-maintenance/20261006/issue140-fork-acceptance-preparation-v1`, including `independent-controls-and-cancellation-root-cause.json` and the original negative packets. + +## Candidate cancellation and same-server recovery qualification + +Normal `setup.py build_ext --inplace` built all declared native modules in this worktree; no extensions were copied or symlinked, and the installed environment was unchanged. The actual candidate control used clean source `b0cf6e9cbe18bf25715e9e1a625d4ec5fdd76ecf`, installed ZMQRuntime 0.4.1, ordinary READY → compile → execute, two genuine fork workers, and the unchanged public waiter/lifecycle/CSV owners. + +Packet `candidate-cancel-recovery-v3` retains original server incarnation PID 1020759, creation time 1791296323.81. Public cancellation killed workers 1021298 and 1021300. The original waiter, terminal progress and a fresh attach-only status client agree on CANCELLED execution `2170d903-6830-44fc-946e-0e9c29f82d2a`; the original well-throughput CSV retains the actionable cancellation error. Both IPC paths survive cancellation with exactly their previous inodes, 6056761 and 6056762. + +On that same original server, the captured original compile request is submitted again normally: new compile ID `9f651be0-f44d-4f99-a632-f7edfd8facbf` completes. The existing execution request owner then receives that actual returned artifact ID. New execution `e21455da-0188-44c5-92a5-06e7d679991f` completes after finite ten-second work in new fork children 1021348 and 1021367, with two successful wells. Original waiter, independently attached status and terminal progress agree on the new COMPLETE ID. All four actual children have SIGTERM and SIGINT set to SIG_DFL. The original server incarnation remains alive throughout both jobs, and all five owned process incarnations are gone after normal disconnect. Both runtime leases are subsequently acquired and released successfully. + +The private helper's original terminal code remains 1: after saving the actual COMPLETE responses it mistakenly passed the frozen nested `terminal_snapshot` mapping to a parser that expects a wire dictionary. A separate offline verification uses the existing `ExecutionProgressObservation.from_wire(...).terminal_status_response()` owner and checks every cancellation/recovery ID, status, PID, IPC inode, child signal, duration, CSV and cleanup guard against the saved actual outcomes. It passes with exit code 0; every original packet file remains byte-identical. No new execution or terminal status was manufactured. Evidence: `candidate-cancel-recovery-v3-offline-acceptance.json`, its verifier and log, alongside the unchanged original packet. + +Earlier candidate v1 and v2 negative controls remain preserved: the first reused an intentionally consumed ordinary compile artifact; the second converted an execution request to compile-only while retaining its artifact ID. These were private fixture mistakes, not production defects. The final control resubmits the actual original compile request and uses the actual newly returned artifact ID. This qualification closes the cancellation/fresh-client/recovery gate without adding a duplicate failure path or claiming to reproduce the original reported hang's exact cause. All diagnostic clocks are excluded from pipeline performance evidence. diff --git a/openhcs/core/orchestrator/worker_execution.py b/openhcs/core/orchestrator/worker_execution.py index e077a1cc1a..63937ce8e8 100644 --- a/openhcs/core/orchestrator/worker_execution.py +++ b/openhcs/core/orchestrator/worker_execution.py @@ -6,6 +6,7 @@ import contextlib import logging import multiprocessing +import signal from abc import ABC, abstractmethod from dataclasses import dataclass, replace from typing import Any, Dict, Iterable, List, Mapping @@ -94,6 +95,13 @@ class WorkerExecutorResources(ABC): multiprocessing_context: Any use_multiprocessing: bool + @staticmethod + def initialize_process_signals() -> None: + """Give child termination its own process lifetime, not a parent's cleanup.""" + + signal.signal(signal.SIGTERM, signal.SIG_DFL) + signal.signal(signal.SIGINT, signal.SIG_DFL) + @property def executor(self) -> concurrent.futures.Executor | None: return None @@ -407,6 +415,8 @@ def _configure_worker_process( import logging import os + WorkerExecutorResources.initialize_process_signals() + worker_log_level_name = os.environ.get("OPENHCS_LOG_LEVEL", "INFO").upper() worker_log_levels = logging.getLevelNamesMapping() if worker_log_level_name not in worker_log_levels: @@ -442,6 +452,7 @@ def _execute_fork_inherited_worker_lane_process( ) -> None: """Process entrypoint for fork-inherited worker lane execution.""" + WorkerExecutorResources.initialize_process_signals() profiling_policy = CProfileWorkerProfilingPolicy.from_environment() try: with profiling_policy.profile( diff --git a/tests/unit/test_orchestrator_lane_planning.py b/tests/unit/test_orchestrator_lane_planning.py index e3108449b0..9170ceaccc 100644 --- a/tests/unit/test_orchestrator_lane_planning.py +++ b/tests/unit/test_orchestrator_lane_planning.py @@ -1,4 +1,6 @@ from contextlib import nullcontext +import multiprocessing +import signal from types import SimpleNamespace import pytest @@ -579,13 +581,70 @@ def test_worker_process_initializer_does_not_prepare_global_function_registry( lambda: initialized.append(True), ) - worker_execution_module._configure_worker_process( - None, - ) + parent_handlers = { + sig: signal.getsignal(sig) for sig in (signal.SIGTERM, signal.SIGINT) + } + try: + worker_execution_module._configure_worker_process(None) + finally: + for sig, handler in parent_handlers.items(): + signal.signal(sig, handler) assert initialized == [] +def test_fork_child_termination_cannot_run_inherited_parent_cleanup( + monkeypatch, tmp_path +) -> None: + cleanup = tmp_path / "parent-endpoint-cleanup" + + def parent_cleanup(_sig, _frame): + cleanup.write_text("parent cleanup invoked") + + parent_handlers = { + sig: signal.getsignal(sig) for sig in (signal.SIGTERM, signal.SIGINT) + } + fork = multiprocessing.get_context("fork") + reader, writer = fork.Pipe(duplex=False) + + def held_lane(_keys, _context, _mode): + writer.send(tuple(signal.getsignal(sig) for sig in parent_handlers)) + signal.pause() + + monkeypatch.setattr( + worker_execution_module, "_execute_fork_inherited_worker_lane_static", held_lane + ) + lane = WorkerLaneExecutionContext( + execution_id="signal-ownership", plate_id=str(tmp_path), + debug_execution_policy=NoOpDebugExecutionPolicy(), worker_slot="worker_0", + worker_assignments={"worker_0": ["A01"]}, + ) + process = fork.Process( + target=worker_execution_module._execute_fork_inherited_worker_lane_process, + args=(writer, [], lane, RuntimeObservationMode.OMIT), + ) + try: + for sig in parent_handlers: + signal.signal(sig, parent_cleanup) + process.start() + writer.close() + assert reader.poll(5), "Actual fork entry did not reach its worker lane" + assert reader.recv() == (signal.SIG_DFL, signal.SIG_DFL) + process.terminate() + process.join(timeout=5) + assert process.exitcode == -signal.SIGTERM + assert not cleanup.exists() + assert all(signal.getsignal(sig) is parent_cleanup for sig in parent_handlers) + finally: + if process.is_alive(): + process.kill() + process.join(timeout=5) + reader.close() + writer.close() + for sig, handler in parent_handlers.items(): + signal.signal(sig, handler) + + def test_pooled_worker_lane_runner_submits_and_collects_lane_results(monkeypatch): class FakeFuture: def __init__(self, result):