fix(pubsub): stop running subscriber callbacks on the publishing thread - #250
Open
YuanYuYuan wants to merge 18 commits into
Open
fix(pubsub): stop running subscriber callbacks on the publishing thread#250YuanYuYuan wants to merge 18 commits into
YuanYuYuan wants to merge 18 commits into
Conversation
YuanYuYuan
force-pushed
the
pr/2-pubsub-reentrancy
branch
from
July 28, 2026 08:06
1f04eb3 to
1006b7d
Compare
There was a problem hiding this comment.
Pull request overview
Fixes subscriber callback deadlocks by moving hazardous delivery off publishing threads and updating Python bindings accordingly.
Changes:
- Adds QoS-aware subscriber selection and callback dispatch queues.
- Releases Python’s GIL during publishing and removes a receive-side payload copy.
- Adds Rust and Python regression and backpressure tests.
Reviewed changes
Copilot reviewed 9 out of 9 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
crates/hiroz/src/pubsub.rs |
Implements dispatching and QoS-aware subscribers. |
crates/hiroz/src/node.rs |
Applies dispatching to raw subscribers. |
crates/hiroz/src/ffi/subscriber.rs |
Stores generalized subscriber handles. |
crates/hiroz/src/common.rs |
Identifies handlers that execute user code. |
crates/hiroz-tests/tests/reentrant_publish.rs |
Tests reentrant publishing and teardown. |
crates/hiroz-tests/tests/dispatch_backpressure.rs |
Tests dispatcher queue bounds. |
crates/hiroz-py/tests/test_reentrant_publish.py |
Tests Python reentrancy and thread cleanup. |
crates/hiroz-py/src/pubsub.rs |
Releases the GIL while publishing. |
crates/hiroz-py/src/node.rs |
Uses borrowed sample payloads in callbacks. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 12 out of 12 changed files in this pull request and generated no new comments.
Comments suppressed due to low confidence (4)
crates/hiroz/src/pubsub.rs:1325
- This branch runs before
runs_user_codeis checked, so every TransientLocal queue/notifier subscriber (including rmw'sbuild_with_notifierpath) gets an unbounded dispatcher even though its handler only enqueues. That delays the wait-set notification and permits an unbounded backlog ahead of the already boundedBoundedQueue, contradicting the queue-mode contract below. Split the advanced path onruns_user_codeand wire queue handlers directly to the advanced subscriber callback.
let inner = if qos_needs_advanced(&self.entity.qos) {
crates/hiroz/src/pubsub.rs:1526
build_internalalready performs this encoding validation for everyDataHandlerat lines 1300–1320. Wrapping the new callback again parses each encoding twice and emits duplicate mismatch/unknown-format logs. Pass the callback directly tobuild_internal.
let expected_encoding = self.expected_encoding.clone();
let callback = Arc::new(move |sample: Sample| {
crates/hiroz-py/tests/test_reentrant_publish.py:132
- This makes the Python suite fail unconditionally on macOS, although macOS Python wheels are supported (
docs/bindings/python.md:13-14)./proc/self/taskis Linux-only and is needed solely by the drain-thread leak detector; skip that one test on unsupported platforms (a skip is not a false pass) while still running the portable re-entrancy tests.
# The leak test can only see the Rust drain thread through procfs.
assert os.path.isdir("/proc/self/task"), (
"/proc/self/task is unavailable - the drain-thread leak test cannot run "
"on this platform and must not be reported as passing"
)
crates/hiroz-py/src/pubsub.rs:38
- The watchdog test does not independently exercise this GIL release: with dispatcher delivery enabled, the seed
publish()returns quickly, and the test then sleeps for 300 ms before measuring progress, so reverting onlyallow_threadsstill passes. Add a detector that keeps the zenoh publish blocked while another Python thread must make progress; otherwise this regression can return unnoticed.
py.allow_threads(|| self.inner.publish(zbuf.into()))
.map_err(|e| e.into_pyerr())
YuanYuYuan
force-pushed
the
pr/2-pubsub-reentrancy
branch
4 times, most recently
from
July 29, 2026 09:13
90092b2 to
db3c6cc
Compare
This was referenced Jul 30, 2026
YuanYuYuan
force-pushed
the
pr/2-pubsub-reentrancy
branch
2 times, most recently
from
August 5, 2026 16:54
85fb828 to
60a8dcd
Compare
This was referenced Aug 5, 2026
Open
Publishing from inside a subscriber callback on the same session deadlocked deterministically, with no error and no traceback. Three separate mechanisms had to be removed. 1. Every subscriber was declared as a zenoh-ext `AdvancedSubscriber`, unconditionally. Its sample callback takes a `std::sync::Mutex` and then invokes the user callback under that guard. `std::sync::Mutex` is not reentrant, so a callback that published into its own topic graph re-entered a mutex its own thread already held further up the stack. Declare the advanced subscriber only when the QoS profile actually configures advanced features: for Volatile — the ROS 2 default — an `AdvancedSubscriber` declares no liveliness subscriber, no heartbeat subscriber and no detection token, so it was pure per-sample overhead plus the fatal lock. 2. Zenoh delivers a same-session sample synchronously, inline on the thread that called `put`. With the lock gone, a callback that publishes therefore *recursed* instead of iterating, until the stack overflowed. Adopt the shape zenoh's own `FifoChannel` uses, and that zenoh-python installs by default for a Python callable: delivery enqueues and returns, user code runs elsewhere. `ZPub`'s four publish paths hold a thread-local marker across the zenoh `put`; the plain subscriber's shim enqueues when that marker is set and invokes inline when it is not. An inter-process sample arrives on a zenoh RX worker, which is never inside a hiroz publish, so that path keeps its inline call and pays one thread-local read. Queue-mode subscribers — every rmw subscription, and every `recv()`-based user — already enqueue and return, so they get no dispatcher at all. The marker keys on the publishing thread rather than on zenoh's `Locality` on purpose: two sessions in one process with a direct route deliver a `Locality::Remote` sample inline on the publisher's thread, so an `allowed_origin(SessionLocal)` split would miss that case. With no path left on which a callback is reachable from inside `put`, re-entrancy is structurally impossible rather than depth-bounded, so the interim `MAX_CALLBACK_REENTRY_DEPTH` cap, `CallbackDepthGuard` and `InheritedCallbackDepth` are removed rather than left as unreachable defensive code. 3. `hiroz-py`'s `ZPublisher.publish`/`publish_raw` release the GIL across the zenoh publish. This does not fix the deadlock, but it downgrades a whole-interpreter freeze — no exception, no traceback, only an external kill — to a single blocked thread, which is the difference between an undiagnosable hang and a diagnosable one. Queue policy is split per path. The plain dispatcher takes its capacity from the same history-QoS expression `build()` uses to size `BoundedQueue` and drops the oldest on overflow; the advanced dispatcher stays unbounded. Bounded and blocking recreates the deadlock on both paths — the blocked producer sits inside the callback holding the very lock the drain thread needs. Bounded and dropping is correct for the plain path, which is Volatile with KEEP_LAST(depth) and already promises no more than `depth` undelivered samples, and wrong for the advanced path, where loss would discard samples miss-detection went out of its way to recover, mid-reorder. Also adds `ZSubBuilder::build_with_sample_callback`, which hands the callback the `Sample` rather than a decoded message, and uses it in `hiroz-py`. The Python callback path routed every sample through an identity codec whose `Output` carries no lifetime, so it had to `to_vec()` the whole payload before the callback ran, only for msgspec to decode out of it and drop it — one full payload copy per message. Measured as an interleaved paired A/B (two release wheels differing only in this call site, 5+6 reps, 16k timed round trips each, half-trip p50): 64 B 114.5 -> 114.1 (noise), 4 KB 120.9 -> 121.0 (noise), 64 KB 224.4 -> 221.1, -3.4 us with 10 of 11 reps in [-2.6, -5.1]. The size-dependence is the point: it is what distinguishes removing a payload-sized memcpy from removing a fixed per-message cost. Wire format is unchanged: an `AdvancedPublisher` with no cache, no publisher_detection and no sample_miss_detection puts on the plain key expression, so Volatile publishers and subscribers stay byte-identical and interop is unaffected. Volatile subscribers no longer get zenoh-ext's HLC-timestamp de-duplication. Ordering is preserved where it was ever guaranteed: one FIFO queue, one drain thread, and drop-oldest preserves the relative order of what survives. Not preserved, and documented at the type: a plain subscriber receiving both local and remote publications on one topic now runs them on two different threads, so their relative order is not guaranteed. Neither ROS 2 nor zenoh guarantees ordering across publishers, and a plain zenoh subscriber could already be invoked concurrently from several RX workers. Detector evidence, both directions. Reverting the dispatch decision (`local_publish_active() -> false`) and keeping the tests, all three self-feeding loop tests die with `fatal runtime error: stack overflow, aborting` (rc=101), including `intra_closed_loop_runs_iteratively`, which drives 2_000 round trips through a two-topic one-session callback cycle that could not previously be expressed as a loop. Against the unfixed sources the original three scenarios fail on their 20s deadline (`0 passed; 3 failed`). Every one of the six Python cells hangs with rc=124 under an external wall-clock timeout on a wheel built from unfixed sources — not merely fails, hangs — and all six pass on this branch.
Three defects, all in this branch's own new machinery. **The FFI publish path was never marked local.** `local_only_shim` hands a sample to the drain thread only while `LOCAL_PUBLISH_DEPTH` is set, and that flag comes from `LocalPublishGuard`. All four `ZPub` publish methods take the guard; `RawPublisher::publish_bytes` did not. A same-process raw publish was therefore delivered inline on the publishing thread, so a raw callback that publishes back into its own topic recurses until the stack is gone -- the exact defect the dispatcher exists to prevent, still reachable through the FFI door, which is the door `rmw-zenoh-rs` uses. **A bounded queue claimed to be lossless.** The backlog warning fired whenever the pending count crossed `DISPATCH_BACKLOG_WARN_AT`, and told the user the queue "is lossless, so the backlog costs memory". Both nearby comments assert that only unbounded dispatchers reach it, but nothing enforced that: capacity comes from `KeepLast(depth)`, and a `KeepLast(1024)` subscriber has exactly that capacity. It would warn that it cannot lose samples immediately before dropping one. Gate the warning on `DISPATCH_UNBOUNDED`; bounded queues already have an accurate drop warning. **A doc link pointed at a function that does not exist.** `LocalPublishGuard` claimed every publish "funnels through `ZPub::finish_put`". There is no such method and no choke point -- four call sites each enter the guard. The next author to add a fifth publish path would have gone looking for a funnel, not found one, and shipped without the guard, silently reinstating the bug above. `hiroz-tests` now enables `hiroz/ffi`. Without it the raw API is not compiled into the test crate at all, so the FFI surface had no coverage and any test written against it would have compiled away to nothing. The new test asserts thread identity rather than absence of a crash: proving the recursion directly needs an unbounded feedback loop, which aborts the runner and explains nothing. Verified in both directions -- with the guard the callback lands on the drain thread and it passes; with the guard removed the callback and the publisher report the same `ThreadId(2)` and it fails.
Enabling `hiroz/ffi` for `hiroz-tests` makes `clippy-tests` lint `crates/hiroz/src/ffi/*` for the first time, and that module has 22 pre-existing `missing_safety_doc` violations across `action.rs`, `serialize.rs` and `service.rs`. Under `-D warnings` the job fails. The guard fix in `RawPublisher::publish_bytes` stays -- it is the actual defect fix, and it was verified in both directions locally: with the guard removed, the raw subscriber callback and the publisher report the same `ThreadId`, meaning delivery happens inline on the publishing thread and a callback that republishes recurses until the stack is gone. What is lost is the CI regression test for that path, and the honest reason is scope: making it runnable requires documenting the safety contract of 22 `pub unsafe extern "C"` functions, which does not belong in a pull request about subscriber-callback re-entrancy. Writing 22 perfunctory `# Safety` blocks without establishing each contract would be worse than leaving them. Follow-up, worth filing: the FFI surface is entirely unlinted and untested because the feature is off everywhere. That is its own defect, and it is why this fix could ship unnoticed in the first place.
Two defects in the new dispatcher, both on teardown, both found by an
adversarial review pass.
**The Python bindings deadlocked the interpreter on teardown.** Dropping a
`ZSub` joins its delivery thread, and that thread's callback body is
`Python::with_gil`. `destroy_subscriber` is a `#[pymethods]` fn, so it runs
with the GIL held: it waits for the thread, the thread waits for the GIL, and
the interpreter freezes with no exception and no traceback. Reachable from
`destroy_subscriber`, `del node`, or interpreter exit -- `tp_dealloc` holds
the GIL too, and `PyZNode` had no `Drop`. This is the same failure class the
PR removes, relocated from `publish()` to teardown, and newly reachable
because nothing joined a GIL-needing thread before. `destroy_subscriber` now
takes a `Python` token and drops under `py.allow_threads`; `PyZNode` gets a
`Drop` that does the same for the subscribers it owns.
The existing `test_transient_local_dispatcher_threads_do_not_leak` passes
either way: it calls `_settle(...)` first, so the drain thread is parked in
`dequeue` and the hazard window is closed before the drop.
**`drop(subscriber)` could block for minutes, or forever.** `dequeue` popped
`pending` before honouring `closed`, so `Drop` ran a user callback for every
queued sample before returning. On the unbounded TransientLocal path that is
`backlog x callback_duration` with no ceiling -- a 1 kHz publisher against a
5 ms callback leaves ~30 000 samples queued after 30 s, blocking the drop for
~150 s with no log line and no way to cancel. It could block forever if a
callback waited on anything the dropping thread had to supply.
`closed` is now checked first. Dropping a subscriber means "stop delivering to
me", so the undelivered backlog is discarded rather than forced through a
callback the caller has already disposed of -- what destroying an rclcpp
subscription does. Teardown costs at most one in-flight callback.
That last point is a deliberate reversal of the previous documented intent
("drain what is queued, then exit"); it is now declared in Breaking Changes,
along with two breaks the description had omitted: Volatile subscriber
callbacks are no longer mutually excluded (they were, via zenoh-ext's
`Mutex<State>`, since every subscriber used to be an `AdvancedSubscriber`),
and `RawSubscriber::inner` changed type.
reentrant_publish 10/10 and dispatch_backpressure 2/2 still pass, including
both teardown scenarios.
The ROS interop step captured nextest's output with `complete` and never printed it, so a green job showed the command echo followed by "All ROS 2 <distro> tests passed!" and nothing in between. That banner could not be falsified: nextest exits 0 having run zero tests, and each interop test returns early -- still passing -- when check_ros2_available says no. Print the captured output and require a nextest summary reporting a non-zero count. Also correct two doc claims in pubsub.rs: the dispatcher and queue-mode capacities are not the same expression (they differ at a zero depth, harmlessly -- now pinned by two queue tests), and catch_unwind around a user callback is inert under the abort-on-panic opt profile.
Every other scenario in this file drives the synchronous publish, so the async path was unpinned. It is guarded differently and the difference is load-bearing: the guard is scoped to into_future() rather than held across the await, which is only sufficient because zenoh resolves a put eagerly there (IntoFuture = ready(self.wait()), zenoh 1.9.0). That is an upstream implementation detail, not a contract -- if the put ever became lazy it would move outside the guard and every deadlock this file prevents would return on the async path unnoticed. Asserts on thread identity rather than waiting for a hang, so it fails in a second with a legible message. Proven in both directions: dropping the guard from the async path fails it on the assertion.
Two changes here were not about subscriber re-entrancy and are moved to their own pull requests: - scripts/test-ros.nu, the non-vacuous interop gate. CI hygiene, found while gathering evidence for this fix. - ZSubBuilder::build_with_sample_callback and its hiroz-py call site, a payload-copy removal. It shared a call site with the re-entrancy fix, which is proximity, not a reason to review them together. Nothing else changes. The 13 tests in reentrant_publish and dispatch_backpressure still pass, and the GIL-release and teardown fixes in hiroz-py stay -- those are the same defect as the deadlock, reached from Python.
Review found the advanced branch was taken on `qos_needs_advanced` alone, before `runs_user_code` was consulted, so every TransientLocal queue-mode subscriber -- /tf_static, /robot_description, every latched rmw subscription -- got a dispatcher thread it does not need. That is an extra OS thread per subscription, an extra thread hop and condvar wake per sample on the inter-process path, and an unbounded queue in front of the bounded one. A queue-mode handler runs no user code, so zenoh-ext's state lock is not a hazard for it. Note the fix is NOT to gate the whole branch on runs_user_code, as first suggested: TransientLocal needs the AdvancedSubscriber for history replay and miss recovery whether or not user code runs. Only the dispatcher is conditional, so `SubscriberHandle::Advanced::dispatcher` becomes an Option, mirroring the Plain variant. Also removes an invented history from two shipped test files: MAX_CALLBACK_REENTRY_DEPTH and its depth cap of 16 never existed on main, so "this caps out at 16" was asserting a behaviour that never shipped. On main the same loop deadlocks -- which is the defect being fixed.
always_shim returns an opaque impl Fn, so it cannot share a match arm with a plain closure -- E0308 on the previous commit. Box both to Box<dyn Fn(Sample) + Send + Sync>.
The second SubscriberHandle::Advanced construction site is in the raw FFI subscriber path, behind #[cfg(feature = "ffi")]. ci.yml never builds with that feature, so it compiled clean there and only test.yml's "Build Rust FFI library" step caught it -- which is exactly the gap issue #270 describes.
This branch predates #271 and carried an older scripts/test-ros.nu. Rebasing replayed it, deleting the two `print` lines #271 added -- so merging would have restored a banner that cannot fail: nextest exits 0 when it runs zero tests, and without the output nothing distinguishes 57 passing interop tests from a binary that matched none. Restores the file to main's version. The extraction commit's own message says it split the CI gate out to #271; the file did not follow.
The advanced (TransientLocal) construction site passed DISPATCH_UNBOUNDED unconditionally, on the argument that dropping would discard the samples miss-detection recovered. That argument holds for KeepAll -- which dispatch_capacity still maps to DISPATCH_UNBOUNDED -- but it was applied to every profile, so a KeepLast(10) subscriber got an unbounded queue. Because the advanced path's shim enqueues remote samples too, that traded zenoh's transport backpressure for unbounded in-process growth: a remote publisher outpacing a slow callback grew the backlog until the process died, with only a doubling-threshold warn! for a signal. Both paths now pass dispatch_capacity, so a callback subscriber retains what its history QoS declares regardless of which path it takes -- which is what the PR description already claimed. Adds the two advanced-path scenarios the file was missing; every existing test in it takes the plain path, so nothing detected this.
… depth" This reverts aa7b66d. Bounding the advanced queue at the declared depth breaks transient_local_delivery_preserves_order, which publishes 500 samples through a KeepLast(10) TransientLocal subscriber and asserts all 500 arrive in order. At depth 10 the queue drops 490. That test is not incidental -- it encodes what the CallbackDispatcher doc states outright: on the advanced path, loss is a correctness bug rather than a QoS allowance, because a TransientLocal subscriber exists to replay history and recover samples zenoh-ext went out of its way to fetch. So the adversarial finding stands (an unbounded queue fed by remote samples has no backpressure and can grow until OOM) but the remedy does not: a thread-handoff buffer sized by the history depth conflates two different things. A burst-tolerant buffer with an absolute cap is the shape that satisfies both; that needs its own design and its own number.
…y depth" This reverts commit 4cb3424.
…ded path transient_local_delivery_preserves_order published 500 samples through a KeepLast(10) subscriber and asserted all 500 arrived. That asserts a promise no RMW makes: rmw_zenoh_cpp's add_new_message drops the oldest once message_queue_.size() >= adapted_qos_profile.depth, for every arriving sample, with no TransientLocal exemption -- the check reads the history policy only. The test's stated property is ordering, and its own doc says so. Assert that instead: a strictly increasing subsequence of what was published. That catches reordering whether or not anything was dropped, where an equality check conflated the two failures. Losslessness is still covered, on the profile that actually promises it, by keep_all_delivers_every_local_sample. Also records in the dispatcher docs that both implementations drop silently w.r.t. the ROS event API: upstream's MESSAGE_LOST comes from sequence-number gaps among arriving messages, which a depth-drop cannot produce, so bounding introduces no reporting gap.
The conversion to dispatch_capacity covered three of four CallbackDispatcher::spawn sites. node.rs's advanced (TransientLocal) arm still passed DISPATCH_UNBOUNDED, so an FFI raw subscriber declaring KeepLast(n) got an unbounded queue fed by remote samples -- the exact defect the other three sites were changed to remove. Two shipped doc comments and the PR description asserted 'both paths pass dispatch_capacity'. There are four paths, and one did not. Nothing caught it because the ffi feature is enabled by no crate, so this arm is never compiled on the PR gate (#291). Found by an audit agent reading the diff against its own description.
YuanYuYuan
force-pushed
the
pr/2-pubsub-reentrancy
branch
from
August 6, 2026 10:35
12a968a to
d11d710
Compare
The comment said the ffi arm 'is not compiled on the PR gate at all'. It is compiled -- test.yml builds --features ffi on pull_request. What is missing is narrower: it is never linted and never tested, and its re-entrancy detector had been deleted. A wrong constant is neither a compile error nor a lint, so nothing was left to catch it. Building is not testing. The same false explanation was corrected in #291 and in this PR's description; the source comment was written in the same commit and missed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Part of #282 — the defect class, the shared fix shape and the merge order are stated there.
Summary
Publishing from inside a subscriber callback on the same session deadlocked deterministically. This moves session-local delivery off the publishing thread onto a bounded per-subscriber drain queue, and stops declaring zenoh-ext's
AdvancedSubscriberfor QoS profiles that do not need it.Role in #282: instance fix. Independent of the keystone (#255): it targets
main, uses no tracked lock types, and can merge in any order. Its locks are candidates for conversion in the follow-up that closes #282.The tip is
d11d710c, merge-baseae4f0f8f(origin/mainafter #260 merged). Of 2,525 changed lines (2,485 added, 40 removed), 1,670 (66%) are the three new test files:crates/hiroz-tests/tests/reentrant_publish.rs(904),crates/hiroz-py/tests/test_reentrant_publish.py(435),crates/hiroz-tests/tests/dispatch_backpressure.rs(331) — 15 new Rust tests and 9 Python cases.Issue
Fixes #249. There was no error and no traceback. Through the Python bindings it froze the whole interpreter.
What this PR does
Three stacked mechanisms produced the hang. This removes all three.
AdvancedSubscriberonly when QoS needs it (qos_needs_advanced,pubsub.rs:527)std::sync::Mutex. For Volatile — the ROS 2 default — it declared no liveliness subscriber, heartbeat or detection token, so it was pure overhead plus the fatal lock. TransientLocal keeps it: history replay and miss recovery live there.CallbackDispatcher,pubsub.rs:381)impl Drop for CallbackDispatcher,pubsub.rs:492;DispatchQueue::dequeuechecksclosedbeforepending,pubsub.rs:251-263)drop(subscriber)ran a user callback for every queued sample —backlog × callback_duration, with no ceiling.All four
CallbackDispatcher::spawnsites passdispatch_capacity:pubsub.rs:1417,pubsub.rs:1449,node.rs:684,node.rs:702.DISPATCH_UNBOUNDEDsurvives only as theKeepAllarm ofdispatch_capacityitself. (Counted with a context grep — every call spans four lines, so a same-line match reports zero.)Known defects in this change, disclosed
Drop for CallbackDispatchercallsthread.join()on a thread that is running user code, with the only escape being a self-join from inside that callback. Dropping a subscriber is therefore an unbounded callout to user code, made while the dropping thread holds whatever it holds.pubsub.rs:492-513; reachable synchronously becauseZSubownsSubscriberHandleby value and both variants owndispatcherby valuelet m = Mutex::new(0); callback body takesm; main thread takesm, then drops the subscriber while one sample is in flight →drop(sub)never returns. No timeout, no log, no panic. Onmainthere is noDropimpl inpubsub.rsand no thread, sodrop(sub)always returned. This is #282's own shape relocated to teardown.CallbackDispatcher::spawn's doc says "theffifeature is enabled by no crate, so that arm is not compiled on the PR gate at all (#291)". The premise is true; the conclusion is false.pubsub.rs:401-403, against.github/workflows/test.yml:179-183(FEATURES="ffi,<distro>,rmw-zenoh",cargo build --no-default-features --features "$FEATURES" --lib, all four distro legs)--features ffibuild or mis-scopes #291. The real reason nothing caught the wrong constant is that a wrong constant is neither a compile error nor a lint.SubscriberHandle::Advanced::subscriber's field-order rationale (pubsub.rs:557-559) says the subscriber is undeclared first "before the dispatcher drains and joins" — it does not drain, it discards (breaking change #5). The "Backpressure" section's lead-in (pubsub.rs:329-330) says "The two paths get different answers", and the bullet 15 lines below (:345) says "same bound, and the same expression"; the same paragraph says the queue-modeBoundedQueueis sized "from the same expression" whiledispatch_capacity's own doc (:139) says in bold that they are not.qos_needs_advanced's summary line says "subscriber/publisher" and closes "only pay for it when the QoS actually asks for it" (pubsub.rs:515-526), but no publisher calls it —ZPubBuilder::builddoespub_builder.advanced()unconditionally (pubsub.rs:879). Its only two callers are the subscriber paths (pubsub.rs:1388,node.rs:679).Sequencing::None→ no seqnum, no cache, no liveliness token). The doc promises a decision the code does not make.local_only_shimenqueues a sample only when a hiroz publish is on this thread; a remote sample runs the callback inline on a zenoh RX worker and never enters the queue.pubsub.rs:474-490; correctly stated in-code atpubsub.rs:342-349LocalPublishGuardispub(crate)(pubsub.rs:54), so its own doc's demand — "a fifth publish path added later must do the same" — is unenforceable outsidehiroz, and one out-of-cratesession.putalready exists (hiroz-union/src/plugin/wasm/host/transport.rs:58).session.declare_subscriberhandles, not hirozZSubs, so no dispatcher-backed callback sits on those key expressions, and a callback publishing back does so throughZPub, which is guarded. Enforcement gap, not a live defect.Reliablemaps toCongestionControl::Blockon every history policy (pubsub.rs:866-870), where upstream usesBlockonly forRELIABLE && KEEP_ALLandDropotherwise (detail/rmw_publisher_data.cpp:179-184).putinside a callback stalls that subscriber's drain loop entirely and its queue then silently drop-oldests, with only the escalatingwarn!as a signal. Before this PR the same blocked publish stalled the publishing/RX thread, which was at least visible to the caller.PyZNode::destroy_subscriberresolves by a per-node id with no node identity (hiroz-py/src/node.rs:144next_sub_id: 0per node,:157Vec<(u64, Box<dyn Any>)>,:428-443).owned_id == 0;n1.destroy_subscriber(s2)tears down n1's subscription and returnsOk(()). Destroying an id the node does not own also returnsOk(()).D1 is the one that changes what a reviewer must decide: it is a genuine new hazard on a public API with no disclosure in the Rust docs (
build_with_callback's "# Ownership" section tells callers only that dropping undeclares).hiroz-pyalready patches the two instances it hit —destroy_subscriber(hiroz-py/src/node.rs:434-442) and the newimpl Drop for PyZNode(:161-175), both viapy.allow_threads— which is direct evidence the hazard is real; every Rust caller is left exposed.Evidence
license/claSUCCESSd11d710c(the tip)__typename == "CheckRun"andstatus == "COMPLETED"pubsub.rs:1417→DISPATCH_UNBOUNDED) makes exactly one test fail:transient_local_keep_last_drops_the_oldest_local_samplesdispatch_backpressurepasses 4/4 with the bound in placeorigin/main(ae4f0f8f) — no unintended reversion in the ranged11d710cgit merge-base origin/main HEADkeep_last_drops_the_oldest_local_samples(dispatch_backpressure.rs:215) detects unbounded growth and drop-newest, because it asserts values ([0, 46, 47, 48, 49]) rather than counts. Its determinism is structural, not slept-on: the callback setsparkedbefore waiting on the latch and the publisher spins onparkedwith a deadline, so the drain thread provably cannot pop during the burst.Established by reading the code, not by executing it:
enqueueanddequeuedequeueholds the state mutex continuously from theclosed/pendingcheck intoCondvar::wait, which releases it atomically; one consumer, sonotify_onesuffices;Dropusesnotify_allDropnever holds the queue lock acrossjoin()self.queue.lock().closed = true;is a statement-scoped temporary, dropped at the;thread.thread().id() == current().id()early return (pubsub.rs:499-503);self.thread.take()detaches, so the drain thread exits when the in-flight callback returnsdeclare_subscriberleaks no threaddispatcheris a local binding at all four sites andwait()?returns past it, runningDropSubscriberHandlevariantssubscriberbeforedispatcheratpubsub.rs:543-546and:554-562; Rust drops fields in declaration order. Weaker than the comment implies — zenoh undeclares withwait_callbacks: false— butenqueue's early return onclosedmakes a late sample harmlesslocal_only_shimenqueues; advanced:always_shimenqueues unconditionally; the queue evicts instead of blockingSession::send_push_consumedrops the session state lock beforecallbacks.call;route_datadropsrtablesbeforesend_pushon both branchesstatesrefstatesrefthen the dispatch state; the drain thread releases the dispatch state before running the callback, so a republishing callback takesstatesrefholding nothing. One-directionalenqueueevicts before inserting and returns unconditionally, so neither the publishing thread nor an RX thread can be parked by a slow callbackcatch_unwindatpubsub.rs:439, poison-tolerantlock(); the doc states its own limitation (inert under this workspace'spanic = "abort"profile)KeepLast(usize::MAX)is safe end to endDISPATCH_UNBOUNDED;cache_depth_from_historyforwards it to zenoh-ext, which stores it as aNonZeroUsizeand compares rather than preallocating;BoundedQueue::newcaps itswith_capacityat 1024saturating_add/saturating_mul; at saturation it warns on every drop — degraded logging, not wrong deliverypublish/publish_rawrelease before the put;destroy_subscriberandDrop for PyZNoderelease before dropping owned callback subscribers; queue-modePyZSubscribers carrydispatcher: Nonefeedback_txis an unboundedmpsc::UnboundedSenderandstatus_txawatch::Sender, neither of which blocks;watchkeeps only the newest value, so a depth-drop cannot lose a terminalGoalStatusBreaking changes
Seven. Six follow from moving session-local delivery off the publishing thread. The seventh is API surface.
publish()returning meant the subscriber had run → it does notKeepLast(depth)warn!KeepAllif losslessness is requiredMutex<State>, so callbacks were serialised by construction → they are not nowmainhas no queue and noDropimpl inpubsub.rs; every accepted sample was delivered inline beforepublishreturned, anddrop(sub)joined nothing → the backlog is discarded (as destroying an rclcpp subscription does), butDropnow joins the drain threadfficonsumersSubscriberHandleandCallbackDispatcherare new public items;RawSubscriber::innerchanges fromAdvancedSubscriber<()>toSubscriberHandle(ffi/subscriber.rs:13)innerrmw-zenoh-rsusesbuild_with_notifier(rmw.rs:574), andwait_for_subscriptionreads the graph rather than local delivery (pubsub.rs:945)always_shimenqueues unconditionally. On the plain path only locally published samples pass through the queue; a remote sample runs the callback inline on an RX worker and is neither queued nor dropped. The capacity constant is the same on both paths; which samples pass through it is not (D5).c62f3e26andd11d710cclosed that on the typed and FFI arms respectively.Queue bound versus
rmw_zenoh_cppRead from source at
rmw_zenoh_cpp/src. Upstream's model: the zenoh sample callback does nothing butSubscriptionData::add_new_message, which locks, bounds, enqueues and notifies; user code runs later on the rclcpp executor thread. No user code ever runs on a zenoh delivery thread, on any profile.rmw_zenoh_cppadapted_qos_profile.depth(detail/rmw_subscription_data.cpp:1125-1126)dispatch_capacity:KeepLast(depth).max(1),KeepAll→ unboundedpop_frontbeforeemplace_back(:1140-1143,:1167)pop_frontbeforepush_backatlen >= capacityKEEP_ALL:1125)DISPATCH_UNBOUNDEDTransientLocalexemption:1125):1110, called from:420,:803)adv_sub_opts.history->max_samples = qos_.depth(:379,:728)cache_depth_from_history(pubsub.rs:580-590)is_shutdown_set, undeclare, queue never drained, takes short-circuit (:843-899,:952,:1062)closedset, drain loop exits, backlog discardedtrigger_callback()and the wait-set notify run undermutex_(:1114guard covers:1170-1175)DataHandler::handlecallsnotifier()afterpushreturns, holding nothing (common.rs:44-48)MESSAGE_LOSTfrom arrival sequence-number gaps (:1146-1163); depth drops are debug-log only (:1128-1134)warn!; noMESSAGE_LOSTat allpop_frontat depth cannot create an arrival gap upstream either); hiroz-better on visibility; the absentMESSAGE_LOSTis pre-existing, #292BLOCKonly forRELIABLE && KEEP_ALL, elseDROP(detail/rmw_publisher_data.cpp:179-184)BLOCKfor everyReliableifonly adds options (:371-387,:427)detail/qos.cpp:27,:109-110);dispatch_capacityfloors it at 1 (pubsub.rs:132).dispatch_capacityis called at exactly four sites, all with a locally declared entity's QoS, and every constructor of that value already normalises zero away:hiroz::qos::QosHistory::KeepLastholds aNonZeroUsize,QosHistory::from_depthmaps 0 → 10 (the rmw path,rmw-zenoh-rs/src/qos.rs:241), the FFI conversion mapshistory_depth <= 0→ 10, and the unspecified case defaults toKeepLast(10). Sodepth.max(1)cannot observe a zero and the divergence cannot manifest. hiroz also answers the same question three ways — 10 inQosHistory::from_depth, 42 incache_depth_from_history, 1 indispatch_capacity— of which only the 42 matches upstream. Upstream's in-tree comment claiming a floor of 1 inrmw_create_subscription(:1137-1139) has no matching code:rmw_zenoh.cppdoes not touchdepthat all.One existing test changed.
transient_local_delivery_preserves_orderpublished 500 samples through aKeepLast(10)subscriber and asserted all 500 arrived — a promise no RMW makes. Its stated property is ordering, so it now asserts a strictly increasing subsequence of what was published. Losslessness is still covered on the profile that promises it, bykeep_all_delivers_every_local_sample.Coverage this does not have
qos_needs_advancedto returntrueunconditionally — so every subscriber declares anAdvancedSubscriber, exactly what this PR exists to stop — and re-run the suiteSo change #1, which carries the "pure overhead" argument, is unpinned in both directions. A test asserting
matches!(handle, SubscriberHandle::Plain { .. })for a Volatile subscriber would close it.Everything else that is unpinned, with the one-line revert that should fail and does not:
dequeue(pubsub.rs:251-263) to poppendingbefore checkingclosedenqueueearly-returns onclosed. No test drops a dispatcher with a non-empty queue: the one drop-under-deadline test publishes once and callsawait_deliveries(&seen, 1)first, and all fourdispatch_backpressuretests release the latch and wait for delivery to be stable for 500 ms before their subscriber goes out of scope. No test asserts on teardown duration.destroy_subscriberreleasing the GIL before dropping (hiroz-py/src/node.rs:434-442)swap_removelambda _msg: Noneon freshly-minted topics no publisher writes to, so the drain thread never enters a callback and the join never needs the GIL. The pre-existing basic-pubsub test sleeps 0.3 s after its single publish first.impl Drop for PyZNodereleasing the GIL (hiroz-py/src/node.rs:161-175)publish_rawreleasing the GIL (hiroz-py/src/pubsub.rs:49)py.allow_threadspublish_rawat all; it appears only in the type stub and a benchmark. (publishis pinned, bytest_interpreter_stays_alive_during_reentrant_publish.)LocalPublishGuardonpublish_serialized(pubsub.rs:1133) andpublish_sample(pubsub.rs:1150)async_publishgot a dedicated detector precisely because it was unpinned; the same argument applies here.catch_unwindaround the user callback (pubsub.rs:439)(*handler)(sample)directlyenqueuekeeps accepting into a queue nobody drains, and the subscriber goes silent forever with no log.transient_local_*. On the advanced path a callback dropping its own subscriber always takes the self-join early return; on the plain path a remote sample runs the callback on an RX worker, so the same user code drops from a thread that is not the drain thread — the join actually runs, concurrently with a possible second callback invocation (breaking change #3). I checked that path and it does not deadlock (zenoh holds no session or routing lock across the callout), but nothing pins it and no test exercises it. Volatile is the ROS 2 default.SubscriberHandle's fieldsenqueuereturns early onceclosedis set, and the plain path's inline branch bypasses the queue. Untested, not defective.warn!Correction to a claim this description previously made: "Nothing detects a regression of
d40b5443" is too strong. Inverting eitherif runs_user_codebranch is detected — flippingpubsub.rs:1413leaves a TransientLocal callback subscriber withdispatcher: None, so it runs under zenoh-ext's state mutex andtransient_local_callback_republishing_on_same_topic_does_not_deadlockdeadlocks; flippingpubsub.rs:1438sends a Volatile callback subscriber into the inline queue-mode arm andself_feeding_callback_loop_iterates_without_a_depth_capdies of stack overflow at 2 000 frames. What is genuinely undetected is the narrower direction: makingruns_user_code()also returntruefor the queue variants adds a needless thread and nothing fails.Two test-quality gaps worth fixing but not blocking:
transient_local_delivery_preserves_order(reentrant_publish.rs:688-700) is vacuous at one delivery —received.windows(2).all(..)yields no windows on a 0- or 1-element slice, and the only floor is!is_empty()received.len() >= 2floor restores the claim without re-asserting the losslessness this PR correctly removed.rx.recv_timeout(..).is_err()and then panic with a fixed "deadlocked" message (reentrant_publish.rs:103-108,dispatch_backpressure.rs:87-89)assert!failing inside a scenario closure drops the sender, sorecv_timeoutreturnsDisconnectedimmediately and an ordinary assertion failure is reported as a deadlock. #260 fixed exactly this onmainby matchingRecvTimeoutError::TimeoutandDisconnectedseparately; these two files reintroduce the older form. The test still fails, so no verdict is wrong — only the message.async_publish_delivers_off_the_publishing_threadassertsassert_ne!(callback_thread, publishing_thread)where the thread name is available and is what the comment claimsthread::current().name()and assertingSome("hiroz-sub-drain")asserts the value rather than a difference. The revert it exists to catch is caught either way.queue.rsunit tests pinBoundedQueue, notDispatchQueuezero_capacity_retains_one_sample's doc says a reorder to insert-then-evict makes it fail — true ofBoundedQueue::push, which it constructs, and false ofDispatchQueue::enqueue, which is whatdispatch_capacitysizes.dispatch_capacity's doc cites it as evidence its zero-depth behaviour is harmless; it is not evidence about that type. They are correct tests of the wrong type for the claim they are cited for.Filed rather than fixed here:
ffifeature is built on the PR gate but never linted and never tested, and its re-entrancy detector was deleted in1dcf3736MESSAGE_LOSTChecklist
d11d710c— 26/26 check runs SUCCESS/SKIPPED, 0 failed, 0 pending,license/claSUCCESS. Verified on the current head SHA, filteringCheckRunand requiringstatus == "COMPLETED"before readingconclusion.ae4f0f8f, on a commit that no longer exists in this range. The test count previously quoted here has been removed rather than restated, because it was not re-measured. CI covers the same gates../scripts/check-local.shhas not been re-run since the rebase.build_with_callbackor a bounded/detaching teardown before this ships to Rust callers; D2's sentence is wrong on a verifiable fact and only the doc comment, not this description, survives the merge.