From fe52fce8317576ecb23f3c363662d2d8ce6091e4 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 30 Sep 2026 05:22:40 -0400 Subject: [PATCH 1/5] test: publish source-only ACK startup failure diagnostic for issue 10 --- ACK-ISSUE10-DRAFT-PR-BODY.md | 63 ++++++ ACK-ISSUE10-OWNERSHIP-RECEIPT.md | 211 ++++++++++++++++++ .../diagnostics/check_ack_startup_failure.py | 91 ++++++++ 3 files changed, 365 insertions(+) create mode 100644 ACK-ISSUE10-DRAFT-PR-BODY.md create mode 100644 ACK-ISSUE10-OWNERSHIP-RECEIPT.md create mode 100644 tests/diagnostics/check_ack_startup_failure.py diff --git a/ACK-ISSUE10-DRAFT-PR-BODY.md b/ACK-ISSUE10-DRAFT-PR-BODY.md new file mode 100644 index 0000000..3cc6a07 --- /dev/null +++ b/ACK-ISSUE10-DRAFT-PR-BODY.md @@ -0,0 +1,63 @@ +## Diagnostic checkpoint only; not merge-ready or the ACK fix + +Tracks #10. This draft makes the source reproducer and ownership receipt +visible while direct production-file agreements and the finite live slot are +pending. It does **not** fix or close #10. + +Changed files only: + +- `tests/diagnostics/check_ack_startup_failure.py` +- `ACK-ISSUE10-OWNERSHIP-RECEIPT.md` +- this draft body + +Production source, configuration, transport declarations, PolyStore, viewers, +installed packages and paired gitlinks are unchanged. Parent owns paired +gitlink integration. Lovelace retains bootstrap and the assigned native slot; +the existing OpenHCS159 owner retains viewer configuration/protocol/server work. + +## Executed evidence + +The existing OpenHCS interpreter runs three serial provider-free checks against +this worktree's real ACK start/loop with mocked Context and inline test Thread: + +- controlled socket/context cleanup passes; +- caller-visible bind failure fails (`ZMQError not raised`); +- truthful failed-listener state fails (`_running` remains true). + +The failing checks are retained without xfail or weaker assertions. The script +is an explicit diagnostic, not part of automatic pytest discovery. Its nonzero +exit demonstrates the current defect, not a completed fix. No real endpoint, +listener thread, native process, viewer or provider call is opened. + +The resource guard remains critical (swap 16.6 GiB). No native/heavy job ran; +the diagnostic is bounded by 10 seconds and numerical-library thread limits=1. + +## Shared-file agreement required before production edits + +Proposed ACK implementation owner: Dirac, with unpublished claims still to be +confirmed for `ack_listener.py`, `streaming/server.py`, `queue_tracker.py` and +focused ACK tests. + +- Lovelace / ZMQ9 retains `client.py`, `messages.py`, `transport_modes.py`, + `execution/server.py`. Any ACK declaration/transport extension must have one + agreed editor; no competing bootstrap will be implemented. +- `config.py` needs an explicit editor agreement if endpoint semantics change. +- OpenHCS159 retains its config/factory/streaming service, viewer protocol and + Fiji/Napari visualizers/servers. Any caller change needs that owner's agreement. +- PolyStore sender/batch-envelope changes also need a named single editor. +- ZMQ6 wait policy and ZMQ7 viewer state are outside this checkpoint. + +NRA/refactor-audit ownership decision: original endpoint/transport/message +declarations own semantics; consumers derive them. No copied defaults, +duplicate registry/decoder/launcher, arbitrary port assignment or compatibility +delivery path. Relevant reviewed patterns are recorded in the receipt. + +## Remaining acceptance + +After direct file agreements, implement truthful startup/liveness and correctly +owned ACK delivery, then run focused source tests. After an explicit resource +gate and slot release, verify concurrent controlled TCP and applicable IPC +streaming owners, each owner's ACK IDs/queue counts, bind failure visibility, +and stopping one owner while the other continues. Source diagnostics do not +establish installed or concurrent-native readiness. Frozen science, original +collision evidence and the user's preserved viewer remain untouched. diff --git a/ACK-ISSUE10-OWNERSHIP-RECEIPT.md b/ACK-ISSUE10-OWNERSHIP-RECEIPT.md new file mode 100644 index 0000000..4cd59a6 --- /dev/null +++ b/ACK-ISSUE10-OWNERSHIP-RECEIPT.md @@ -0,0 +1,211 @@ +# Issue 10: source investigation and ownership checkpoint + +Date: 2026-09-30. Independent task owner: Dirac. +Issue: https://github.com/OpenHCSDev/ZMQRuntime/issues/10 +Worktree: /home/ts/wt/zmqruntime-ack-delivery-owner-20260930 +Branch: fix/ack-delivery-owner-20260930 +Base: 0f9e840a9ed526f0a2b87a660393f5b7c34fc9eb (origin/main). + +## Safety and implementation status + +Source investigation and diagnostic checkpoint only. No production edits, +installed changes, package/environment changes, native/viewer/MCP startup, or +real endpoint bind. The H003 scientific freeze, inputs, report and original warning remain +untouched. The absence of a current 7555 listener is not collision resolution. +Lovelace retains the sole live acceptance slot. + +The resource guard returned exit 2 for historical swap usage (15.6 GiB). +Available RAM was 14.7 GiB; home disk headroom was 27.8 GiB. Follow-up vmstat +showed zero current swap-in/out and memory PSI averages were zero. Work was +limited to serial source reads and one short, thread-limited provider-free +diagnostic using the existing OpenHCS interpreter. No heavy suite or fleet ran. + +## Required guidance read + +Read the installed NRA and refactor-audit skills and the current archive at +/home/ts/code/projects/nominal-refactor-advisor/skills/refactor-audit.skill. +Relevant current chapters read fully: boundaries, identity, membership, +implementation and over-time, plus the surface-receipt instructions. +This is a source-backed diagnostic checkpoint, not an NRA proof or full scan. +The guidance requires ACK identity/routing and lifecycle facts to remain with +their original typed owners, rather than a second registry, decoder or launcher. + +## Verified source trace + +1. PolyStore's StreamingBackend._register_with_queue_tracker starts + GlobalAckListener at transport_config.shared_ack_port, then registers each + image ID in its process-local GlobalQueueTrackerRegistry. Its save_batch + invokes this before sending the batch over REQ/REP. +2. ZMQConfig owns shared_ack_port=7555. GlobalAckListener is a Python singleton, + not a cross-process owner. Its start marks _running=True before its listener + thread binds. Already-running calls do not verify requested endpoint identity. +3. The listener logs fatal bind failures and closes its socket/context but does + not clear _running or propagate the startup failure to the caller. +4. StreamingVisualizerServer creates a PUSH socket connected to its config's + shared ACK endpoint. send_ack emits the original ImageAck declaration: + image_id, viewer_port, viewer_type, status, timestamp and error. No producer + incarnation/return-route identity appears in that declaration. +5. The default listener callback routes by viewer port into the local registry. + QueueTracker.mark_processed deliberately counts an unregistered image + retroactively, with a source comment attributing this to worker-local + registries. Missing trackers instead update ViewerStateManager directly. + Thus blindly rejecting unknown images or choosing an arbitrary new port would + alter intended cross-worker progress semantics; neither is an established fix. + +The collision mechanism and ownership risk are source-backed. Actual ACK +misdelivery or starvation in the frozen science run has NOT been demonstrated. +The per-batch REQ/REP transfer receipt is distinct from asynchronous per-image +PUSH/PULL progress ACKs; success of one does not establish health of the other. + +## Provider-free reproducer (observed) + +Executed against this worktree's ack_listener.py with the existing interpreter, +PYTHONDONTWRITEBYTECODE=1 and thread limits=1. unittest.mock replaced zmq.Context +with a controlled context/socket and threading.Thread with an inline test +thread. ControlledSocket.bind raises ZMQError(EADDRINUSE). The real listener +start and loop were called, then start was called again. + +Observed JSON: + +```json +{ + "real_endpoints_opened": 0, + "start_returned": null, + "fatal_bind_attempts": ["tcp://*:7555"], + "thread_completed": true, + "running_after_fatal_bind": true, + "socket_closed": true, + "context_terminated": true, + "second_start_ignored": true +} +``` + +This establishes false readiness/stuck startup in source only. It does not +substitute for concurrent native or installed streaming evidence. + +## Shared-file coordination blocker + +PR9 is OPEN, head 28d9ed6a0121ebb524ae37fd97de5355308bda7f, +feat/exclusive-endpoint-bootstrap-20260930. It owns client.py, +execution/server.py, messages.py and transport_modes.py, related startup/close +tests, and its validation docs. PR7's published scope is viewer_state.py and +test_viewer_state.py. Unpublished claims still require direct confirmation. + +Requested peer: Lovelace 01a0ee61-a6b6-7b81-af1f-154b3cddbbca. +No agent-session messaging tool is exposed here. The installed agent-comms CLI +resolves the owner-installed active route, but this ID is not a registered +thread, and the bounded owner metadata lookup found no Lovelace or Dirac route. +No guessed-root write, identity impersonation, foreign-tree edit, or agent-reply +polling was performed. Need Lovelace's registered comms name/root or a direct +ownership response delivered into this session. + +Proposed scope to negotiate, NOT a finalized claim: ack_listener.py, +streaming/server.py, queue_tracker.py, their focused tests; declaration changes +in messages.py/config.py/transport_modes.py and PolyStore's streaming sender and +typed batch-envelope owner only if the traced delivery fix requires them. +Lovelace owns bootstrap; no competing bootstrap implementation will be made. + +## Exact acceptance remaining + +### Updated crossings and guidance confirmation + +Rechecked published heads after the owner's latest scope clarification: +OpenHCS256 is 5ca21c798642e820f224eebf294fc54e0dc3f965; +ZMQRuntime9 remains 28d9ed6a0121ebb524ae37fd97de5355308bda7f. +OpenHCS159 is d45ebbb61da0463885e81e654a5c8ab895f41398. +The actual listener path is src/zmqruntime/ack_listener.py, not +src/zmqruntime/streaming/ack_listener.py. + +| File/surface | Proposed single editor; current claim boundary | +| --- | --- | +| ACK listener, streaming/server.py, queue_tracker.py and focused ACK tests | Dirac, subject to Lovelace's unpublished-claim confirmation; not yet an agreed exclusive file claim | +| ZMQ config.py | No final editor agreed; endpoint semantics remain on ZMQConfig, not a new ACK config | +| ZMQ client.py, messages.py, transport_modes.py, execution/server.py | Lovelace/ZMQ9; request declaration/transport extensions from this owner rather than editing concurrently | +| ZMQ execution/wait_policy.py | Existing ZMQ6 owner; outside ACK edits | +| ZMQ viewer_state.py | Existing ZMQ7 owner; outside ACK edits | +| OpenHCS core/config.py, core/streaming_config_factory.py, core/viewer_streaming_service.py, runtime/viewer_protocol.py, runtime/fiji_stream_visualizer.py, runtime/fiji_viewer_server.py, runtime/napari_stream_visualizer.py, runtime/napari_viewer_server.py | Existing OpenHCS159 owner; identity/direct agreement not established here | +| PolyStore streaming sender and typed batch envelope | No final editor agreed; cannot silently change caller-owned delivery semantics | +| Paired dependency gitlink integration | Parent, explicitly assigned | +| Issue257 acceptance/versioned fixture | Parent only; no production runtime change inferred | + +Separate archive-refactor agent identity: not known. Do not infer an agent +identity from the shared GitHub account or claim a peer agreement that has not +occurred. A fresh bounded owner-metadata lookup again found neither the supplied +Lovelace ID nor Lovelace/Dirac aliases in the selected installed comms route. +No comms message was sent merely to relay the parent's instruction. + +The NRA skill, installed refactor-audit skill, current repo archive SKILL.md, +catalog README and complete identity, membership, implementation, boundaries +and over-time chapters were reread for this checkpoint. Relevant reviewed +patterns/guards: + +- IDEN-6: inspect whether viewer-port routing answers the actual producer/ACK + ownership question across processes. The existing worker retrofit behavior is + part of the required relation, not permission to discard unknown IDs. +- IMPL-13: extend the existing transport/lifecycle ownership mechanism rather + than build a second, weaker launcher or endpoint-cleanup authority. +- BOUND-1/BOUND-2: decode at the ACK/batch boundary using the original typed + declaration; downstream consumers do not invent another shape/decoder. +- MEMB-5: derive wire projections from the original declaration rather than + maintain a second handwritten schema or registry. +- TIME-7: consumers derive default endpoint semantics from their owner; real + explicit user overrides remain overrides, not copied fallback defaults. +- TIME-1/TIME-9: any replacement delivery mechanism cuts over in lockstep and + removes the replaced path, without a legacy route or compatibility adapter. + +These are source-backed ownership risks and implementation guards, not a claim +that every pattern has been independently measured as an existing violation. +No new census, NRA scan or native proof is claimed at this checkpoint. + +Ownership decision: original ZMQConfig/TransportDeclaration and ImageAck/batch +declarations own endpoint, transport and ACK semantics. Producers and viewers +consume/derive those declarations. No duplicate config, registry, arbitrary +port assignment or bootstrap implementation. Direct agreement remains required +before any shared source edit. Parent's projection fixture/provenance checks +are outside this ACK implementation and will not be weakened here. + +### Visible provider-free checkpoint + +The owner requested a visible draft PR after OpenHCS275 merged (reported +cd047c4, script/test/RST only). The new independent file is +tests/diagnostics/check_ack_startup_failure.py. It changes neither a shared +production file nor the original native/viewer owners' tests. The diagnostic +exercises the worktree's actual listener start/loop with a controlled failing +socket and inline test thread. It has no xfails, suppression of failed +assertions, real socket binds or real listener threads. It is not automatically +pytest-discovered: it is an explicitly failing acceptance witness, not a claim +of a merge-ready fix. + +Resource guard immediately before this checkpoint still returned exit 2, +level=critical, swap=16.6 GiB, available RAM=18.5 GiB, home free=25.9 GiB. +No heavy job ran. Existing Python, thread limits=1, timeout=10 seconds: + +```sh +timeout 10s env OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 \ + PYTHONDONTWRITEBYTECODE=1 \ + /home/ts/code/projects/openhcs/.venv/bin/python \ + tests/diagnostics/check_ack_startup_failure.py +``` + +Three checks execute: the controlled socket/context cleanup check passes; +truthful startup failure propagation and failed-listener running-state checks +fail on the unmodified production baseline. A nonzero exit is the retained +defect evidence, not a timeout or a passing readiness claim. This checkpoint +does not resolve delivery ownership or issue 10 and must not close the issue. + +After claims are reconciled: implement truthful bind readiness/failure and +correctly owned ACK delivery using existing typed declaration/transport owners; +delete the replaced delivery mechanism, without compatibility routing/defaults. +Add focused provider-free tests for failed bind, truthful healthy/dead state, +endpoint mismatch, correct ACK routing/queue counts, duplicates and cleanup. +Publish the coherent implementation promptly as a draft PR linked to issue 10. + +Only after parent assigns the finite live slot: run two owned controlled +application/native streaming owners concurrently through the existing entrypoint +on TCP, then applicable IPC. Observe bind outcomes, each owner's own image IDs, +ACK receipts and queue progression; show no ACK stealing/misrouting or dead +listener reported healthy. Stop one owner and prove the other continues ACK +delivery; verify teardown releases only owned endpoints/resources. Include +controlled occupied-endpoint startup failure and truthful surfaced failure. +No foreign 7555 listener intervention, science rerun, timeout inflation or +installation mutation is authorized by this checkpoint. diff --git a/tests/diagnostics/check_ack_startup_failure.py b/tests/diagnostics/check_ack_startup_failure.py new file mode 100644 index 0000000..6c55f12 --- /dev/null +++ b/tests/diagnostics/check_ack_startup_failure.py @@ -0,0 +1,91 @@ +"""Provider-free issue 10 readiness diagnostic; exits nonzero until fixed. + +Run with the existing interpreter. This is deliberately not pytest-discovered: +it is a visible failing acceptance witness, not an xfail or a passing fix claim. +The real ACK startup/loop runs against a controlled failing socket and inline +test thread. No real endpoint, listener thread, native process or viewer opens. +""" + +from __future__ import annotations + +import errno +import sys +import unittest +from contextlib import ExitStack +from pathlib import Path +from unittest.mock import Mock, patch + + +SOURCE_ROOT = Path(__file__).resolve().parents[2] / "src" +sys.path.insert(0, str(SOURCE_ROOT)) + +from zmqruntime import ack_listener +from zmqruntime.config import TransportMode, ZMQConfig + + +if not Path(ack_listener.__file__).resolve().is_relative_to(SOURCE_ROOT): + raise RuntimeError("Diagnostic must exercise this worktree's ACK listener") + + +class AckStartupFailureDiagnostic(unittest.TestCase): + def setUp(self) -> None: + stack = ExitStack() + self.addCleanup(stack.close) + stack.enter_context(patch.object(ack_listener.GlobalAckListener, "_instance", None)) + stack.enter_context(patch.object(ack_listener, "logger", Mock())) + self.socket = Mock() + self.socket.bind.side_effect = ack_listener.zmq.ZMQError(errno.EADDRINUSE) + self.context = Mock() + self.context.socket.return_value = self.socket + self.context_factory = stack.enter_context( + patch.object(ack_listener.zmq, "Context", return_value=self.context) + ) + self.thread_factory = stack.enter_context( + patch.object(ack_listener.threading, "Thread", side_effect=self._inline_thread) + ) + self.listener = ack_listener.GlobalAckListener() + self.config = ZMQConfig() + + def _inline_thread(self, *, target, **options): + thread = Mock() + thread.start.side_effect = target + return thread + + def _start(self) -> None: + self.listener.start( + self.config.shared_ack_port, + transport_mode=TransportMode.TCP, + config=self.config, + ) + + def tearDown(self) -> None: + self.listener.stop() + + def test_failed_bind_is_reported_to_start_caller(self) -> None: + with self.assertRaises(ack_listener.zmq.ZMQError): + self._start() + + def test_failed_listener_does_not_claim_running(self) -> None: + try: + self._start() + except ack_listener.zmq.ZMQError: + pass + self.assertFalse(self.listener._running) + + def test_controlled_reproducer_releases_its_socket_and_context(self) -> None: + try: + self._start() + except ack_listener.zmq.ZMQError: + pass + self.context_factory.assert_called_once_with() + self.context.socket.assert_called_once_with(ack_listener.zmq.PULL) + self.thread_factory.assert_called_once() + self.socket.bind.assert_called_once_with( + f"tcp://*:{self.config.shared_ack_port}" + ) + self.socket.close.assert_called_once_with() + self.context.term.assert_called_once_with() + + +if __name__ == "__main__": + unittest.main(verbosity=2) From 4a7864bc0fca766dce86ae9990fcd065e5d80a85 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 30 Sep 2026 05:25:11 -0400 Subject: [PATCH 2/5] docs: record ACK draft publication and exact owner crossing requests --- ACK-ISSUE10-DRAFT-PR-BODY.md | 6 ++++++ ACK-ISSUE10-OWNERSHIP-RECEIPT.md | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/ACK-ISSUE10-DRAFT-PR-BODY.md b/ACK-ISSUE10-DRAFT-PR-BODY.md index 3cc6a07..a0ca0aa 100644 --- a/ACK-ISSUE10-DRAFT-PR-BODY.md +++ b/ACK-ISSUE10-DRAFT-PR-BODY.md @@ -52,6 +52,12 @@ declarations own semantics; consumers derive them. No copied defaults, duplicate registry/decoder/launcher, arbitrary port assignment or compatibility delivery path. Relevant reviewed patterns are recorded in the receipt. +Exact ownership requests posted to the existing owner PRs: +[Lovelace/native PR9](https://github.com/OpenHCSDev/ZMQRuntime/pull/9#issuecomment-5908226428), +[viewer PR159](https://github.com/OpenHCSDev/openhcs/pull/159#issuecomment-5908226994). +Posting is verified; owner receipt/agreement is not yet verified. Production +files remain untouched pending explicit single-editor agreement. + ## Remaining acceptance After direct file agreements, implement truthful startup/liveness and correctly diff --git a/ACK-ISSUE10-OWNERSHIP-RECEIPT.md b/ACK-ISSUE10-OWNERSHIP-RECEIPT.md index 4cd59a6..81fbe2e 100644 --- a/ACK-ISSUE10-OWNERSHIP-RECEIPT.md +++ b/ACK-ISSUE10-OWNERSHIP-RECEIPT.md @@ -193,6 +193,25 @@ fail on the unmodified production baseline. A nonzero exit is the retained defect evidence, not a timeout or a passing readiness claim. This checkpoint does not resolve delivery ownership or issue 10 and must not close the issue. +Published draft: https://github.com/OpenHCSDev/ZMQRuntime/pull/11. +Initial diagnostic commit: fe52fce8317576ecb23f3c363662d2d8ce6091e4. +Publication verified OPEN and isDraft=true, with only the diagnostic and two +receipt/body documents. The final diagnostic run executed three checks in +0.013 seconds; one passed and two failed, exit 1. Git diff --check passed. + +Substantive single-editor requests were posted directly on the existing owner +PRs, not through a guessed agent-comms identity: + +- Lovelace/native bootstrap: https://github.com/OpenHCSDev/ZMQRuntime/pull/9#issuecomment-5908226428 +- Current viewer owner: https://github.com/OpenHCSDev/openhcs/pull/159#issuecomment-5908226994 + +The requests identify exact retained/proposed file claims, ask about unpublished +overlap, and propose requesting shared declaration/caller extensions from the +existing editor. Posting is confirmed; receipt by an agent and owner agreement +are NOT confirmed. No reply polling or production/shared-file edit occurred. +The installed stack, frozen scientific artifacts, and the user viewer at 5690 +remain untouched. Parent retains paired gitlink integration. + After claims are reconciled: implement truthful bind readiness/failure and correctly owned ACK delivery using existing typed declaration/transport owners; delete the replaced delivery mechanism, without compatibility routing/defaults. From 859070c7b8b12460b01140ff040399ce38b90cd5 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 30 Sep 2026 06:21:52 -0400 Subject: [PATCH 3/5] fix: make ACK startup and liveness truthful with worker-owned cleanup --- ACK-ISSUE10-DRAFT-PR-BODY.md | 140 ++++---- ACK-ISSUE10-OWNERSHIP-RECEIPT.md | 72 ++++ src/zmqruntime/ack_listener.py | 244 ++++++++++--- .../diagnostics/check_ack_startup_failure.py | 20 +- tests/test_ack_listener.py | 331 ++++++++++++++++++ 5 files changed, 672 insertions(+), 135 deletions(-) create mode 100644 tests/test_ack_listener.py diff --git a/ACK-ISSUE10-DRAFT-PR-BODY.md b/ACK-ISSUE10-DRAFT-PR-BODY.md index a0ca0aa..c33ac8d 100644 --- a/ACK-ISSUE10-DRAFT-PR-BODY.md +++ b/ACK-ISSUE10-DRAFT-PR-BODY.md @@ -1,69 +1,75 @@ -## Diagnostic checkpoint only; not merge-ready or the ACK fix - -Tracks #10. This draft makes the source reproducer and ownership receipt -visible while direct production-file agreements and the finite live slot are -pending. It does **not** fix or close #10. - -Changed files only: - -- `tests/diagnostics/check_ack_startup_failure.py` -- `ACK-ISSUE10-OWNERSHIP-RECEIPT.md` -- this draft body - -Production source, configuration, transport declarations, PolyStore, viewers, -installed packages and paired gitlinks are unchanged. Parent owns paired -gitlink integration. Lovelace retains bootstrap and the assigned native slot; -the existing OpenHCS159 owner retains viewer configuration/protocol/server work. - -## Executed evidence - -The existing OpenHCS interpreter runs three serial provider-free checks against -this worktree's real ACK start/loop with mocked Context and inline test Thread: - -- controlled socket/context cleanup passes; -- caller-visible bind failure fails (`ZMQError not raised`); -- truthful failed-listener state fails (`_running` remains true). - -The failing checks are retained without xfail or weaker assertions. The script -is an explicit diagnostic, not part of automatic pytest discovery. Its nonzero -exit demonstrates the current defect, not a completed fix. No real endpoint, -listener thread, native process, viewer or provider call is opened. - -The resource guard remains critical (swap 16.6 GiB). No native/heavy job ran; -the diagnostic is bounded by 10 seconds and numerical-library thread limits=1. - -## Shared-file agreement required before production edits - -Proposed ACK implementation owner: Dirac, with unpublished claims still to be -confirmed for `ack_listener.py`, `streaming/server.py`, `queue_tracker.py` and -focused ACK tests. - -- Lovelace / ZMQ9 retains `client.py`, `messages.py`, `transport_modes.py`, - `execution/server.py`. Any ACK declaration/transport extension must have one - agreed editor; no competing bootstrap will be implemented. -- `config.py` needs an explicit editor agreement if endpoint semantics change. -- OpenHCS159 retains its config/factory/streaming service, viewer protocol and - Fiji/Napari visualizers/servers. Any caller change needs that owner's agreement. -- PolyStore sender/batch-envelope changes also need a named single editor. -- ZMQ6 wait policy and ZMQ7 viewer state are outside this checkpoint. - -NRA/refactor-audit ownership decision: original endpoint/transport/message -declarations own semantics; consumers derive them. No copied defaults, -duplicate registry/decoder/launcher, arbitrary port assignment or compatibility -delivery path. Relevant reviewed patterns are recorded in the receipt. - -Exact ownership requests posted to the existing owner PRs: +## Working ACK-private startup/liveness checkpoint; issue 10 remains incomplete + +Tracks #10 without closing it. This draft now includes a production readiness +fix, bounded real-thread controlled-socket tests, the retained original witness +and the ownership/validation receipt. + +### Claims and declaration owners + +Dirac owns src/zmqruntime/ack_listener.py, tests/test_ack_listener.py, the +retained diagnostic and these receipts on fix/ack-delivery-owner-20260930. +Fresh published ZMQ9/159 production claims are disjoint. Parent also confirmed +the relevant external trees clean and notified Lovelace of the private boundary. + +- Lovelace/ZMQ9 retains client.py, execution/server.py, messages.py, + transport_modes.py and paired declaration work. +- No config.py, transport declaration, queue routing, streaming server, + PolyStore, OpenHCS viewer/caller or paired gitlink change is made here. +- Shared routing/config/caller changes still need one agreed editor. +- Parent owns coherent paired gitlink integration. + +Existing TransportEndpoint/TransportDeclaration own address derivation. +Existing EndpointStartupStatus/Phase, OperationDeadline and OperationCancellation +own lifecycle/budget/cancellation semantics. Future conveys the worker bind +outcome, not another registry or lifecycle family. No second endpoint authority, +port/default catalog, decoder, launcher or compatibility route is introduced. + +### Working behavior + +- start waits for bind and propagates the original failure after cleanup. +- _running derives from the original lifecycle declaration: binding and fatal + failures never report ready; fatal receive errors retire the worker. +- Same-address starts share the outcome; different-address reuse is rejected. +- A short joining-caller wait cannot cancel the launch owner's attempt. +- Explicit retry is safe after ownership retires; no automatic replay. +- Stop cancels and joins only its worker, finitely and without self-join. +- Context/socket create, bind, receive and close remain on the listener thread. +- Launch, Future wait and join occur outside the lifecycle lock. +- Premature running flag, separate host/port/mode fields and fatal-error retry + path are removed in place. + +Per-call waits are bounded by 5000ms unless an existing typed operation deadline +is supplied. This is an ACK operation budget, not a changed endpoint default. + +### Executed source evidence + +17 focused checks PASS in 0.39s: 12 real-thread controlled-socket ACK cases plus +existing queue/config tests. Retained inline witness: all 3 PASS in 0.013s. +Original two failures and cleanup pass remain preserved at baseline 4a7864b. +No xfail or weakened readiness assertion. Fixtures check every socket operation +and context termination occurs on its original worker; no real endpoint opens. + +Run with the existing OpenHCS interpreter, PYTHONPATH pointing to this tree's +src, PYTHONDONTWRITEBYTECODE=1, numerical-library thread limits=1, pytest plugin +autoload disabled and cache provider disabled, bounded by timeout 10s: + + python -m pytest -q -p no:cacheprovider tests/test_ack_listener.py tests/test_queue_tracker.py tests/test_config.py + python tests/diagnostics/check_ack_startup_failure.py + +Critical swap remains (16.4 GiB). No heavy/native/provider job, installed change, +foreign process close, scientific replay or biology artifact change occurred. +Full NRA scan and installed/live acceptance are deferred, not certified. + +### Shared coordination and remaining acceptance + +Existing substantive ownership requests: [Lovelace/native PR9](https://github.com/OpenHCSDev/ZMQRuntime/pull/9#issuecomment-5908226428), [viewer PR159](https://github.com/OpenHCSDev/openhcs/pull/159#issuecomment-5908226994). -Posting is verified; owner receipt/agreement is not yet verified. Production -files remain untouched pending explicit single-editor agreement. - -## Remaining acceptance - -After direct file agreements, implement truthful startup/liveness and correctly -owned ACK delivery, then run focused source tests. After an explicit resource -gate and slot release, verify concurrent controlled TCP and applicable IPC -streaming owners, each owner's ACK IDs/queue counts, bind failure visibility, -and stopping one owner while the other continues. Source diagnostics do not -establish installed or concurrent-native readiness. Frozen science, original -collision evidence and the user's preserved viewer remain untouched. +Posting is confirmed; shared editor agreement is not yet confirmed. + +Cross-process ACK return-route/config semantics and any PolyStore/OpenHCS caller +changes remain unfinished. After direct file agreement and explicit resource +gate/slot release, verify concurrent TCP/applicable IPC streaming owners, +their own ACK IDs/queue counts, occupied-endpoint failure and stopping one while +the other continues. Source checks do not prove installed readiness or issue10 +completion. Frozen biology, installed295e and user viewer5690 remain untouched. diff --git a/ACK-ISSUE10-OWNERSHIP-RECEIPT.md b/ACK-ISSUE10-OWNERSHIP-RECEIPT.md index 81fbe2e..48bf859 100644 --- a/ACK-ISSUE10-OWNERSHIP-RECEIPT.md +++ b/ACK-ISSUE10-OWNERSHIP-RECEIPT.md @@ -1,5 +1,77 @@ # Issue 10: source investigation and ownership checkpoint +## Current checkpoint: ACK-private startup/liveness implementation + +The latest owner instruction explicitly permits moving the disjoint private +source fix forward. Published ZMQ9 (28d9ed6) claims only client.py, +execution/server.py, messages.py and transport_modes.py in production; +OpenHCS159 (d45ebbb) claims no ACK listener/queue tracker/streaming-server source. +Parent additionally confirmed both relevant external worktrees clean and notified +Lovelace directly of the boundary. No claim or edit is inferred for those trees. + +Dirac claims and edits src/zmqruntime/ack_listener.py, tests/test_ack_listener.py, +the retained diagnostic and these receipts on fix/ack-delivery-owner-20260930. +No queue routing, streaming server, shared declaration, config, PolyStore, +OpenHCS caller or paired gitlink edit is in this checkpoint. Parent owns paired +gitlink integration; Lovelace retains shared bootstrap/declaration work. + +Working behavior: start waits finitely for bind and propagates the original +failure after cleanup. BINDING does not claim readiness; _running is derived +from the original EndpointStartupPhase.accepts_requests declaration. Fatal +receive failures also retire readiness rather than loop forever. Same-address +calls share the startup outcome; different-address reuse is rejected. An +attaching caller's short wait does not cancel the launch owner's attempt. +Explicit retry is allowed only after the previous worker relinquishes ownership. +Stop cancels and joins only the owned listener, with finite wait and no self-join. + +Address semantics are delegated to existing TransportEndpoint.data_url and +TransportDeclaration; there is no ACK endpoint/default/routing catalog. Typed +EndpointStartupStatus/Phase, OperationCancellation and OperationDeadline remain +their original owners and are consumed without changing those declarations. +Future conveys the worker's bind outcome, not another lifecycle or registry. +The optional deadline uses the existing owner; 5000ms is the finite per-call +ACK startup/shutdown budget, not an endpoint default or timeout inflation. + +All context/socket creation, bind, receive and cleanup occurs on the listener +thread. Launch, Future wait and thread join happen outside the lifecycle lock. +Premature mutable _running, the separate port/host/mode fields and the fatal +receive-error retry path are removed in place, without compatibility fallbacks. +The original ImageAck decoder and queue callback behavior remain unchanged. + +Verification: 17 focused checks passed in 0.39 seconds (12 ACK real-thread +controlled-socket cases plus existing queue/config checks). The retained inline +bind-failure witness passes all three checks; baseline 4a7864b still retains its +two failures and cleanup pass. Real-thread cases cover delayed bind/lock +inversion, original bind error plus retry, same/different endpoint reuse, fatal +receive, bounded stop during bind, attaching-caller timeout isolation, expired +budget, context/thread construction/launch failures, launch-owner timeout and +self-stop after original typed ACK decode. Fixture teardown proves every fake +socket call and context termination uses its original listener thread. + +No real endpoint or native/viewer process is opened by these tests. The source +interpreter is the existing OpenHCS Python, with thread limits=1, pytest plugin +autoload disabled, cache provider disabled, and an outer timeout of 10 seconds. + +The resource guard remains critical: swap 16.4 GiB, RAM available 18.2 GiB, +home free 25.5 GiB. Only tiny serial source tests and a 0.50-second static debt +census ran. The full NRA package/dependency scan and live TCP/IPC acceptance +are deferred under the explicit no-heavy/no-native gate. This is not a global +NRA proof, zero-debt claim or installed-readiness claim. + +The authoritative repo refactor-audit.skill, NRA skill and relevant complete +catalog chapters were read before coding. Reviewed applicable guards: IDEN-3/6 +(one lifecycle/address identity), IMPL-13 (reuse original lifecycle/transport), +BOUND-1/2 (retain original decode boundary), TIME-1/7/9 (remove replaced path, +no copied endpoint defaults or compatibility adapter). + +Remaining issue10 work is distinct: shared cross-process ACK route/config +ownership and any caller changes require direct agreement with Lovelace/current +viewer owner. Concurrent native TCP/IPC ACK-ID/queue accounting and shutdown +isolation remain unverified until resource gate and explicit slot release. +Frozen biology, installed 295e and user viewer5690 are untouched. + +## Historical diagnostic checkpoint (through 4a7864b) + Date: 2026-09-30. Independent task owner: Dirac. Issue: https://github.com/OpenHCSDev/ZMQRuntime/issues/10 Worktree: /home/ts/wt/zmqruntime-ack-delivery-owner-20260930 diff --git a/src/zmqruntime/ack_listener.py b/src/zmqruntime/ack_listener.py index 28bbdcd..0c5698c 100644 --- a/src/zmqruntime/ack_listener.py +++ b/src/zmqruntime/ack_listener.py @@ -5,6 +5,8 @@ import logging import threading import time +from concurrent.futures import Future +from concurrent.futures import TimeoutError as FutureTimeoutError from typing import Callable, Optional import zmq @@ -12,7 +14,9 @@ from zmqruntime.config import TransportMode, ZMQConfig from zmqruntime.messages import ImageAck from zmqruntime.queue_tracker import GlobalQueueTrackerRegistry -from zmqruntime.transport import get_zmq_transport_url, resolve_transport_mode +from zmqruntime.startup import EndpointStartupPhase, EndpointStartupStatus +from zmqruntime.timeouts import OperationCancellation, OperationDeadline +from zmqruntime.transport import TransportEndpoint, resolve_transport_mode from zmqruntime.viewer_state import ViewerStateManager logger = logging.getLogger(__name__) @@ -32,17 +36,38 @@ def __new__(cls): return cls._instance def __init__(self): - if self._initialized: - return - self._callbacks: list[Callable[[ImageAck], None]] = [] - self._running = False - self._thread: Optional[threading.Thread] = None - self._transport_mode: TransportMode | None = None - self._config: ZMQConfig | None = None - self._port: int | None = None - self._host: str = "*" - self._initialized = True - self._register_default_callback() + with self._lock: + if self._initialized: + return + self._condition = threading.Condition() + self._callbacks: list[Callable[[ImageAck], None]] = [] + self._thread: Optional[threading.Thread] = None + self._endpoint: TransportEndpoint | None = None + self._config = ZMQConfig() + self._cancellation = OperationCancellation() + self._startup: Future[None] = Future() + self._status = EndpointStartupStatus( + EndpointStartupPhase.DISCONNECTED, "Ack listener stopped" + ) + self._register_default_callback() + self._initialized = True + + @property + def startup_status(self) -> EndpointStartupStatus: + """Return the listener-owned lifecycle, including terminal failure.""" + with self._condition: + return self._status + + @property + def _running(self) -> bool: + """Derive readiness from the existing lifecycle declaration.""" + return self.startup_status.phase.accepts_requests + + def _set_status(self, phase: EndpointStartupPhase, message: str) -> None: + with self._condition: + self._status = EndpointStartupStatus( + phase, message, self._status.sequence + 1, time.time() + ) def _register_default_callback(self) -> None: def _mark_processed(ack: ImageAck) -> None: @@ -61,7 +86,8 @@ def _mark_processed(ack: ImageAck) -> None: def register_callback(self, callback: Callable[[ImageAck], None]) -> None: """Register callback for ack messages.""" - self._callbacks.append(callback) + with self._condition: + self._callbacks.append(callback) def start( self, @@ -69,48 +95,134 @@ def start( transport_mode: TransportMode | None = None, host: str = "*", config: ZMQConfig | None = None, + *, + timeout_ms: int = 5000, + operation_deadline: OperationDeadline | None = None, ) -> None: - """Start listening on given port.""" - with self._lock: - if self._running: - logger.debug("Ack listener already running") - return - self._transport_mode = resolve_transport_mode(transport_mode) - self._config = config or ZMQConfig() - self._port = port - self._host = host - self._running = True - self._thread = threading.Thread( - target=self._listener_loop, - daemon=True, - name="AckListener", - ) - self._thread.start() + """Return only after bind succeeds, or propagate the actual failure. - def stop(self) -> None: - """Stop the listener.""" - with self._lock: - if not self._running: + Concurrent callers for the same address share its startup outcome. An + already-owned different address is rejected rather than silently reused. + The finite wait uses the existing operation deadline/cancellation owners. + """ + endpoint = TransportEndpoint(host, port, resolve_transport_mode(transport_mode)) + config = config or ZMQConfig() + deadline = operation_deadline or OperationDeadline.after_milliseconds( + timeout_ms, operation="ACK listener startup" + ) + deadline.remaining_seconds() + launch = None + with self._condition: + if self._thread is not None: + assert self._endpoint is not None + if self._endpoint.data_url(self._config) != endpoint.data_url(config): + raise ValueError("Ack listener already owns a different endpoint") + if self._cancellation.requested(): + raise RuntimeError("Ack listener is still stopping") + else: + self._endpoint = endpoint + self._config = config + self._cancellation = OperationCancellation() + self._startup = Future() + self._set_status(EndpointStartupPhase.BINDING_ENDPOINT, endpoint.data_url(config)) + try: + self._thread = threading.Thread( + target=self._listener_loop, + args=(endpoint, config, self._cancellation, self._startup), + daemon=True, + name="AckListener", + ) + except Exception as error: + self._set_status(EndpointStartupPhase.FAILED, str(error)) + self._startup.set_exception(error) + launch = self._thread + startup = self._startup + cancellation = self._cancellation + # Neither thread launch nor outcome/cleanup waits hold the lifecycle lock. + if launch is not None: + try: + launch.start() + except Exception as error: + with self._condition: + self._thread = None + self._set_status(EndpointStartupPhase.FAILED, str(error)) + startup.set_exception(error) + try: + startup.result(timeout=deadline.remaining_seconds_or_zero()) + except FutureTimeoutError: + if startup.done(): + raise + if launch is not None: + with self._condition: + if self._startup is startup: + cancellation.cancel() + self._set_status( + EndpointStartupPhase.FAILED, str(deadline.timeout_error()) + ) + raise deadline.timeout_error() from None + with self._condition: + if self._startup is not startup or not self._running: + raise RuntimeError( + f"Ack listener stopped during startup: {self._status.message}" + ) + + def stop( + self, + *, + timeout_ms: int = 5000, + operation_deadline: OperationDeadline | None = None, + ) -> None: + """Cancel and join only this listener; its thread closes its resources.""" + deadline = operation_deadline or OperationDeadline.after_milliseconds( + timeout_ms, operation="ACK listener shutdown" + ) + with self._condition: + thread = self._thread + if thread is None: return - self._running = False + startup = self._startup + self._cancellation.cancel() + self._set_status(EndpointStartupPhase.DISCONNECTED, "Ack listener stopping") + if thread is threading.current_thread(): + return + # A concurrent stop may arrive before start() launches the stored thread. + # Its startup outcome certifies launch or failure before join is legal. + try: + startup.exception(timeout=deadline.remaining_seconds_or_zero()) + except FutureTimeoutError: + raise deadline.timeout_error() from None + if thread.ident is None: + return + thread.join(timeout=deadline.remaining_seconds_or_zero()) + if thread.is_alive(): + raise deadline.timeout_error() - def _listener_loop(self) -> None: - context = zmq.Context() + def _listener_loop( + self, + endpoint: TransportEndpoint, + config: ZMQConfig, + cancellation: OperationCancellation, + startup: Future[None], + ) -> None: + context = None socket = None + failure = None try: + if cancellation.requested(): + raise RuntimeError("Ack listener cancelled before startup") + context = zmq.Context() socket = context.socket(zmq.PULL) - if self._port is None: - raise RuntimeError("Ack listener port not set") - ack_url = get_zmq_transport_url( - self._port, - host=self._host, - mode=self._transport_mode, - config=self._config, - ) + socket.setsockopt(zmq.LINGER, 0) + ack_url = endpoint.data_url(config) socket.bind(ack_url) + with self._condition: + if cancellation.requested(): + raise RuntimeError("Ack listener cancelled before readiness") + self._set_status(EndpointStartupPhase.CONNECTED, ack_url) + startup.set_result(None) logger.info("Ack listener bound to %s", ack_url) - while self._running: + while not cancellation.requested(): try: if socket.poll(timeout=1000): ack_dict = socket.recv_json() @@ -119,25 +231,41 @@ def _listener_loop(self) -> None: except Exception as e: logger.error("Failed to parse ack message: %s", e, exc_info=True) continue - for callback in list(self._callbacks): + with self._condition: + callbacks = tuple(self._callbacks) + for callback in callbacks: try: callback(ack) except Exception as e: logger.error("Ack callback error: %s", e, exc_info=True) - except zmq.ZMQError as e: - if self._running: - logger.error("ZMQ error in ack listener: %s", e) - time.sleep(0.1) + except zmq.ZMQError: + if not cancellation.requested(): + raise except Exception as e: + failure = e + self._set_status(EndpointStartupPhase.FAILED, str(e)) logger.error("Fatal error in ack listener: %s", e, exc_info=True) finally: - if socket: + if socket is not None: try: - socket.close() - except Exception: - pass - try: - context.term() - except Exception: - pass + socket.close(linger=0) + except Exception as error: + failure = failure or error + logger.error("Ack socket cleanup failed: %s", error, exc_info=True) + if context is not None: + try: + context.term() + except Exception as error: + failure = failure or error + logger.error("Ack context cleanup failed: %s", error, exc_info=True) + with self._condition: + self._thread = None + if failure is not None: + self._set_status(EndpointStartupPhase.FAILED, str(failure)) + else: + self._set_status(EndpointStartupPhase.DISCONNECTED, "Ack listener stopped") + if not startup.done(): + startup.set_exception( + failure or RuntimeError("Ack listener stopped before readiness") + ) logger.info("Ack listener stopped") diff --git a/tests/diagnostics/check_ack_startup_failure.py b/tests/diagnostics/check_ack_startup_failure.py index 6c55f12..f762f61 100644 --- a/tests/diagnostics/check_ack_startup_failure.py +++ b/tests/diagnostics/check_ack_startup_failure.py @@ -1,28 +1,28 @@ -"""Provider-free issue 10 readiness diagnostic; exits nonzero until fixed. +"""Retained provider-free issue 10 bind-failure witness. -Run with the existing interpreter. This is deliberately not pytest-discovered: -it is a visible failing acceptance witness, not an xfail or a passing fix claim. +Run with the existing interpreter and PYTHONPATH pointing at this tree's src. +This is deliberately not pytest-discovered: +it retains the original failing contracts and now passes with the source fix. The real ACK startup/loop runs against a controlled failing socket and inline test thread. No real endpoint, listener thread, native process or viewer opens. +The separate real-thread tests cover lifecycle locks and worker-owned cleanup. """ from __future__ import annotations import errno -import sys import unittest from contextlib import ExitStack from pathlib import Path from unittest.mock import Mock, patch -SOURCE_ROOT = Path(__file__).resolve().parents[2] / "src" -sys.path.insert(0, str(SOURCE_ROOT)) - from zmqruntime import ack_listener from zmqruntime.config import TransportMode, ZMQConfig +SOURCE_ROOT = Path(__file__).resolve().parents[2] / "src" + if not Path(ack_listener.__file__).resolve().is_relative_to(SOURCE_ROOT): raise RuntimeError("Diagnostic must exercise this worktree's ACK listener") @@ -46,9 +46,9 @@ def setUp(self) -> None: self.listener = ack_listener.GlobalAckListener() self.config = ZMQConfig() - def _inline_thread(self, *, target, **options): + def _inline_thread(self, *, target, args=(), **options): thread = Mock() - thread.start.side_effect = target + thread.start.side_effect = lambda: target(*args) return thread def _start(self) -> None: @@ -83,7 +83,7 @@ def test_controlled_reproducer_releases_its_socket_and_context(self) -> None: self.socket.bind.assert_called_once_with( f"tcp://*:{self.config.shared_ack_port}" ) - self.socket.close.assert_called_once_with() + self.socket.close.assert_called_once_with(linger=0) self.context.term.assert_called_once_with() diff --git a/tests/test_ack_listener.py b/tests/test_ack_listener.py new file mode 100644 index 0000000..86526d2 --- /dev/null +++ b/tests/test_ack_listener.py @@ -0,0 +1,331 @@ +"""Real-thread ACK lifecycle checks with controlled sockets, never endpoints.""" + +from __future__ import annotations + +import errno +import queue +import threading +from unittest.mock import Mock + +import pytest + +from zmqruntime import ack_listener +from zmqruntime.config import TransportMode, ZMQConfig +from zmqruntime.messages import ImageAck +from zmqruntime.startup import EndpointStartupPhase +from zmqruntime.timeouts import OperationDeadline, OperationTimeoutError + + +class ControlledAckSocket: + def __init__(self, owner): + self.owner = owner + self.worker = threading.get_ident() + self.bound = threading.Event() + self.closed = threading.Event() + self.url = None + self.bind_error = owner.bind_error + self.poll_error = threading.Event() + self.calls = [] + self.incoming = queue.Queue() + self.received = None + + def setsockopt(self, option, value): + self.calls.append(("setsockopt", threading.get_ident(), option, value)) + + def bind(self, url): + self.calls.append(("bind", threading.get_ident())) + self.url = url + self.bound.set() + if not self.owner.release_bind.wait(1): + raise TimeoutError("Test did not release controlled bind") + if self.bind_error is not None: + raise self.bind_error + + def poll(self, timeout): + if self.poll_error.wait(min(timeout / 1000, 0.01)): + raise ack_listener.zmq.ZMQError(errno.ETERM) + try: + self.received = self.incoming.get_nowait() + except queue.Empty: + return False + return True + + def recv_json(self): + self.calls.append(("recv_json", threading.get_ident())) + return self.received + + def close(self, *, linger): + self.calls.append(("close", threading.get_ident(), linger)) + self.closed.set() + + +class ControlledAckContext: + def __init__(self, owner): + self.controlled_socket = ControlledAckSocket(owner) + self.terminated = threading.Event() + self.terminating_thread = None + + def socket(self, kind): + assert kind == ack_listener.zmq.PULL + return self.controlled_socket + + def term(self): + self.terminating_thread = threading.get_ident() + self.terminated.set() + + +class AckLifecycleHarness: + def __init__(self): + self.contexts = [] + self.bind_error = None + self.release_bind = threading.Event() + self.release_bind.set() + self.context_created = threading.Event() + self.listener = None + self.callers = [] + + def make_context(self): + context = ControlledAckContext(self) + self.contexts.append(context) + self.context_created.set() + return context + + def start_in_caller_thread(self, **kwargs): + errors = [] + returned = threading.Event() + + def start(): + try: + self.listener.start( + ZMQConfig().shared_ack_port, + transport_mode=TransportMode.TCP, + timeout_ms=750, + **kwargs, + ) + except Exception as error: + errors.append(error) + finally: + returned.set() + + caller = threading.Thread(target=start, daemon=True) + self.callers.append(caller) + caller.start() + return caller, returned, errors + + +@pytest.fixture +def harness(monkeypatch): + controlled = AckLifecycleHarness() + monkeypatch.setattr(ack_listener.GlobalAckListener, "_instance", None) + monkeypatch.setattr(ack_listener.zmq, "Context", controlled.make_context) + monkeypatch.setattr(ack_listener, "logger", Mock()) + controlled.listener = ack_listener.GlobalAckListener() + yield controlled + controlled.release_bind.set() + controlled.listener.stop(timeout_ms=1000) + for caller in controlled.callers: + caller.join(timeout=1) + assert not caller.is_alive(), "Controlled caller leaked" + for context in controlled.contexts: + assert context.terminated.wait(1), "Controlled context leaked" + socket = context.controlled_socket + assert socket.closed.is_set() + assert context.terminating_thread == socket.worker + assert all(call[1] == socket.worker for call in socket.calls) + + +def start(listener, **kwargs): + config = ZMQConfig() + listener.start( + config.shared_ack_port, + transport_mode=TransportMode.TCP, + config=config, + timeout_ms=750, + **kwargs, + ) + + +def test_bind_failure_is_original_error_after_worker_cleanup_and_explicit_retry(harness): + listener = harness.listener + collision = ack_listener.zmq.ZMQError(errno.EADDRINUSE) + harness.bind_error = collision + with pytest.raises(ack_listener.zmq.ZMQError) as caught: + start(listener) + assert caught.value is collision + assert not listener._running + assert listener.startup_status.phase is EndpointStartupPhase.FAILED + assert harness.contexts[0].terminated.is_set() + assert listener._thread is None + + harness.bind_error = None + start(listener) + assert listener._running + assert listener.startup_status.phase is EndpointStartupPhase.CONNECTED + assert len(harness.contexts) == 2 + + +def test_bind_readiness_wait_releases_lock_and_stop_joins_worker(harness): + harness.release_bind.clear() + caller, returned, errors = harness.start_in_caller_thread() + assert harness.context_created.wait(1) + assert harness.contexts[0].controlled_socket.bound.wait(1) + assert harness.listener.startup_status.phase is EndpointStartupPhase.BINDING_ENDPOINT + assert not harness.listener._running + assert not returned.is_set() + harness.release_bind.set() + assert returned.wait(1), "Startup/loop lock inversion" + caller.join(timeout=1) + assert not errors + assert harness.listener._running + harness.listener.stop(timeout_ms=750) + assert not harness.listener._running + assert harness.contexts[0].terminated.is_set() + assert harness.listener._thread is None + + +def test_same_endpoint_reuse_and_different_endpoint_rejection(harness): + start(harness.listener) + start(harness.listener) + assert len(harness.contexts) == 1 + with pytest.raises(ValueError, match="different endpoint"): + harness.listener.start( + ZMQConfig().shared_ack_port + 1, + transport_mode=TransportMode.TCP, + timeout_ms=750, + ) + assert harness.listener._running + assert len(harness.contexts) == 1 + + +def test_fatal_receive_clears_readiness_and_releases_resources(harness): + start(harness.listener) + context = harness.contexts[0] + context.controlled_socket.poll_error.set() + assert context.terminated.wait(1) + # Join through the public owner to synchronize final lifecycle publication. + harness.listener.stop(timeout_ms=750) + assert not harness.listener._running + assert harness.listener.startup_status.phase is EndpointStartupPhase.FAILED + + +def test_stop_during_bind_is_finite_and_never_publishes_readiness(harness): + harness.release_bind.clear() + caller, returned, errors = harness.start_in_caller_thread() + assert harness.context_created.wait(1) + assert harness.contexts[0].controlled_socket.bound.wait(1) + with pytest.raises(OperationTimeoutError): + harness.listener.stop(timeout_ms=20) + assert not harness.listener._running + harness.release_bind.set() + assert returned.wait(1) + caller.join(timeout=1) + assert len(errors) == 1 + assert isinstance(errors[0], RuntimeError) + assert "cancelled before readiness" in str(errors[0]) + harness.listener.stop(timeout_ms=750) + assert not harness.listener._running + assert harness.listener._thread is None + + +def test_joining_caller_timeout_does_not_cancel_existing_start_owner(harness): + harness.release_bind.clear() + caller, returned, errors = harness.start_in_caller_thread() + assert harness.context_created.wait(1) + assert harness.contexts[0].controlled_socket.bound.wait(1) + with pytest.raises(OperationTimeoutError): + harness.listener.start( + ZMQConfig().shared_ack_port, + transport_mode=TransportMode.TCP, + timeout_ms=20, + ) + assert harness.listener.startup_status.phase is EndpointStartupPhase.BINDING_ENDPOINT + harness.release_bind.set() + assert returned.wait(1) + caller.join(timeout=1) + assert not errors + assert harness.listener._running + + +def test_expired_deadline_has_no_context_or_thread_side_effect(harness): + with pytest.raises(OperationTimeoutError): + start( + harness.listener, + operation_deadline=OperationDeadline("already expired", 1, 0), + ) + assert not harness.contexts + assert harness.listener._thread is None + + +def test_context_creation_failure_is_reported_without_stale_running_state(harness, monkeypatch): + failure = RuntimeError("controlled context creation failure") + monkeypatch.setattr(ack_listener.zmq, "Context", Mock(side_effect=failure)) + with pytest.raises(RuntimeError) as caught: + start(harness.listener) + assert caught.value is failure + assert harness.listener._thread is None + assert not harness.listener._running + + +def test_thread_launch_failure_is_reported_without_context_allocation(harness, monkeypatch): + failure = RuntimeError("controlled thread launch failure") + thread = Mock() + thread.start.side_effect = failure + monkeypatch.setattr(ack_listener.threading, "Thread", Mock(return_value=thread)) + with pytest.raises(RuntimeError) as caught: + start(harness.listener) + assert caught.value is failure + assert not harness.contexts + assert harness.listener._thread is None + assert not harness.listener._running + + +def test_thread_construction_failure_has_terminal_status(harness, monkeypatch): + failure = RuntimeError("controlled thread construction failure") + monkeypatch.setattr(ack_listener.threading, "Thread", Mock(side_effect=failure)) + with pytest.raises(RuntimeError) as caught: + start(harness.listener) + assert caught.value is failure + assert harness.listener.startup_status.phase is EndpointStartupPhase.FAILED + assert harness.listener._thread is None + assert not harness.contexts + + +def test_start_owner_timeout_cancels_only_its_attempt_then_allows_explicit_retry(harness): + harness.release_bind.clear() + with pytest.raises(OperationTimeoutError): + harness.listener.start( + ZMQConfig().shared_ack_port, + transport_mode=TransportMode.TCP, + timeout_ms=20, + ) + assert not harness.listener._running + assert harness.listener.startup_status.phase is EndpointStartupPhase.FAILED + with pytest.raises(RuntimeError, match="still stopping"): + start(harness.listener) + harness.release_bind.set() + harness.listener.stop(timeout_ms=750) + start(harness.listener) + assert harness.listener._running + assert len(harness.contexts) == 2 + + +def test_typed_ack_callback_can_stop_its_own_worker_without_self_join(harness): + received = [] + + def stop_from_callback(ack): + received.append(ack) + harness.listener.stop(timeout_ms=750) + + harness.listener.register_callback(stop_from_callback) + start(harness.listener) + context = harness.contexts[0] + ack = ImageAck("controlled-image", ZMQConfig().shared_ack_port, "controlled-viewer") + # A rejected malformed frame must not kill the healthy listener or introduce + # another decoder. The subsequent valid record uses the original wire owner. + context.controlled_socket.incoming.put({}) + context.controlled_socket.incoming.put(ack.to_dict()) + assert context.terminated.wait(1) + harness.listener.stop(timeout_ms=750) + assert received == [ack] + assert not harness.listener._running + assert harness.listener.startup_status.phase is EndpointStartupPhase.DISCONNECTED From aff9fc8e55f3fa09892d930e414c2e39360a7700 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 30 Sep 2026 06:25:01 -0400 Subject: [PATCH 4/5] test: cover ACK cancellation before real listener launch --- ACK-ISSUE10-DRAFT-PR-BODY.md | 2 +- ACK-ISSUE10-OWNERSHIP-RECEIPT.md | 12 ++++++++++-- src/zmqruntime/ack_listener.py | 6 ++++-- tests/test_ack_listener.py | 32 ++++++++++++++++++++++++++++++++ 4 files changed, 47 insertions(+), 5 deletions(-) diff --git a/ACK-ISSUE10-DRAFT-PR-BODY.md b/ACK-ISSUE10-DRAFT-PR-BODY.md index c33ac8d..3e993c1 100644 --- a/ACK-ISSUE10-DRAFT-PR-BODY.md +++ b/ACK-ISSUE10-DRAFT-PR-BODY.md @@ -43,7 +43,7 @@ is supplied. This is an ACK operation budget, not a changed endpoint default. ### Executed source evidence -17 focused checks PASS in 0.39s: 12 real-thread controlled-socket ACK cases plus +18 focused checks PASS in 0.41s: 13 real-thread controlled-socket ACK cases plus existing queue/config tests. Retained inline witness: all 3 PASS in 0.013s. Original two failures and cleanup pass remain preserved at baseline 4a7864b. No xfail or weakened readiness assertion. Fixtures check every socket operation diff --git a/ACK-ISSUE10-OWNERSHIP-RECEIPT.md b/ACK-ISSUE10-OWNERSHIP-RECEIPT.md index 48bf859..9a5d9f3 100644 --- a/ACK-ISSUE10-OWNERSHIP-RECEIPT.md +++ b/ACK-ISSUE10-OWNERSHIP-RECEIPT.md @@ -38,14 +38,15 @@ Premature mutable _running, the separate port/host/mode fields and the fatal receive-error retry path are removed in place, without compatibility fallbacks. The original ImageAck decoder and queue callback behavior remain unchanged. -Verification: 17 focused checks passed in 0.39 seconds (12 ACK real-thread +Verification: 18 focused checks passed in 0.41 seconds (13 ACK real-thread controlled-socket cases plus existing queue/config checks). The retained inline bind-failure witness passes all three checks; baseline 4a7864b still retains its two failures and cleanup pass. Real-thread cases cover delayed bind/lock inversion, original bind error plus retry, same/different endpoint reuse, fatal receive, bounded stop during bind, attaching-caller timeout isolation, expired budget, context/thread construction/launch failures, launch-owner timeout and -self-stop after original typed ACK decode. Fixture teardown proves every fake +self-stop after original typed ACK decode, and stop before listener thread +launch without joining an unstarted thread. Fixture teardown proves every fake socket call and context termination uses its original listener thread. No real endpoint or native/viewer process is opened by these tests. The source @@ -70,6 +71,13 @@ viewer owner. Concurrent native TCP/IPC ACK-ID/queue accounting and shutdown isolation remain unverified until resource gate and explicit slot release. Frozen biology, installed 295e and user viewer5690 are untouched. +The working checkpoint supersedes the draft's diagnostic-only status. Initial +source implementation commit: 859070c7b8b12460b01140ff040399ce38b90cd5. +Subsequent private refinements query Thread.is_alive through its original owner +instead of reconstructing launch state from Thread.ident, and preserve original +worker timeout errors while using the canonical deadline for a wait-timeout race. +Ruff E/F checks and git diff --check pass. No endpoint bind occurs in any test. + ## Historical diagnostic checkpoint (through 4a7864b) Date: 2026-09-30. Independent task owner: Dirac. diff --git a/src/zmqruntime/ack_listener.py b/src/zmqruntime/ack_listener.py index 0c5698c..c8d203c 100644 --- a/src/zmqruntime/ack_listener.py +++ b/src/zmqruntime/ack_listener.py @@ -151,7 +151,9 @@ def start( startup.result(timeout=deadline.remaining_seconds_or_zero()) except FutureTimeoutError: if startup.done(): - raise + # Preserve a real worker exception; a completion racing the + # wait timeout must still use the caller's canonical deadline. + startup.result() if launch is not None: with self._condition: if self._startup is startup: @@ -191,7 +193,7 @@ def stop( startup.exception(timeout=deadline.remaining_seconds_or_zero()) except FutureTimeoutError: raise deadline.timeout_error() from None - if thread.ident is None: + if not thread.is_alive(): return thread.join(timeout=deadline.remaining_seconds_or_zero()) if thread.is_alive(): diff --git a/tests/test_ack_listener.py b/tests/test_ack_listener.py index 86526d2..d450836 100644 --- a/tests/test_ack_listener.py +++ b/tests/test_ack_listener.py @@ -329,3 +329,35 @@ def stop_from_callback(ack): assert received == [ack] assert not harness.listener._running assert harness.listener.startup_status.phase is EndpointStartupPhase.DISCONNECTED + + +def test_stop_before_listener_thread_launch_is_bounded_without_joining_unstarted_thread( + harness, monkeypatch +): + before_launch = threading.Event() + release_launch = threading.Event() + original_start = threading.Thread.start + + def gated_start(thread): + if thread.name == "AckListener": + before_launch.set() + if not release_launch.wait(1): + raise TimeoutError("Test did not release listener launch") + return original_start(thread) + + monkeypatch.setattr(threading.Thread, "start", gated_start) + caller, returned, errors = harness.start_in_caller_thread() + try: + assert before_launch.wait(1) + with pytest.raises(OperationTimeoutError): + harness.listener.stop(timeout_ms=20) + assert not harness.listener._running + finally: + release_launch.set() + assert returned.wait(1) + caller.join(timeout=1) + assert len(errors) == 1 + assert "cancelled before startup" in str(errors[0]) + harness.listener.stop(timeout_ms=750) + assert harness.listener._thread is None + assert not harness.contexts From e7dd84bf1a9c634fe8923d6dab6f94c14174e585 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 30 Sep 2026 06:27:25 -0400 Subject: [PATCH 5/5] docs: record measured ACK private source census and proof limits --- ACK-ISSUE10-OWNERSHIP-RECEIPT.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/ACK-ISSUE10-OWNERSHIP-RECEIPT.md b/ACK-ISSUE10-OWNERSHIP-RECEIPT.md index 9a5d9f3..03a7f6e 100644 --- a/ACK-ISSUE10-OWNERSHIP-RECEIPT.md +++ b/ACK-ISSUE10-OWNERSHIP-RECEIPT.md @@ -78,6 +78,18 @@ instead of reconstructing launch state from Thread.ident, and preserve original worker timeout errors while using the canonical deadline for a wait-timeout race. Ruff E/F checks and git diff --check pass. No endpoint bind occurs in any test. +Static source census at aff9fc8 versus 4a7864b, root src/zmqruntime, measures +the touched production file after minus before: code lines +121; own None +identity checks +7; broad exception boundaries +2. All measured changes for +type-identity checks, long chains/terms, codec subclasses, foreign absence +probes, string/type dispatch and their arms, raw string-key reads/gets, +getattr/default probes, long functions, classes/ABCs/enums are zero. The extra +None checks describe this owner's optional endpoint/thread/deadline and local +cleanup resources. The two extra exception boundaries report owned thread +construction/launch failures through the startup outcome rather than hide them. +No densities are inferred from under 500 net changed code lines. These syntax +counts are screening evidence, not zero debt, R1 proof or semantic equivalence. + ## Historical diagnostic checkpoint (through 4a7864b) Date: 2026-09-30. Independent task owner: Dirac.