Skip to main content

graphrefly_core/
batch.rs

1//! Wave engine — drain loop, fire selection, emission commit, sink dispatch.
2//!
3//! Ports the wave-engine portion of the handle-protocol prototype
4//! (`~/src/graphrefly-ts/src/__experiments__/handle-core/core.ts`).
5//! Sibling to [`super::node`]; the dispatcher's other concerns
6//! (registration, subscription, pause/resume, terminal cascade,
7//! `set_deps`) live there.
8//!
9//! # Wave engine entry points
10//!
11//! - [`Core::run_wave`] — wave entry. Claims `in_tick` under the state lock,
12//!   runs `op` lock-released, then drains all transitive fn-fires and
13//!   flushes per-subscriber notifications. Each fn-fire iteration drops
14//!   the state lock around `BindingBoundary::invoke_fn` so user fn callbacks
15//!   can re-enter Core safely.
16//! - [`Core::drain_and_flush`] — drain phase + flush phase. Acquires/drops
17//!   the state lock per iteration around `invoke_fn`.
18//! - [`Core::commit_emission`] — equals-substitution + DIRTY/DATA/RESOLVED
19//!   queueing + child propagation. `&self`-only; bracket-fires
20//!   `BindingBoundary::custom_equals` lock-released.
21//! - [`Core::queue_notify`] — per-subscriber message queueing with
22//!   pause-buffer routing. Snapshots the subscriber list at first-touch-
23//!   per-wave so late subscribers (installed mid-wave between drain
24//!   iterations) don't receive duplicate deliveries from messages already
25//!   queued before they subscribed.
26//! - [`Core::deliver_data_to_consumer`] — single-edge propagation; marks
27//!   the consumer for fn-fire if its tracked-deps set is satisfied.
28//!   Called from `commit_emission`, plus `activate_derived` and
29//!   `set_deps` in [`super::node`].
30//!
31//! # Re-entrance discipline (Slice A close — M1 fully lock-released)
32//!
33//! - **Wave-end sink fires** drop the state lock first (Slice A-bigger
34//!   discipline).
35//! - **`BindingBoundary::invoke_fn`** in `fire_fn` fires lock-released —
36//!   user fn callbacks may re-enter `Core::emit` / `pause` / `resume` /
37//!   `invalidate` / `complete` / `error` / `teardown` and run a nested
38//!   wave (the existing `in_tick` re-entrance gate composes
39//!   transparently).
40//! - **`BindingBoundary::custom_equals`** in `commit_emission`'s equals
41//!   check fires lock-released.
42//! - **Subscribe-time handshake** is the one remaining lock-held callback.
43//!   It now fires per-tier (`[Start]`, `[Data(v)]`, `[Complete|Error]`,
44//!   `[Teardown]`) as separate sink calls, matching the canonical R1.3.5.a
45//!   tier-split. Re-entrance from a handshake sink callback panics with
46//!   the [`reentrance_guard`] diagnostic.
47
48use std::cell::{Cell, RefCell};
49use std::collections::HashMap;
50use std::sync::Arc;
51
52use ahash::AHashSet;
53use indexmap::map::Entry;
54use indexmap::IndexMap;
55
56use smallvec::SmallVec;
57
58use crate::boundary::{DepBatch, FnEmission, FnResult};
59use crate::handle::{FnId, HandleId, NodeId, NO_HANDLE};
60use crate::message::Message;
61use crate::node::{Core, CoreState, EqualsMode, OperatorOp, Sink, TerminalKind};
62
63// Slice G (R1.3.2.d / R1.3.3.a) per-thread tier-3-emit tracker.
64//
65// **Wave scope = the owner thread (S4, D246/D248/D249).** `Core` is
66// single-owner `!Send + !Sync`: every emit in a wave runs on the one
67// owner thread, and a wave is one uninterrupted owner-side drain
68// bounded above by the outermost `BatchGuard` drop. A per-thread
69// `AHashSet<NodeId>` is therefore the natural placement for "has node
70// X already emitted a tier-3 message in this wave?" — its lifetime
71// matches the wave's, with no cross-thread or cross-wave contamination
72// (there is no other thread driving this Core; the deleted
73// `wave_owner` `ReentrantMutex` / cross-thread-BLOCK model is gone
74// with S2c's §7 machinery).
75//
76// **History:** placed per-partition on `SubgraphLockBox::state` (Q3
77// v1), moved to a per-thread thread-local by the D1 patch
78// (2026-05-09) to survive mid-wave cross-thread `set_deps` partition
79// splits — a hazard that only existed under the now-deleted
80// shared-Core cross-thread model. Post-S4 the thread-local placement
81// is simply the owner thread's wave-scoped set.
82//
83// **Lifecycle:** populated by `Core::commit_emission` /
84// `Core::commit_emission_verbatim`; cleared at the OUTERMOST
85// `BatchGuard` drop on the owner thread (both success and
86// panic-discard paths). Re-entrant nested waves on the same Core+
87// thread share the set — inner-wave emits add to the same set; the
88// outermost drop is the canonical clear point.
89thread_local! {
90    static TIER3_EMITTED_THIS_WAVE: RefCell<AHashSet<NodeId>> = RefCell::new(AHashSet::new());
91}
92
93// Q-beyond Sub-slice 1 (D108 / 2026-05-09): per-thread wave-scoped state.
94//
95// **Design rationale (bench-driven, see `benches/lock_strategy.rs`):**
96// - S1 showed parking_lot Mutex same-thread re-acquire is ~14 ns/op,
97//   identical to thread_local borrow_mut. The "mutex hop is slow" intuition
98//   is wrong UNCONTENDED.
99// - S3 showed shared mutex on disjoint cross-thread keys is 2.7× slower
100//   than per-partition mutex / thread_local (35.9 vs 13.0 ns/op) — pure
101//   cache-line bouncing on the lock state itself.
102// - Conclusion: the cost of the prior `Core::cross_partition` mutex was
103//   dominated by cache-line bouncing across cores, NOT by single-thread
104//   mutex acquire overhead. Moving the four wave-scoped fields to a
105//   per-thread thread_local eliminates the bounce point entirely.
106//
107// **Wave scope = the owner thread (S4, D246/D248/D249):** `Core` is
108// single-owner `!Send + !Sync` — exactly one owner thread drives a
109// given `Core`, and a wave is **one uninterrupted owner-side drain**
110// (the deleted cross-thread `wave_owner` `ReentrantMutex` / "cross-thread
111// emits BLOCK" model is gone with S2c's §7 machinery). There is no
112// cross-thread interleave to defend against; the only cross-`Core`
113// concurrency is host-native via *independent* per-worker Cores
114// (actor model), each with its own `WAVE_STATE`.
115//
116// **Lifecycle:** populated by `Core::commit_emission` /
117// `Core::queue_notify` / etc.; mostly drained mid-wave by the auto-resolve
118// sweep + cache snapshot commit/restore. Outermost `BatchGuard::drop`
119// releases any retained handles still in `wave_cache_snapshots` /
120// `deferred_handle_releases`. Defensive wave-start clear at outermost
121// owning BatchGuard entry guards against cargo's thread-reuse propagating
122// stale entries from a prior panicked-mid-wave test.
123thread_local! {
124    static WAVE_STATE: RefCell<WaveState> = RefCell::new(WaveState::new());
125}
126
127// Wave-ownership flag for the at-most-one Core this OS thread may own.
128// Stores the active `Core::generation` (nonzero ⇒ owning a wave on that
129// Core; `0` ⇒ no active Core). Membership-of-generation means "this
130// thread is currently inside an OWNING wave on that Core" — i.e. the
131// outermost `BatchGuard` whose drop must run the drain. Replaces the
132// former Core-global `CoreState::in_tick` bool.
133//
134// **Why a single-generation `Cell<u64>` (D252, S5, 2026-05-19).** Post-
135// D247/D248 `Core` is single-owner `!Send + !Sync`; one Core per OS
136// thread is the model. The earlier `AHashSet<u64>` keyed by
137// `Core::generation` defended against an owner thread holding a wave on
138// Core-A and *also* entering a wave on Core-B from a `DeferQueue`
139// closure (/qa F1, the cross-Core owner-side nesting case D047 fixed).
140// Under D248 single-owner that defense is theoretical — no in-tree call
141// path produces it (would require an owner-side `DeferFn` to capture &
142// drive a *second* `&Core`; the `Send` half of the seam is closed under
143// `Core: !Send`). Per D252 (user-locked 2026-05-19), the hashing +
144// allocation cost is replaced by a single `Cell<u64>` (1 word, no
145// alloc) and the "one Core per OS thread" model is locked in as a
146// **hard invariant** — `BatchGuard::claim_in_tick` panics fail-loud if
147// it observes a nonzero generation that doesn't match `self.generation`,
148// structurally rejecting cross-Core same-thread nesting rather than
149// relying on convention. Nested same-Core re-entry (/qa EC#3, LIVE) is
150// preserved: the matching `claim` returns `false` (slot already holds
151// our generation) so the nested guard's drop no-ops and the outer wave
152// drains. `0` is reserved as the sentinel and `Core::generation` is
153// `NonZeroU64` (the existing process-monotonic counter starts at 1) so
154// the sentinel cannot collide with a live Core.
155//
156// **No lock required.** `Cell` is `!Sync` and only the one owner thread
157// touches it — single-owner `!Sync` Core ⇒ no cross-thread reader.
158//
159// Stale slot: the owning `BatchGuard::drop` clears the cell on every
160// exit path — normal return, the closure-body-panic branch, AND the
161// drain-phase-panic `catch_unwind` arm (before `resume_unwind`). So
162// a slot can only be left stuck if `Drop` itself never runs:
163// `std::mem::forget(guard)` or a process abort without unwinding — both
164// out of contract (`BatchGuard` is `#[must_use]` + `!Send`). A stale
165// nonzero slot would trip the D252 panic-on-mismatch on the NEXT Core's
166// claim on this thread — surfaced loudly, not silently masked.
167//
168// History: this flag lived briefly per-thread (Q-beyond sub-slice 3),
169// was reverted to Core-global (/qa F1+F2), keyed per-(Core, thread) for
170// the deleted disjoint-cross-thread model (D047, 2026-05-15), and at S4
171// (D246/D248/D249) the disjoint-partition constraint was retired with
172// the §7 cross-thread machinery. D252/S5 (2026-05-19) collapses the
173// `AHashSet<u64>` to `Cell<u64>` and locks "one Core per OS thread" as
174// a hard invariant — reversing D047's per-(Core, thread) keying since
175// the cross-Core owner-side nesting case it defended is no in-tree path
176// under single-owner Core. See `docs/rust-port-decisions.md` D252 +
177// D047/D246 and `docs/migration-status.md` § "D246 S5".
178thread_local! {
179    static IN_TICK_OWNED: Cell<u64> = const { Cell::new(0) };
180}
181
182/// Wave-scoped state previously held under [`Core::cross_partition`]'s
183/// `parking_lot::Mutex<CrossPartitionState>`. Now per-thread (Q-beyond
184/// Sub-slice 1, 2026-05-09; Sub-slice 2 added `pending_fires` +
185/// `pending_notify`, 2026-05-09; Sub-slice 3 added `currently_firing`,
186/// `in_tick`, `deferred_flush_jobs`, `deferred_cleanup_hooks`,
187/// `pending_wipes`, `invalidate_hooks_fired_this_wave`, 2026-05-09).
188///
189/// All fields are populated and drained within one wave on the one
190/// owner thread. Cross-thread access is structurally impossible —
191/// `Core` is single-owner `!Send + !Sync` (S4/D248); there is no
192/// other thread driving this Core.
193///
194/// **Refcount discipline (load-bearing):** `wave_cache_snapshots`,
195/// `deferred_handle_releases`, and `pending_notify` hold binding-side
196/// handle retains. They MUST be drained (and released through
197/// `Core::binding.release_handle`) by the outermost `BatchGuard::drop`
198/// on success and panic paths. `pending_notify` holds one retain per
199/// payload-bearing message (one per `Message::payload_handle()`); the
200/// retains are taken in `Core::queue_notify` and balanced either by
201/// `flush_notifications` (success path: pushed into
202/// `deferred_handle_releases`) or directly in the panic-discard path of
203/// `BatchGuard::drop` (taken from `pending_notify` and released).
204///
205/// The thread_local has no `Drop` hook with access to a binding — a
206/// panic that bypasses `BatchGuard::drop` (e.g. panic OUTSIDE any batch)
207/// would leak retains until the thread exits OR the next outermost
208/// wave-start clear runs (which for safety we don't fire — clearing
209/// without releasing would double-leak by losing the retain). The
210/// defensive wave-start clear in `BatchGuard::begin_batch_with_guards`
211/// clears `pending_auto_resolve` + `pending_pause_overflow` +
212/// `pending_fires` (no retains) + `currently_firing` +
213/// `invalidate_hooks_fired_this_wave` (also no retains) but NOT the
214/// retain-holding fields — those must be empty by construction at
215/// outermost wave start (a prior wave's panic-discard path drained them,
216/// or a prior wave's success path drained them).
217pub(crate) struct WaveState {
218    /// Payload-handle releases owed for messages that landed in
219    /// `pending_notify` during this wave (one per `payload_handle()`).
220    /// `BatchGuard::drop` releases these after sinks fire and the lock
221    /// is dropped, balancing the retain done in `queue_notify`.
222    pub(crate) deferred_handle_releases: Vec<HandleId>,
223    /// Pre-wave cache snapshots used to restore state if the wave aborts
224    /// mid-flight (e.g., a `Core::batch` closure panics). Each entry is
225    /// `(node_id → old_cache_handle)` — the handle the node held BEFORE
226    /// the wave started writing to it. The snapshotted handle holds a
227    /// retain (taken when the snapshot was inserted) so it stays alive
228    /// for restoration. On wave success, snapshots are drained and their
229    /// retains released. On wave abort, each cache slot is restored from
230    /// the snapshot and the original retain transfers to the cache slot.
231    pub(crate) wave_cache_snapshots: HashMap<NodeId, HandleId>,
232    /// Nodes that need an auto-Resolved at wave end if they don't receive
233    /// a tier-3+ message from their own commit_emission. Populated by
234    /// the RESOLVED child propagation in `commit_emission`. Drained by
235    /// the auto-resolve sweep in `drain_and_flush`.
236    pub(crate) pending_auto_resolve: AHashSet<NodeId>,
237    /// R1.3.8.c pause-overflow ERROR synthesis queue. Recorded by
238    /// [`Core::queue_notify`] when the pause buffer first overflows;
239    /// drained at wave-end after the lock-released call to
240    /// `BindingBoundary::synthesize_pause_overflow_error`.
241    pub(crate) pending_pause_overflow: Vec<crate::node::PendingPauseOverflow>,
242    /// Nodes whose fn we owe a fire to — drained by [`Core::run_wave`].
243    ///
244    /// Q-beyond Sub-slice 2 (D108, 2026-05-09): moved from
245    /// `CoreState::pending_fires` to per-thread `WaveState`. Wave-scoped
246    /// — populated by `deliver_data_to_consumer`, `terminate_node`'s
247    /// child-cascade `QueueFire` branch, `activate_derived`'s producer
248    /// queueing, `resume`'s pending-wave consolidation, and operator
249    /// re-arm paths; drained by `pick_next_fire` / `fire_fn` /
250    /// `fire_regular` / `fire_operator` (each removes the firing node
251    /// before invoking).
252    pub(crate) pending_fires: AHashSet<NodeId>,
253    /// Per-node outgoing message buffer; flushed at wave end. Insertion-
254    /// ordered so flush order is deterministic — load-bearing for
255    /// R1.3.9.d meta-TEARDOWN ordering: when a parent and its meta
256    /// companion both have queued messages in the same wave, the meta
257    /// (queued first via `teardown_inner`'s recursion order) flushes
258    /// first.
259    ///
260    /// Each entry carries the per-wave subscriber snapshot taken at first
261    /// touch (Slice A close, M1: lock-released drain). Late subscribers
262    /// installed mid-wave between fn-fire iterations don't appear in
263    /// already-snapshotted entries; this is the load-bearing fix that
264    /// prevents duplicate-Data delivery when a handshake delivers the
265    /// post-commit cache and the wave's flush would otherwise also fire
266    /// to the same sink.
267    ///
268    /// Q-beyond Sub-slice 2 (D108, 2026-05-09): moved from
269    /// `CoreState::pending_notify` to per-thread `WaveState`. The map
270    /// holds a payload-handle retain per payload-bearing message
271    /// (`Message::payload_handle()`); these MUST be released by the
272    /// outermost `BatchGuard::drop` (success path: through
273    /// `flush_notifications` → `deferred_handle_releases`; panic path:
274    /// directly in `BatchGuard::drop`'s panic branch).
275    pub(crate) pending_notify: IndexMap<NodeId, PendingPerNode>,
276    /// D217-AMEND-2 (2026-05-16): persistent spare for `pending_notify`,
277    /// ping-ponged with it at wave end so a fresh `IndexMap::default()`
278    /// (a new `ahash::RandomState` via `gen_hasher_seed`/`from_keys`
279    /// PLUS RawVec realloc churn on the next wave's `queue_notify`) is
280    /// NEVER constructed after thread init. The empirical attribution
281    /// (`examples/profile_st_emit.rs` + macOS `sample`) put the old
282    /// per-wave `mem::take(&mut pending_notify)` at ~1250 of ~4767
283    /// hot-path samples — the dominant §7 floor tax (D217 lever-1
284    /// "slab store" falsified; the node store is minor). Holds NO
285    /// retains between waves: it is always empty (cleared, capacity +
286    /// hasher retained) outside `flush_notifications`.
287    pub(crate) pending_notify_recycle: IndexMap<NodeId, PendingPerNode>,
288    // Q-beyond Sub-slice 3 (D108, 2026-05-09) moved `in_tick` and
289    // `currently_firing` from `CoreState` to per-thread `WaveState`;
290    // /qa F1+F2 (2026-05-10) reverted both to `CoreState`; the in_tick
291    // placement was finalized 2026-05-15 (D047) and then collapsed by
292    // D252 (S5, 2026-05-19) — see below. The two fields have *different*
293    // scope requirements:
294    //
295    // - **`in_tick` — one-Core-per-OS-thread `Cell<u64>` (D252).** Pure
296    //   thread-local once broke cross-Core isolation (Core-A's flag
297    //   leaked to Core-B on the same OS thread, /qa F1); pure Core-
298    //   global broke the now-deleted disjoint-partition cross-thread
299    //   drain. The intermediate D047 `AHashSet<u64>` keyed by
300    //   `Core::generation` defended both. Under post-D248 single-owner
301    //   Core the cross-Core owner-side nesting case has no in-tree
302    //   consumer (would require an owner-side `DeferFn` to drive a
303    //   *second* `&Core`, structurally absent), so D252 collapses the
304    //   set to a single `Cell<u64>` slot per OS thread and panics
305    //   fail-loud on cross-Core nesting. Same-Core nested re-entry
306    //   (/qa EC#3) is preserved by the matching-generation branch in
307    //   `BatchGuard::claim_in_tick`. NOT a `CoreState` field.
308    //
309    // - **`currently_firing` — Core-global (stays on `CoreState`).**
310    //   Per-thread placement silently bypassed the cross-thread P13
311    //   partition-migration check in `Core::set_deps`: thread B's set_deps
312    //   must observe thread A's firing pushes. Per-Core (cross-thread
313    //   visible) placement restores the D091 safety check (/qa F2).
314    //
315    // The other 11 wave-scoped fields stay per-thread because they're
316    // accessed only by the one owner thread (single-owner `!Send` Core,
317    // S4/D248 — no cross-thread emitter exists).
318    /// Slice E2 (R1.3.9.b strict per D057): per-wave-per-node dedup
319    /// for `OnInvalidate` cleanup hook firing. A node already in this
320    /// set this wave has already had its `OnInvalidate` queued into
321    /// `deferred_cleanup_hooks` and MUST NOT queue again, even if
322    /// `invalidate_inner` re-encounters it.
323    ///
324    /// Q-beyond Sub-slice 3 (D108, 2026-05-09): moved from
325    /// `CoreState::invalidate_hooks_fired_this_wave` to per-thread
326    /// `WaveState`. Wave-scoped — populated by `invalidate_inner` and
327    /// cleared by `WaveState::clear_wave_state`.
328    pub(crate) invalidate_hooks_fired_this_wave: AHashSet<NodeId>,
329    /// Deferred sink-fire jobs collected by `flush_notifications`.
330    /// `flush_notifications` populates this from `pending_notify`;
331    /// `Core::drain_deferred` takes it and `Core::fire_deferred` fires
332    /// each entry lock-released. Each tuple is
333    /// `(sinks_for_one_node_one_phase, phase_messages)`. Empty between
334    /// waves.
335    ///
336    /// Q-beyond Sub-slice 3 (D108, 2026-05-09): moved from
337    /// `CoreState::deferred_flush_jobs` to per-thread `WaveState`. No
338    /// retains held — the `Vec<Sink>` clones own Arcs that drop
339    /// naturally; the `Vec<Message>` payload retains were already moved
340    /// into `deferred_handle_releases` by `flush_notifications`.
341    pub(crate) deferred_flush_jobs: DeferredJobs,
342    /// Slice E2 (per D060/D061): lock-released drain queue for
343    /// `OnInvalidate` cleanup hooks. Populated by `Core::invalidate_inner`
344    /// when a node's cache transitions `!= NO_HANDLE → NO_HANDLE`;
345    /// drained after the lock drops at wave boundary by
346    /// `Core::fire_deferred` (each call wrapped in `catch_unwind` per
347    /// D060). Panic-discarded silently per D061.
348    ///
349    /// Q-beyond Sub-slice 3 (D108, 2026-05-09): moved from
350    /// `CoreState::deferred_cleanup_hooks` to per-thread `WaveState`.
351    pub(crate) deferred_cleanup_hooks: Vec<(NodeId, crate::boundary::CleanupTrigger)>,
352    /// Slice E2 /qa Q2(b) (D069): lock-released drain queue for
353    /// `BindingBoundary::wipe_ctx` calls fired eagerly from
354    /// `Core::terminate_node` when a resubscribable node terminates with
355    /// no live subscribers. Drained alongside `deferred_cleanup_hooks`
356    /// at wave boundary; same `catch_unwind` discipline. Panic-discarded
357    /// silently.
358    ///
359    /// Q-beyond Sub-slice 3 (D108, 2026-05-09): moved from
360    /// `CoreState::pending_wipes` to per-thread `WaveState`.
361    pub(crate) pending_wipes: Vec<NodeId>,
362}
363
364impl WaveState {
365    fn new() -> Self {
366        Self {
367            deferred_handle_releases: Vec::new(),
368            wave_cache_snapshots: HashMap::new(),
369            pending_auto_resolve: AHashSet::new(),
370            pending_pause_overflow: Vec::new(),
371            pending_fires: AHashSet::new(),
372            pending_notify: IndexMap::new(),
373            // D217-AMEND-2: one `IndexMap::default()` for the thread's
374            // life — its ahash seed + capacity are recycled forever.
375            pending_notify_recycle: IndexMap::new(),
376            invalidate_hooks_fired_this_wave: AHashSet::new(),
377            deferred_flush_jobs: Vec::new(),
378            deferred_cleanup_hooks: Vec::new(),
379            pending_wipes: Vec::new(),
380        }
381    }
382
383    /// Wave-end clear of the non-retain-holding fields. Called from
384    /// [`Core::drain_and_flush`]'s wave-end path. Fields holding retains
385    /// (`wave_cache_snapshots`, `deferred_handle_releases`,
386    /// `pending_notify`) are NOT cleared here — they follow the
387    /// success/panic paths' explicit drain discipline in
388    /// `BatchGuard::drop`.
389    pub(crate) fn clear_wave_state(&mut self) {
390        self.pending_auto_resolve.clear();
391        // pending_pause_overflow is normally drained by drain_and_flush
392        // via the synthesis loop. If a wave is panic-discarded BEFORE
393        // synthesis runs, BatchGuard::drop's panic path also clears it
394        // explicitly. Pre-wave defensive clear in
395        // `begin_batch_with_guards` makes this idempotent.
396        self.pending_pause_overflow.clear();
397        // Sub-slice 2: pending_fires is intentionally NOT cleared
398        // here. Two reasons:
399        //   1. Wave-success drain empties it by construction: every
400        //      `pick_next_fire` selection is removed by
401        //      `fire_regular` / `fire_operator` before invocation,
402        //      and `drain_and_flush` only exits when the set is empty.
403        //   2. The `Core::resume` default-mode consolidated-fire
404        //      pattern stages an entry OUTSIDE any in-tick wave and
405        //      then enters a new wave to drain it; clearing here
406        //      would erase that pre-staged entry. The panic-discard
407        //      path in `BatchGuard::drop` clears it explicitly.
408
409        // /qa F2 reverted (2026-05-10): currently_firing moved BACK to
410        // CoreState::currently_firing — defensive clear there.
411        // Slice E2 (D057): per-wave-per-node OnInvalidate dedup is
412        // wave-scoped — cleared so the next wave can fire cleanups
413        // again.
414        self.invalidate_hooks_fired_this_wave.clear();
415        // `deferred_flush_jobs`, `deferred_cleanup_hooks`, and
416        // `pending_wipes` are intentionally NOT cleared here. They
417        // follow the same discipline as `deferred_handle_releases` /
418        // `pending_notify`:
419        //   - SUCCESS path (`BatchGuard::drop` non-panic): drained by
420        //     `Core::drain_deferred` AFTER `clear_wave_state` runs,
421        //     then fired lock-released by `Core::fire_deferred`.
422        //   - PANIC-DISCARD path (`BatchGuard::drop` panic): explicitly
423        //     `std::mem::take`-and-dropped AFTER `clear_wave_state`
424        //     runs (silently per D061 / D069).
425        // Clearing here would race the success path: queued sink fires
426        // / cleanup hooks / wipes would be erased BEFORE
427        // `drain_deferred` could take them.
428    }
429}
430
431/// Run a closure with mutable access to this thread's [`WaveState`].
432///
433/// Convention: prefer this helper over inline `WAVE_STATE.with(...)`
434/// for sites that touch ONE field. For sites that interleave state lock
435/// access with wave-state mutation, inline `WAVE_STATE.with(...)` keeps
436/// the lock-acquire / wave-state-borrow scopes visible (mirrors the
437/// pre-Q-beyond `let mut s = self.lock_state(); let mut cps = self.lock_cross_partition();`
438/// pattern).
439///
440/// **Re-entrance:** the closure MUST NOT re-enter Core in a way that
441/// would call back into `with_wave_state` — `RefCell::borrow_mut` panics
442/// on nested borrow. The same discipline that the prior
443/// `parking_lot::Mutex<CrossPartitionState>` enforced (no re-entry
444/// holding cross_partition) carries over.
445pub(crate) fn with_wave_state<R>(f: impl FnOnce(&mut WaveState) -> R) -> R {
446    WAVE_STATE.with(|cell| f(&mut cell.borrow_mut()))
447}
448
449/// Outermost-wave defensive clear of [`WaveState`]'s non-retain-holding
450/// fields. Called from [`BatchGuard::begin_batch_with_guards`] on
451/// outermost owning entry. Mirrors the pre-existing tier3 defensive
452/// clear (D1 patch, 2026-05-09) — guards against cargo's thread-reuse
453/// propagating stale entries from a prior panicked-mid-wave test.
454///
455/// The retain-holding fields (`wave_cache_snapshots` /
456/// `deferred_handle_releases`) MUST already be empty by construction at
457/// outermost wave entry — outermost `BatchGuard::drop` always drains
458/// them on both success and panic paths. If they're non-empty here it
459/// indicates a prior wave bypassed `BatchGuard::drop`; in that case
460/// the next BatchGuard's outermost drop will eventually drain them.
461fn wave_state_clear_outermost() {
462    with_wave_state(|ws| {
463        // /qa F4 (2026-05-10): debug_assert that retain-holding fields
464        // are empty at outermost wave start. The invariant claim is
465        // "outermost BatchGuard::drop drains them on both success and
466        // panic paths, so they're empty before the next wave starts."
467        // If a panic path EVER bypasses the drain (today: not reachable
468        // because BatchGuard::drop is robust against panicking sinks via
469        // catch_unwind), this assert catches it in tests immediately
470        // rather than letting stale entries leak into the next wave's
471        // drain (which would release Core-A's HandleIds via Core-B's
472        // binding under cross-Core same-thread sequential use).
473        debug_assert!(
474            ws.wave_cache_snapshots.is_empty(),
475            "wave_state_clear_outermost: wave_cache_snapshots non-empty at \
476             outermost wave start ({} entries) — prior BatchGuard::drop \
477             bypassed the drain (would leak retains into next wave's \
478             binding). See /qa F4 (2026-05-10).",
479            ws.wave_cache_snapshots.len()
480        );
481        debug_assert!(
482            ws.deferred_handle_releases.is_empty(),
483            "wave_state_clear_outermost: deferred_handle_releases non-empty \
484             at outermost wave start ({} entries) — prior BatchGuard::drop \
485             bypassed the drain. See /qa F4 (2026-05-10).",
486            ws.deferred_handle_releases.len()
487        );
488        debug_assert!(
489            ws.pending_notify.is_empty(),
490            "wave_state_clear_outermost: pending_notify non-empty at \
491             outermost wave start ({} entries) — prior BatchGuard::drop \
492             bypassed the drain. See /qa F4 (2026-05-10).",
493            ws.pending_notify.len()
494        );
495        // D217-AMEND-2 / QA: enforce the invariant the field's own doc
496        // claims ("always empty outside `flush_notifications`"). The
497        // recycle slot is cleared at the end of every `flush_notifications`
498        // and drained on the panic-discard path (`discard_wave_cleanup`);
499        // a non-empty slot here means a panic bypassed both — surface it
500        // loudly in tests rather than silently injecting a prior wave's
501        // stale entries into the next wave's `mem::swap`.
502        debug_assert!(
503            ws.pending_notify_recycle.is_empty(),
504            "wave_state_clear_outermost: pending_notify_recycle non-empty \
505             at outermost wave start ({} entries) — a panic bypassed both \
506             flush_notifications' clear AND discard_wave_cleanup's drain. \
507             See D217-AMEND-2 / QA (2026-05-16).",
508            ws.pending_notify_recycle.len()
509        );
510        ws.pending_auto_resolve.clear();
511        ws.pending_pause_overflow.clear();
512        // Sub-slice 2: pending_fires is intentionally NOT cleared here.
513        // Pre-Sub-slice-2 it lived on CoreState and survived between
514        // waves; load-bearing for `Core::resume`'s default-mode
515        // consolidated-fire pattern, which inserts into pending_fires
516        // OUTSIDE any in-tick wave (Phase 1, lock-held but `in_tick`
517        // false at that moment) and then calls `run_wave_for(node_id)`
518        // — `run_wave_for` enters a NEW outermost wave whose drain must
519        // pick up that pre-staged pending_fires entry. Clearing here
520        // would erase it.
521        //
522        // pending_fires holds no retains, so a stale entry from a
523        // prior panicked-mid-wave test that bypassed BatchGuard::drop
524        // would leak as a spurious fire on the next wave on the same
525        // thread (no refcount damage). The panic-discard path in
526        // BatchGuard::drop and the wave-success drain together
527        // guarantee pending_fires is empty by wave end; relying on
528        // that invariant matches the pre-refactor lifecycle.
529        //
530        // Intentionally NOT clearing wave_cache_snapshots /
531        // deferred_handle_releases / pending_notify here — those hold
532        // retains and need a binding to release. Documented invariant:
533        // they're empty by outermost wave start.
534
535        // Sub-slice 3 (2026-05-09; /qa F2 partially reverted 2026-05-10):
536        // defensively clear the OnInvalidate dedup set on outermost-wave
537        // entry. Holds no retains; a stale entry from a prior
538        // panicked-mid-wave test that bypassed BatchGuard::drop would
539        // only suppress the OnInvalidate cleanup hook for that node on
540        // the next wave (no refcount damage). Clearing matches the
541        // tier3 defensive-clear precedent.
542        //
543        // `currently_firing` was reverted to CoreState (per /qa F2 — the
544        // per-thread placement silently bypassed the cross-thread P13
545        // partition-migration check); its defensive clear lives in
546        // `CoreState::clear_wave_state` (which BatchGuard::drop runs
547        // wave-end on both success and panic paths).
548        ws.invalidate_hooks_fired_this_wave.clear();
549        // Intentionally NOT clearing deferred_flush_jobs /
550        // deferred_cleanup_hooks / pending_wipes here — by invariant
551        // they're empty at outermost wave start (drained on success
552        // by drain_deferred → fire_deferred; drained on panic by
553        // BatchGuard::drop's panic branch). Pre-clearing would race a
554        // hypothetical wave that staged into them OUTSIDE in_tick
555        // (none does today, but matching the deferred_handle_releases
556        // / pending_notify discipline keeps the invariant uniform).
557    });
558}
559
560// §7 (D208–D211): the per-thread `PARTITION_CACHE` is DELETED. It existed
561// to amortize the union-find `compute_touched_partitions` BFS + registry
562// epoch round-trips across repeated same-seed emits. With static
563// user-declared scheduling groups there is no epoch and the
564// touched-group walk resolves group `Arc`s under a single uncontended
565// `group_locks` lock (and is entirely skipped for the all-`None` floor),
566// so the cache (and its ABA-avoidance generation keying) is unnecessary.
567
568/// Has `node` emitted a tier-3 (DATA / RESOLVED) message in the current
569/// wave on this thread? See [`TIER3_EMITTED_THIS_WAVE`] for the per-thread
570/// wave-scope rationale.
571fn tier3_check(node: NodeId) -> bool {
572    TIER3_EMITTED_THIS_WAVE.with(|s| s.borrow().contains(&node))
573}
574
575/// Mark `node` as having emitted a tier-3 message in the current wave on
576/// this thread. Idempotent. See [`TIER3_EMITTED_THIS_WAVE`].
577fn tier3_mark(node: NodeId) {
578    TIER3_EMITTED_THIS_WAVE.with(|s| {
579        s.borrow_mut().insert(node);
580    });
581}
582
583/// Wave-end clear of the per-thread tier3 tracker. Called from the
584/// OUTERMOST [`BatchGuard::drop`] on this thread (both success and
585/// panic-discard paths). Inner non-owning BatchGuard drops MUST NOT
586/// invoke this — the outer wave is still in flight and inner-wave marks
587/// are part of the outer wave's Slice G coalescing state.
588fn tier3_clear() {
589    TIER3_EMITTED_THIS_WAVE.with(|s| {
590        s.borrow_mut().clear();
591    });
592}
593
594/// Deferred sink-fire jobs collected during `flush_notifications`. Each
595/// entry pairs a snapshot of the sink Arcs to fire with the messages to
596/// deliver to them — one entry per (node × phase) cell with non-empty
597/// content. Drained from `CoreState` and fired lock-released.
598pub(crate) type DeferredJobs = Vec<(Vec<Sink>, Vec<Message>)>;
599
600/// Lock-released drain payload of the wave's BatchGuard:
601/// `(sink_jobs, handle_releases, OnInvalidate cleanup hooks, pending wipe_ctx fires)`.
602/// Returned by [`Core::drain_deferred`], consumed by [`Core::fire_deferred`].
603/// Sliced into a type alias to satisfy `clippy::type_complexity`.
604pub(crate) type WaveDeferred = (
605    DeferredJobs,
606    Vec<HandleId>,
607    Vec<(crate::handle::NodeId, crate::boundary::CleanupTrigger)>,
608    Vec<crate::handle::NodeId>,
609);
610
611/// One subscriber-snapshot epoch within a node's wave-end notification
612/// queue. A `PendingBatch` is opened the first time `queue_notify` runs
613/// for the node in a wave, and a fresh batch is opened whenever the node's
614/// `subscribers_revision` advances mid-wave (a new sink subscribes, an
615/// existing sink unsubscribes, or a handshake-time panic evicts an
616/// orphaned sink). All messages within one batch flush to the same sink
617/// list — the snapshot taken when the batch opened, frozen against
618/// subsequent revision bumps.
619pub(crate) struct PendingBatch {
620    /// `NodeRecord::subscribers_revision` value at the moment this batch
621    /// opened. Used by `queue_notify` to decide append-to-last-batch vs
622    /// open-fresh-batch on every push.
623    pub(crate) snapshot_revision: u64,
624    /// Subscriber snapshot frozen at batch-open time. SmallVec<[_; 1]>
625    /// inlines the common single-subscriber case (avoids heap alloc for
626    /// the dominant 1-sink-per-node pattern in most reactive graphs).
627    pub(crate) sinks: SmallVec<[Sink; 1]>,
628    /// Messages queued to this batch. SmallVec<[_; 3]> inlines the
629    /// common per-node-per-wave message set (DIRTY + DATA + optional
630    /// RESOLVED) without heap allocation.
631    pub(crate) messages: SmallVec<[Message; 3]>,
632}
633
634/// Per-node wave-end notification queue, structured as one or more
635/// subscriber-snapshot epochs (`batches`). The common case (no
636/// mid-wave subscribe / unsubscribe at this node) keeps a single
637/// inline batch — `SmallVec<[_; 1]>` keeps that allocation-free.
638///
639/// **Slice X4 / D2 (2026-05-08):** the prior shape was a single
640/// `(sinks, messages)` pair per node — the snapshot froze on first
641/// `queue_notify` and was reused for every subsequent emit to the same
642/// node in the wave. That caused the documented late-subscriber +
643/// multi-emit-per-wave gap (R1.3.5.a divergence): a sub installed
644/// between two emits to the same node was invisible to the second
645/// emit's flush slice. The revision-tracked batch list resolves it —
646/// late subs land in a fresh batch that frozenly carries them, while
647/// pre-subscribe batches retain their original snapshot so the new
648/// sub doesn't double-receive earlier emits via flush AND handshake.
649pub(crate) struct PendingPerNode {
650    pub(crate) batches: SmallVec<[PendingBatch; 1]>,
651}
652
653impl PendingPerNode {
654    /// Iterate every queued message for this node across all batches in
655    /// arrival order. Used by R1.3.3.a invariant assertions and the
656    /// auto-resolve / Slice-G coalescing tier-3-presence checks, which
657    /// reason about wave-content per node, not per batch.
658    pub(crate) fn iter_messages(&self) -> impl Iterator<Item = &Message> + '_ {
659        self.batches.iter().flat_map(|b| b.messages.iter())
660    }
661
662    /// Mutable counterpart for `iter_messages`. Used by
663    /// `rewrite_prior_resolved_to_data` to in-place rewrite Resolved
664    /// entries to Data when a wave detects a multi-emit case after the
665    /// fact.
666    pub(crate) fn iter_messages_mut(&mut self) -> impl Iterator<Item = &mut Message> + '_ {
667        self.batches.iter_mut().flat_map(|b| b.messages.iter_mut())
668    }
669}
670
671/// RAII helper for the A6 reentrancy guard (Slice F, 2026-05-07).
672///
673/// Pushes `node_id` onto [`WaveState::currently_firing`] on construction,
674/// pops it on Drop. [`Core::set_deps`] consults the stack and rejects
675/// `set_deps(N, ...)` from inside N's own fn-fire with
676/// [`crate::node::SetDepsError::ReentrantOnFiringNode`] — closing the
677/// D1 hazard where Phase-1's snapshot of `dep_handles` would refer to
678/// a different dep ordering than Phase-3's `tracked` storage.
679///
680/// Wraps the lock-released `invoke_fn` (and operator-equivalent FFI
681/// callbacks like `project_each` / `predicate_each`). Drop fires even
682/// on panic, so the stack stays balanced under user-fn unwinds.
683///
684/// Membership semantics (NOT strict LIFO): the only consumer of
685/// `currently_firing` is `Core::set_deps`'s reentrancy check, which uses
686/// `contains(&n)` — a set-membership test. Drop pops the right-most
687/// matching `node_id` via `rposition` + `swap_remove`. For a stack like
688/// `[A, B, A]` (A's fn re-enters B, B's fn re-enters A), B's drop pops
689/// the SECOND A (index 1) via swap_remove, leaving `[A, A]` — the
690/// physical order of the remaining As may not match construction order,
691/// but membership is preserved. If a future call site needs strict LIFO
692/// (e.g. "pop the most recently fired node"), switch to `pop()` + assert
693/// the popped value equals `self.node_id`. (QA A6, 2026-05-07)
694// D221 (F-b) floor-hardening, 2026-05-17: holds `&'a Core`, NOT an
695// owned `core.clone()` (Core is no longer `Clone`). D246/S2c: the
696// `group_locks`/`global_wave` Arcs are deleted; the lock-free
697// single-owner `RefCell` floor pays zero per-fn-fire Arc tax. Both
698// construction sites
699// (`fire_regular` batch.rs:~1148, `fire_operator` batch.rs:~1719) are
700// locals in a `&self` method, so the `self: &Core` borrow strictly
701// outlives the guard — the lifetime is sound by construction (no
702// escape, dropped within the same method). Removing the clone here also
703// stops S2's `LockedCell` deletion from being able to reintroduce the
704// tax.
705pub(crate) struct FiringGuard<'a> {
706    core: &'a Core,
707    node_id: NodeId,
708}
709
710impl<'a> FiringGuard<'a> {
711    pub(crate) fn new(core: &'a Core, node_id: NodeId) -> Self {
712        // /qa F2 reverted (2026-05-10): currently_firing moved BACK to
713        // CoreState (cross-thread visible, restoring the D091 P13 check).
714        // Push under the state lock scope.
715        {
716            let mut s = core.lock_state();
717            s.shared.currently_firing.push(node_id);
718        }
719        Self { core, node_id }
720    }
721}
722
723impl Drop for FiringGuard<'_> {
724    fn drop(&mut self) {
725        // /qa F2 reverted (2026-05-10): currently_firing moved BACK to
726        // CoreState. Pop under state lock.
727        {
728            let mut s = self.core.lock_state();
729            // Pop the right-most matching node_id (membership semantics —
730            // not strict LIFO). If absent, an external rebalance already
731            // popped — silent no-op (panic-in-Drop is poison).
732            if let Some(pos) = s
733                .shared
734                .currently_firing
735                .iter()
736                .rposition(|n| *n == self.node_id)
737            {
738                s.shared.currently_firing.swap_remove(pos);
739            }
740        }
741    }
742}
743
744/// Borrow the per-operator scratch slot as `&T`. Panics if the slot is
745/// uninitialized or the contained type doesn't match `T` — both are
746/// invariant violations for any `fire_op_*` helper that should only be
747/// called from `fire_operator`'s match arm for the matching variant.
748fn scratch_ref<T: crate::op_state::OperatorScratch>(s: &CoreState, node_id: NodeId) -> &T {
749    s.require_node(node_id)
750        .op_scratch
751        .as_ref()
752        .expect("op_scratch slot uninitialized for operator node")
753        .as_any_ref()
754        .downcast_ref::<T>()
755        .expect("op_scratch type mismatch")
756}
757
758/// Mutable borrow of the per-operator scratch slot. Same invariants as
759/// [`scratch_ref`].
760fn scratch_mut<T: crate::op_state::OperatorScratch>(s: &mut CoreState, node_id: NodeId) -> &mut T {
761    s.require_node_mut(node_id)
762        .op_scratch
763        .as_mut()
764        .expect("op_scratch slot uninitialized for operator node")
765        .as_any_mut()
766        .downcast_mut::<T>()
767        .expect("op_scratch type mismatch")
768}
769
770impl Core {
771    // -------------------------------------------------------------------
772    // Wave entry + drain
773    // -------------------------------------------------------------------
774
775    /// Wave entry. The caller passes a closure that performs the wave's
776    /// triggering operation (`commit_emission`, `terminate_node`, etc.).
777    /// The closure runs lock-released; closure-internal Core methods
778    /// acquire the state lock as they go.
779    ///
780    /// **Implementation:** delegates to [`Self::begin_batch`] for the
781    /// wave's RAII lifecycle. The returned `BatchGuard` claims `in_tick`
782    /// (`Core::generation`-keyed) and on drop runs the drain + flush +
783    /// sink-fire phases — OR, if the closure panicked, the
784    /// panic-discard path that restores cache snapshots and clears
785    /// in_tick. (S4/D248: the `wave_owner` re-entrant mutex is deleted —
786    /// single-owner `!Send` Core, one uninterrupted owner-side drain.)
787    /// This unification gives `run_wave` the same panic-safety
788    /// guarantee as the user-facing `Core::batch`.
789    ///
790    /// **Re-entrance:** a closure invoked from inside another wave — the
791    /// inner `run_wave`'s `begin_batch` observes `in_tick=true`, the
792    /// returned guard is non-owning (`owns_tick=false`), drop is a no-op.
793    /// The outer wave's drain picks up the inner closure's queued work.
794    ///
795    /// **Lock-release discipline (Slice A close, M1):** all binding-side
796    /// callbacks except the subscribe-time handshake fire lock-released.
797    /// Sinks / user fns / custom-equals oracles that re-enter Core via
798    /// the owner-side mailbox/`DeferQueue` seam run a nested wave. The
799    /// one owner thread runs the in-flight drain to quiescence before
800    /// `emit` returns — preserving the user-facing "emit returning means
801    /// subscribers have observed" contract (no cross-thread lock needed;
802    /// there is no cross-thread emitter).
803    /// Wave entry with a known `seed` node. Acquires only the partitions
804    /// transitively touched from `seed` (downstream cascade via
805    /// `s.children` + R1.3.9.d meta-companion cascade) instead of every
806    /// current partition. The canonical Y1 parallelism win for per-seed
807    /// entry points (`Core::emit`, `Core::subscribe`'s activation,
808    /// `Core::pause` / `Core::resume` / `Core::invalidate` / `Core::complete`
809    /// / `Core::error` / `Core::teardown` / `Core::set_deps`'s
810    /// push-on-subscribe).
811    ///
812    /// S4/D248: single-owner `!Send + !Sync` Core — one uninterrupted
813    /// owner-side drain per wave; the deleted per-partition `wave_owner`
814    /// `ReentrantMutex` parallelism is replaced by host-native
815    /// concurrency across *independent per-worker Cores* (actor model).
816    /// The "emit returning means subscribers have observed" contract
817    /// holds because the one owner thread drains to quiescence before
818    /// returning.
819    ///
820    /// Slice Y1 / Phase E (2026-05-08).
821    pub(crate) fn run_wave_for<F>(&self, seed: crate::handle::NodeId, op: F)
822    where
823        F: FnOnce(&Self),
824    {
825        let _guard = self.begin_batch_for(seed);
826        op(self);
827    }
828
829    /// Fallible wave entry. Returns `Err` if partition acquire violates
830    /// ascending order (Phase H+ STRICT, D115). Used by `try_emit` /
831    /// `try_complete` / `try_error`; the public `run_wave_for` calls
832    /// `begin_batch_for` which panics on violation.
833    pub(crate) fn try_run_wave_for<F>(
834        &self,
835        seed: crate::handle::NodeId,
836        op: F,
837    ) -> Result<(), crate::node::PartitionOrderViolation>
838    where
839        F: FnOnce(&Self),
840    {
841        let _guard = self.try_begin_batch_for(seed)?;
842        op(self);
843        Ok(())
844    }
845
846    /// Drain retains held by `wave_cache_snapshots` and return them so
847    /// the caller can release them lock-released. Called from the
848    /// wave-success path in [`BatchGuard::drop`].
849    ///
850    /// Q-beyond Sub-slice 1 (D108, 2026-05-09): the snapshots map moved
851    /// to per-thread `WaveState`; signature takes `&mut WaveState`. The
852    /// drain-and-release-lock-released discipline (introduced as /qa A1
853    /// fix 2026-05-09 against the prior cross_partition mutex) carries
854    /// over: caller drains under WaveState borrow + state lock, releases
855    /// after both are dropped — `release_handle` may re-enter Core via
856    /// finalizers and re-entry under either guard would deadlock /
857    /// double-borrow.
858    #[must_use]
859    pub(crate) fn drain_wave_cache_snapshots(ws: &mut WaveState) -> Vec<HandleId> {
860        if ws.wave_cache_snapshots.is_empty() {
861            return Vec::new();
862        }
863        std::mem::take(&mut ws.wave_cache_snapshots)
864            .into_values()
865            .collect()
866    }
867
868    /// Restore cache slots from `wave_cache_snapshots` and clear the map.
869    /// Called from the wave-abort path in `BatchGuard::drop` (panic).
870    ///
871    /// For each snapshotted node:
872    ///
873    /// 1. Read the current cache (the in-flight new value).
874    /// 2. Set `cache = old_handle` (the snapshot's retained value).
875    /// 3. Release the now-unowned current cache handle.
876    ///
877    /// Returns the list of "current" handles to release outside the lock.
878    /// Q-beyond Sub-slice 1 (D108, 2026-05-09): the snapshots map moved
879    /// to per-thread `WaveState`; signature takes both `s` (for cache
880    /// slots) and `ws` (for the snapshots map).
881    pub(crate) fn restore_wave_cache_snapshots(
882        &self,
883        s: &mut CoreState,
884        ws: &mut WaveState,
885    ) -> Vec<HandleId> {
886        if ws.wave_cache_snapshots.is_empty() {
887            return Vec::new();
888        }
889        let snapshots = std::mem::take(&mut ws.wave_cache_snapshots);
890        let mut releases = Vec::with_capacity(snapshots.len());
891        for (node_id, old_handle) in snapshots {
892            let Some(rec) = s.nodes.get_mut(&node_id) else {
893                releases.push(old_handle);
894                continue;
895            };
896            let current = std::mem::replace(&mut rec.cache, old_handle);
897            if current != NO_HANDLE {
898                releases.push(current);
899            }
900        }
901        releases
902    }
903
904    /// Drain pending fires until quiescent, then flush wave-end notifications
905    /// to subscribers. Each fire iteration drops the state lock around the
906    /// binding's `invoke_fn` callback so user fns may re-enter Core safely.
907    ///
908    /// `&self`-only — manages its own locking. Called from [`Self::run_wave`]
909    /// and [`super::node::Core::activate_derived`] (via `run_wave`).
910    pub(crate) fn drain_and_flush(&self) {
911        let mut guard = 0u32;
912        loop {
913            // A′ (D232-AMEND): apply any producer-sink / timer
914            // `MailboxOp`s **in-wave** at the top of every drain
915            // iteration. Each applied op re-enters `Core::{emit,
916            // complete,error}` with `in_tick = true` (non-owning batch
917            // guard → it does NOT start its own drain; it queues into
918            // this wave's `pending_fires`), so a sink that posted during
919            // the previous `fire_fn` is picked up on the very next
920            // iteration — immediate, in-wave, cascade-ordering-preserving
921            // (consistent with the pre-S2b deferred-producer-op
922            // drained-within-the-wave behaviour). Quiescence requires
923            // BOTH `pending_fires` AND the mailbox empty.
924            //
925            // §7-floor guard (D-reflect, 2026-05-17): gate on the cheap
926            // `runnable` atomic (one `Acquire` load) BEFORE touching the
927            // mailbox `parking_lot::Mutex`. A no-producer / no-timer wave
928            // (the `identity_dedup` ≈508 ns floor path) never posts, so
929            // `runnable` stays `false` and this costs one relaxed-ish
930            // atomic load per drain iteration — NOT a mutex lock + deque
931            // pop. **Sink-side** posts are same-thread, in-wave: the
932            // `runnable` Release precedes this Acquire on the same
933            // thread, so no in-wave op is missed. **Task-side** posts
934            // (timer/temporal `tokio::spawn` tasks) are cross-thread:
935            // their happens-before is the `ops` `parking_lot::Mutex`
936            // (acquire/release), NOT this atomic — `runnable` is only an
937            // advisory fast-path bit there, and a racing task post is
938            // caught by the embedder pump's *unconditional*
939            // `drain_mailbox()` (timer tasks drain at the pump, not this
940            // in-wave gate). Do NOT remove the unconditional pump drain.
941            // This is exactly the per-group wake bit S4 wires to the
942            // host executor — doing it here now is coherent, not
943            // throwaway.
944            if self.mailbox.is_runnable() || self.deferred.is_runnable() {
945                self.drain_mailbox();
946            }
947
948            // R1.3.8.c (Slice F, A3): if no fires are pending but there are
949            // queued pause-overflow ERRORs, synthesize them now. The
950            // resulting ERROR cascade may add to pending_fires (children
951            // settling their terminal state), so we loop back to drain.
952            //
953            // Q-beyond Sub-slice 1 + 2 (D108, 2026-05-09): pending_fires
954            // and pending_pause_overflow both live on per-thread
955            // WaveState. State lock no longer required for either read.
956            let synth_pending = with_wave_state(|ws| {
957                if ws.pending_fires.is_empty() && !ws.pending_pause_overflow.is_empty() {
958                    std::mem::take(&mut ws.pending_pause_overflow)
959                } else {
960                    Vec::new()
961                }
962            });
963            for entry in synth_pending {
964                // Lock-released call to the binding hook. Default impl
965                // returns None — the binding has opted out of R1.3.8.c
966                // and we fall back to silent-drop + ResumeReport.dropped.
967                let handle = self.binding.synthesize_pause_overflow_error(
968                    entry.node_id,
969                    entry.dropped_count,
970                    entry.configured_max,
971                    entry.lock_held_ns / 1_000_000,
972                );
973                if let Some(h) = handle {
974                    // Re-enter Core::error to terminate the node and
975                    // cascade. We're inside a wave (`in_tick = true`),
976                    // so error() gets a non-owning batch guard — it
977                    // doesn't try to start its own drain. The cascade
978                    // queues into our outer drain via pending_fires
979                    // and pending_notify.
980                    self.error(entry.node_id, h);
981                }
982            }
983
984            // Pick next fire under a short lock. Also re-read the configured
985            // drain cap so callers can tune via `Core::set_max_batch_drain_iterations`
986            // without restarting waves mid-flight.
987            //
988            // Q-beyond Sub-slice 2 (D108, 2026-05-09): pending_fires lives
989            // on per-thread WaveState; pick_next_fire takes both state and
990            // WaveState. The pending_size diagnostic and emptiness check
991            // also read WaveState. Borrow scopes are split: WaveState
992            // borrow drops before fire_fn runs (which re-borrows WaveState
993            // via fire_regular / fire_operator).
994            let (next, cap, pending_size) = {
995                let s = self.lock_state();
996                let cap = s.shared.max_batch_drain_iterations;
997                let (next, pending_size) = with_wave_state(|ws| {
998                    if ws.pending_fires.is_empty() {
999                        return (None, 0);
1000                    }
1001                    let size = ws.pending_fires.len();
1002                    let next = Self::pick_next_fire(&s, ws);
1003                    (next, size)
1004                });
1005                (next, cap, pending_size)
1006            };
1007            if pending_size == 0 {
1008                // QA F1 (2026-05-18): quiescence requires BOTH
1009                // `pending_fires` AND the mailbox empty — the asserted
1010                // invariant the old `if pending_size == 0 { break }`
1011                // did NOT enforce. If the mailbox still holds work,
1012                // `continue` so the next iteration's top-of-loop
1013                // `is_runnable()`-gated `drain_mailbox()` applies it
1014                // (an applied op either cascades into `pending_fires`
1015                // or, if terminal/no-op, leaves the mailbox empty so
1016                // the *next* check breaks). §7 floor: no producer/timer
1017                // ⇒ never posted ⇒ `is_runnable()` false ⇒ breaks on the
1018                // first empty `pending_fires` (one atomic load — already
1019                // in the floor budget).
1020                // QA P3 (2026-05-18): the mailbox-continue does NOT
1021                // count against the fire-cascade `cap`. `drain_mailbox`
1022                // already drains the FIFO to quiescence in ONE call
1023                // (re-posts during `apply` are popped by the same
1024                // `drain_into` loop), and the self-reposting-`Defer`
1025                // livelock is bounded INSIDE `drain_into` (its own
1026                // `max_ops`). Reaching here `is_runnable()` again means
1027                // genuinely-new cross-thread (timer) work — bounded by
1028                // external input, not a fire cycle — so counting it
1029                // against the fire `cap` would false-trip a production
1030                // panic on heavy producer/timer graphs.
1031                if self.mailbox.is_runnable() || self.deferred.is_runnable() {
1032                    continue;
1033                }
1034                break;
1035            }
1036            guard += 1;
1037            assert!(
1038                guard < cap,
1039                "wave drain exceeded {cap} iterations \
1040                 (pending_fires={pending_size}). Most likely cause: a runtime \
1041                 cycle introduced by an operator that re-arms its own pending_fires \
1042                 slot from inside `invoke_fn` (e.g. a producer that subscribes to \
1043                 itself, or a fn that calls Core::emit on a node whose fn fires \
1044                 the original node again). Structural cycles via set_deps are \
1045                 rejected at edge-mutation time. Tune via Core::set_max_batch_drain_iterations \
1046                 only with concrete evidence the workload needs more iterations."
1047            );
1048            let Some(next) = next else { break };
1049            // fire_fn manages its own locking around invoke_fn.
1050            self.fire_fn(next);
1051        }
1052        // Auto-resolve sweep: nodes registered in pending_auto_resolve
1053        // by the RESOLVED child propagation need a Resolved if they didn't
1054        // fire and settle via their own commit_emission. Check pending_notify
1055        // for each candidate — if it has Dirty but no tier-3+ message, the
1056        // node never settled and needs auto-Resolved. Route through
1057        // queue_notify so paused nodes get the Resolved into their pause
1058        // buffer.
1059        let mut s = self.lock_state();
1060        // Q-beyond Sub-slice 1 + 2 (D108, 2026-05-09): pending_auto_resolve
1061        // and pending_notify both live on per-thread WaveState. /qa A5
1062        // fix (2026-05-09): explicit scope for the WaveState borrow so
1063        // it drops BEFORE the for-loop. Inside the loop, `queue_notify`
1064        // re-borrows WaveState for `pending_pause_overflow.push` /
1065        // `pending_notify` writes — re-entrance on RefCell::borrow_mut
1066        // would panic. Explicit scope makes the lifetime load-bearing.
1067        let candidates = with_wave_state(|ws| std::mem::take(&mut ws.pending_auto_resolve));
1068        for node_id in candidates {
1069            let needs_resolve = with_wave_state(|ws| {
1070                ws.pending_notify
1071                    .get(&node_id)
1072                    .is_some_and(|entry| !entry.iter_messages().any(|m| m.tier() >= 3))
1073            });
1074            if needs_resolve {
1075                self.queue_notify(&mut s, node_id, Message::Resolved);
1076            }
1077        }
1078        // Final flush phase — populates deferred_flush_jobs
1079        // from pending_notify (already carries per-node sink snapshots).
1080        self.flush_notifications(&mut s);
1081    }
1082
1083    /// Pick the pending node with the lowest topological rank.
1084    ///
1085    /// Nodes with lower `topo_rank` have no transitive upstream in
1086    /// `pending_fires` (by construction — `topo_rank = 1 + max dep rank`).
1087    /// This is O(|pending_fires|) instead of the prior O(N·V) BFS.
1088    /// §10 perf optimization (D047, Slice U).
1089    ///
1090    /// Q-beyond Sub-slice 2 (D108, 2026-05-09): `pending_fires` lives on
1091    /// per-thread `WaveState`. Caller passes `&WaveState` alongside
1092    /// `&CoreState` so the borrow scopes stay disjoint and visible.
1093    fn pick_next_fire(s: &CoreState, ws: &WaveState) -> Option<NodeId> {
1094        ws.pending_fires
1095            .iter()
1096            .copied()
1097            .min_by_key(|&id| s.nodes.get(&id).map_or(0, |r| r.topo_rank))
1098    }
1099
1100    /// Wave drain entry point. Dispatches via `rec.op` to either the
1101    /// regular fn-fire path ([`Self::fire_regular`]) or the operator
1102    /// dispatch ([`Self::fire_operator`]).
1103    pub(crate) fn fire_fn(&self, node_id: NodeId) {
1104        let op = {
1105            let s = self.lock_state();
1106            s.nodes.get(&node_id).and_then(|r| r.op)
1107        };
1108        match op {
1109            Some(operator_op) => self.fire_operator(node_id, operator_op),
1110            None => {
1111                // State / Derived / Dynamic / Producer all dispatch via fn_id.
1112                self.fire_regular(node_id);
1113            }
1114        }
1115    }
1116
1117    /// Fire a node's fn lock-released around `invoke_fn`.
1118    ///
1119    /// Phase 1 (lock-held): remove from pending_fires, snapshot fn_id +
1120    /// dep_records → DepBatch + kind. Skip if terminal, first-run-gate-closed,
1121    /// or stateless.
1122    ///
1123    /// Phase 2 (lock-released): call `BindingBoundary::invoke_fn`. User fn
1124    /// callbacks may re-enter Core (`emit`, `pause`, etc.) and run a nested
1125    /// wave — the in_tick gate composes naturally because nested calls
1126    /// observe `in_tick = true` and skip their own drain.
1127    ///
1128    /// Phase 3 (lock-held): mark `has_fired_once`, store dynamic-tracked,
1129    /// decide between Noop+RESOLVED, single Data, or Batch.
1130    ///
1131    /// Phase 4: commit emissions. Single Data goes through
1132    /// `commit_emission` (with equals substitution). Batch emissions are
1133    /// processed in sequence — Data via `commit_emission_verbatim` (no
1134    /// equals substitution per R1.3.2.d / R1.3.3.c), Complete/Error via
1135    /// terminal cascade.
1136    #[allow(clippy::too_many_lines)] // Slice G added Noop / Batch tier-3 guards
1137    fn fire_regular(&self, node_id: NodeId) {
1138        enum FireAction {
1139            None,
1140            SingleData(HandleId),
1141            Batch(SmallVec<[FnEmission; 2]>),
1142        }
1143
1144        // Phase 1: snapshot inputs — build DepBatch per dep from dep_records.
1145        // `has_fired_once` is captured here for the Slice E2 OnRerun gate
1146        // (Phase 1.5 below): the cleanup hook only fires when the fn has
1147        // run at least once already in this activation cycle.
1148        let prep: Option<(crate::handle::FnId, Vec<DepBatch>, bool, bool, bool)> = {
1149            let s = self.lock_state();
1150            // Q-beyond Sub-slice 2 (D108, 2026-05-09): pending_fires lives
1151            // on per-thread WaveState. Removed via with_wave_state — no
1152            // re-entry concern because only the immediate remove happens
1153            // under the borrow.
1154            with_wave_state(|ws| {
1155                ws.pending_fires.remove(&node_id);
1156            });
1157            let rec = s.require_node(node_id);
1158            // Skip: terminal, first-run-gate-closed (R2.5.3 / R5.4 — partial
1159            // mode opts out of the gate per D011), or stateless.
1160            //
1161            // D263: when `terminal_as_real_input == true`, a terminal dep
1162            // counts as "real input" so the gate opens on COMPLETE-without-
1163            // DATA from any dep (mirrors `fire_operator`'s unconditional
1164            // terminal-aware clause; gated here per-node so the historical
1165            // sentinel-hold behaviour stays the default for `fire_fn`).
1166            let has_real_input = !rec.has_sentinel_deps()
1167                || (rec.terminal_as_real_input
1168                    && rec.dep_records.iter().any(|dr| dr.terminal.is_some()));
1169            if rec.terminal.is_some() || (!rec.partial && !has_real_input) {
1170                None
1171            } else {
1172                rec.fn_id.map(|fn_id| {
1173                    let use_mask = rec.dep_records.len() <= 64;
1174                    let mask = rec.involved_mask;
1175                    let dep_batches: Vec<DepBatch> = rec
1176                        .dep_records
1177                        .iter()
1178                        .enumerate()
1179                        .map(|(i, dr)| DepBatch {
1180                            data: dr.data_batch.clone(),
1181                            prev_data: dr.prev_data,
1182                            // §10.3 perf (Slice V1): derive from bitmask
1183                            // for ≤64 deps; fall back to per-dep field.
1184                            involved: if use_mask {
1185                                (mask >> i) & 1 != 0
1186                            } else {
1187                                dr.involved_this_wave
1188                            },
1189                        })
1190                        .collect();
1191                    (
1192                        fn_id,
1193                        dep_batches,
1194                        rec.is_dynamic,
1195                        rec.has_fired_once,
1196                        rec.is_producer(),
1197                    )
1198                })
1199            }
1200        };
1201        let Some((fn_id, dep_batches, is_dynamic, has_fired_once, is_producer)) = prep else {
1202            return;
1203        };
1204
1205        // Phase 1.5 (Slice E2 — R2.4.5 OnRerun, lock-released per D045): if
1206        // the fn has fired at least once in this activation cycle, fire its
1207        // OnRerun cleanup hook BEFORE the next invoke_fn re-allocates fn-
1208        // local resources. First-fire is intentionally skipped — there is
1209        // no prior run to clean up. Fires OUTSIDE `FiringGuard` because
1210        // cleanup re-entrance is not the A6 reentrancy concern (which
1211        // protects against `set_deps(self, ...)` from inside the in-flight
1212        // invoke_fn). Operator nodes never reach this path (`fire_regular`
1213        // is the fn-id branch of `fire_fn`; operators dispatch via
1214        // `fire_operator`), so cleanup hooks correctly only fire for fn-
1215        // shaped nodes (state / derived / dynamic / producer).
1216        if has_fired_once {
1217            self.binding
1218                .cleanup_for(node_id, crate::boundary::CleanupTrigger::OnRerun);
1219        }
1220
1221        // Phase 2: invoke fn lock-released. A6 reentrancy guard is scoped to
1222        // the FFI call only — Phase 3's lock-held state mutation is not part
1223        // of "currently firing" because set_deps would already block on the
1224        // state lock by then. Drop on the guard pops the stack even if
1225        // invoke_fn panics, keeping `currently_firing` balanced.
1226        //
1227        // D246 rule 5 / D245 (QA D1) — the owner-side full-`Core` facade
1228        // hand-off is needed ONLY by producer-building bindings (to
1229        // construct `ProducerCtx` from a real Core surface here without a
1230        // thread-local / `Core` clone / stored back-ref — all β-invalid
1231        // under the actor model). Branch on node kind so the hot
1232        // derived/dynamic/state path keeps the single parameterless
1233        // `invoke_fn` virtual call it always had (no `&dyn CoreFull`
1234        // fat-pointer coercion, no default-body re-dispatch) — byte-
1235        // identical to pre-D246, zero §7-floor regression. Only the rare
1236        // producer-build fire pays the facade hand-off. `self: &Core`
1237        // unsized-coerces to `&dyn CoreFull` (`Core: CoreFull`).
1238        let result = {
1239            let _firing = FiringGuard::new(self, node_id);
1240            if is_producer {
1241                self.binding
1242                    .invoke_fn_with_core(node_id, fn_id, &dep_batches, self)
1243            } else {
1244                self.binding.invoke_fn(node_id, fn_id, &dep_batches)
1245            }
1246        };
1247
1248        // Phase 3: apply result under the lock — defensive terminal check
1249        // (a sibling cascade may have terminated this node during phase 2).
1250        let action: FireAction = {
1251            let mut s = self.lock_state();
1252            // Defensive: node may have terminated mid-phase-2 via a sibling
1253            // cascade (a fn that re-entered `Core::error` on a path that
1254            // cascaded here). If so, release any payload handles and no-op.
1255            if s.require_node(node_id).terminal.is_some() {
1256                match &result {
1257                    FnResult::Data { handle, .. } => {
1258                        self.binding.release_handle(*handle);
1259                    }
1260                    FnResult::Batch { emissions, .. } => {
1261                        for em in emissions {
1262                            match em {
1263                                FnEmission::Data(h) | FnEmission::Error(h) => {
1264                                    self.binding.release_handle(*h);
1265                                }
1266                                FnEmission::Complete => {}
1267                            }
1268                        }
1269                    }
1270                    FnResult::Noop { .. } => {}
1271                }
1272                return;
1273            }
1274            let rec = s.require_node_mut(node_id);
1275            rec.has_fired_once = true;
1276            if is_dynamic {
1277                let tracked = match &result {
1278                    FnResult::Data { tracked, .. }
1279                    | FnResult::Noop { tracked }
1280                    | FnResult::Batch { tracked, .. } => tracked.clone(),
1281                };
1282                if let Some(t) = tracked {
1283                    rec.tracked = t.into_iter().collect();
1284                }
1285            }
1286            match result {
1287                FnResult::Noop { .. } => {
1288                    // Slice G: skip Resolved if a prior emission in the same
1289                    // wave already queued tier-3 (would violate R1.3.3.a).
1290                    // Q-beyond Sub-slice 2 (D108, 2026-05-09): pending_notify
1291                    // lives on per-thread WaveState. Borrow scoped to the
1292                    // tier3 read so queue_notify (which re-borrows
1293                    // WaveState) doesn't double-borrow.
1294                    let already_dirty = s.require_node(node_id).dirty;
1295                    let already_tier3 = with_wave_state(|ws| {
1296                        ws.pending_notify
1297                            .get(&node_id)
1298                            .is_some_and(|entry| entry.iter_messages().any(|m| m.tier() == 3))
1299                    });
1300                    if already_dirty && !already_tier3 {
1301                        self.queue_notify(&mut s, node_id, Message::Resolved);
1302                    }
1303                    FireAction::None
1304                }
1305                FnResult::Data { handle, .. } => FireAction::SingleData(handle),
1306                FnResult::Batch { emissions, .. } if emissions.is_empty() => {
1307                    // Empty Batch is equivalent to Noop — settle with
1308                    // RESOLVED if the node was dirty (R1.3.1.a). Slice G:
1309                    // skip if a prior emission already queued tier-3.
1310                    // Q-beyond Sub-slice 2 (D108, 2026-05-09): see Noop
1311                    // arm above for the WaveState borrow scope rationale.
1312                    let already_dirty = s.require_node(node_id).dirty;
1313                    let already_tier3 = with_wave_state(|ws| {
1314                        ws.pending_notify
1315                            .get(&node_id)
1316                            .is_some_and(|entry| entry.iter_messages().any(|m| m.tier() == 3))
1317                    });
1318                    if already_dirty && !already_tier3 {
1319                        self.queue_notify(&mut s, node_id, Message::Resolved);
1320                    }
1321                    FireAction::None
1322                }
1323                FnResult::Batch { emissions, .. } => FireAction::Batch(emissions),
1324            }
1325        };
1326
1327        // Phase 4: commit emissions.
1328        match action {
1329            FireAction::None => {}
1330            // Single Data — equals substitution applies (R1.3.2).
1331            FireAction::SingleData(handle) => {
1332                self.commit_emission(node_id, handle);
1333            }
1334            // Batch — process in sequence. No equals substitution
1335            // (R1.3.2.d / R1.3.3.c: multi-message waves pass verbatim).
1336            FireAction::Batch(emissions) => {
1337                self.commit_batch(node_id, emissions);
1338            }
1339        }
1340    }
1341
1342    /// Process a `FnResult::Batch` emissions sequence. Each `Data` goes
1343    /// through `commit_emission_verbatim` (no equals substitution per
1344    /// R1.3.2.d / R1.3.3.c). Terminal emissions (`Complete` / `Error`)
1345    /// cascade per R1.3.4; processing stops at the first terminal and
1346    /// remaining handles are released (R1.3.4.a: no further messages
1347    /// after terminal).
1348    fn commit_batch(&self, node_id: NodeId, emissions: SmallVec<[FnEmission; 2]>) {
1349        let mut iter = emissions.into_iter();
1350        for em in iter.by_ref() {
1351            match em {
1352                FnEmission::Data(handle) => {
1353                    self.commit_emission_verbatim(node_id, handle);
1354                }
1355                FnEmission::Complete => {
1356                    self.complete(node_id);
1357                    break;
1358                }
1359                FnEmission::Error(handle) => {
1360                    self.error(node_id, handle);
1361                    break;
1362                }
1363            }
1364        }
1365        // Release handles from any emissions after the terminal break.
1366        for em in iter {
1367            match em {
1368                FnEmission::Data(h) | FnEmission::Error(h) => {
1369                    self.binding.release_handle(h);
1370                }
1371                FnEmission::Complete => {}
1372            }
1373        }
1374    }
1375
1376    // -------------------------------------------------------------------
1377    // Emission commit — equals-substitution lives here
1378    // -------------------------------------------------------------------
1379
1380    /// Apply a node's emission. `&self`-only; brackets the equals check
1381    /// around a lock release so `BindingBoundary::custom_equals` can re-enter
1382    /// Core safely.
1383    ///
1384    /// Phase 1 (lock-held): defensive terminal short-circuit; snapshot
1385    /// equals_mode + old cache handle.
1386    ///
1387    /// Phase 2 (lock-released): call `handles_equal` — `EqualsMode::Identity`
1388    /// is a pure `u64` compare with no boundary call; `EqualsMode::Custom`
1389    /// crosses to the binding's `custom_equals` oracle, which may re-enter
1390    /// Core.
1391    ///
1392    /// Phase 3 (lock-held): set cache, queue Dirty + Data/Resolved into
1393    /// pending_notify (which snapshots subscribers on first touch),
1394    /// propagate to children.
1395    // Q2 / Q3 (2026-05-09) tipped past clippy's 100-line threshold; the
1396    // function is already a multi-phase wave-engine routine and breaking
1397    // out the four phases would obscure the lock-discipline.
1398    #[allow(clippy::too_many_lines)]
1399    pub(crate) fn commit_emission(&self, node_id: NodeId, new_handle: HandleId) {
1400        assert!(
1401            new_handle != NO_HANDLE,
1402            "NO_HANDLE is not a valid DATA payload (R1.2.4) for node {node_id:?}",
1403        );
1404
1405        // Phase 1: terminal short-circuit + snapshot equals/cache.
1406        let snapshot = {
1407            let s = self.lock_state();
1408            let rec = s.require_node(node_id);
1409            // (§7-D: the throwaway `bench_state_collapse` relocated
1410            // is_state/producer assert was removed — the normal-path
1411            // validation in `Core::emit` is retained; the
1412            // commit_emission single-pass collapse is deferred, §7-A.)
1413            if rec.terminal.is_some() {
1414                drop(s);
1415                self.binding.release_handle(new_handle);
1416                return;
1417            }
1418            (rec.cache, rec.equals)
1419        };
1420        let (old_handle, equals_mode) = snapshot;
1421
1422        // Slice G (2026-05-07): R1.3.2.d says equals substitution only
1423        // fires for SINGLE-DATA waves at one node. Detect "this is a
1424        // subsequent emit in the same wave at this node" via the
1425        // per-thread `TIER3_EMITTED_THIS_WAVE` thread-local
1426        // (D1 patch, 2026-05-09 — moved off per-partition state to be
1427        // robust against mid-wave cross-thread `set_deps` partition
1428        // splits). If set → multi-emit wave: skip equals, queue Data
1429        // verbatim, retroactively rewrite any prior Resolved (queued by
1430        // an earlier same-value emit's equals match) to Data using the
1431        // wave-start cache snapshot. Outside batch / first emit:
1432        // standard per-emit equals path. Thread-local lookup is
1433        // ~5ns and lock-free.
1434        let is_subsequent_emit_in_wave = tier3_check(node_id);
1435
1436        if is_subsequent_emit_in_wave {
1437            // Multi-emit wave detected. Skip equals, queue Data verbatim.
1438            // Also rewrite any prior Resolved entries to Data using the
1439            // wave-start cache snapshot.
1440            self.rewrite_prior_resolved_to_data(node_id);
1441            self.commit_emission_verbatim(node_id, new_handle);
1442            return;
1443        }
1444
1445        // Phase 2: equals check (lock-released for Custom).
1446        let is_data = !self.handles_equal_lock_released(equals_mode, old_handle, new_handle);
1447
1448        // Phase 3: apply emission under the lock. Defensive terminal
1449        // re-check — a concurrent cascade between phase 2 and phase 3
1450        // could have terminated the node.
1451        let mut s = self.lock_state();
1452        if s.require_node(node_id).terminal.is_some() {
1453            drop(s);
1454            self.binding.release_handle(new_handle);
1455            return;
1456        }
1457
1458        // R1.3.1.a condition (b): synthesize DIRTY only if node not already
1459        // dirty from an earlier emission in the same wave.
1460        let already_dirty = s.require_node(node_id).dirty;
1461        s.require_node_mut(node_id).dirty = true;
1462        if !already_dirty {
1463            self.queue_notify(&mut s, node_id, Message::Dirty);
1464        }
1465
1466        if is_data {
1467            // P3 (Slice A close /qa): re-read CURRENT cache. Same-thread
1468            // re-entry from a `custom_equals` oracle that called back into
1469            // `Core::emit` on this same node during phase 2's lock-released
1470            // equals check could have advanced the cache between phase 1's
1471            // snapshot (`old_handle`) and this point.
1472            let current_cache = s.require_node(node_id).cache;
1473            // Q-beyond Sub-slice 1 (D108, 2026-05-09): wave_cache_snapshots
1474            // lives on per-thread WaveState. `in_tick` is the one-Core-
1475            // per-OS-thread [`IN_TICK_OWNED`] slot (D252); this read is on
1476            // the wave-owner thread, so it observes this thread's own
1477            // ownership.
1478            let in_tick = self.in_tick();
1479            let snapshot_taken = if in_tick && current_cache != NO_HANDLE {
1480                use std::collections::hash_map::Entry;
1481                with_wave_state(|ws| match ws.wave_cache_snapshots.entry(node_id) {
1482                    Entry::Vacant(slot) => {
1483                        slot.insert(current_cache);
1484                        true
1485                    }
1486                    Entry::Occupied(_) => false,
1487                })
1488            } else {
1489                false
1490            };
1491            s.require_node_mut(node_id).cache = new_handle;
1492            if current_cache != NO_HANDLE && !snapshot_taken {
1493                self.binding.release_handle(current_cache);
1494            }
1495            // Slice E1 (R2.6.5 / Lock 6.G): push DATA into the replay
1496            // buffer if the node opted in. RESOLVED entries are NOT
1497            // buffered (canonical "DATA only").
1498            self.push_replay_buffer(&mut s, node_id, new_handle);
1499            // Slice G (D1 patch, 2026-05-09): mark this node as having
1500            // emitted tier-3 in this wave on the per-thread tracker.
1501            tier3_mark(node_id);
1502            self.queue_notify(&mut s, node_id, Message::Data(new_handle));
1503            // Propagate to children
1504            let child_ids: Vec<NodeId> = s
1505                .children
1506                .get(&node_id)
1507                .map(|c| c.iter().copied().collect())
1508                .unwrap_or_default();
1509            for child_id in child_ids {
1510                let dep_idx = s.require_node(child_id).dep_index_of(node_id);
1511                if let Some(idx) = dep_idx {
1512                    self.deliver_data_to_consumer(&mut s, child_id, idx, new_handle);
1513                }
1514            }
1515        } else {
1516            // RESOLVED: handle unchanged. Don't release; old still in use.
1517            // Slice G: snapshot cache so a subsequent same-wave emit can
1518            // rewrite this Resolved to Data using the snapshot.
1519            // Q-beyond Sub-slice 1 (D108, 2026-05-09): wave_cache_snapshots
1520            // lives on per-thread WaveState. /qa F1 reverted (2026-05-10);
1521            // D252 (S5) collapsed to one-Core-per-OS-thread `Cell<u64>` —
1522            // `in_tick` is read on the wave-owner
1523            // thread (observes this thread's own ownership).
1524            let current_cache = s.require_node(node_id).cache;
1525            if self.in_tick() && current_cache != NO_HANDLE {
1526                use std::collections::hash_map::Entry;
1527                with_wave_state(|ws| {
1528                    if let Entry::Vacant(slot) = ws.wave_cache_snapshots.entry(node_id) {
1529                        self.binding.retain_handle(current_cache);
1530                        slot.insert(current_cache);
1531                    }
1532                });
1533            }
1534            // Slice G (D1 patch, 2026-05-09): mark this node as having
1535            // emitted tier-3 in this wave on the per-thread tracker.
1536            tier3_mark(node_id);
1537            self.queue_notify(&mut s, node_id, Message::Resolved);
1538            let child_ids: Vec<NodeId> = s
1539                .children
1540                .get(&node_id)
1541                .map(|c| c.iter().copied().collect())
1542                .unwrap_or_default();
1543            // /qa A7 fix (2026-05-09): collect auto-resolve inserts
1544            // during the loop and bulk-insert into pending_auto_resolve
1545            // under a SINGLE cross_partition acquire after the loop.
1546            // Pre-fix the loop acquired `cross_partition` once per
1547            // child via `self.lock_cross_partition().pending_auto_resolve.insert(...)`,
1548            // which is N mutex hops for an N-child cascade. Cannot
1549            // hoist to acquire-cps-before-loop because `queue_notify`
1550            // (called inside the loop) also acquires cross_partition
1551            // for `pending_pause_overflow.push` in the rare overflow
1552            // case — re-entrance on the non-reentrant Mutex would
1553            // self-deadlock.
1554            let mut auto_resolve_inserts: SmallVec<[NodeId; 4]> = SmallVec::new();
1555            for child_id in child_ids {
1556                let already_involved = s.require_node(child_id).involved_this_wave;
1557                if !already_involved {
1558                    {
1559                        let child = s.require_node_mut(child_id);
1560                        child.involved_this_wave = true;
1561                        child.dirty = true;
1562                    }
1563                    self.queue_notify(&mut s, child_id, Message::Dirty);
1564                    // Q2 (2026-05-09): pending_auto_resolve lives on
1565                    // CrossPartitionState. Deferred to after-loop
1566                    // bulk insert per the /qa A7 fix above.
1567                    auto_resolve_inserts.push(child_id);
1568                }
1569            }
1570            // /qa A7 (2026-05-09) — preserved post-Sub-slice-1 (D108):
1571            // single WaveState borrow for the bulk-insert. queue_notify
1572            // above no longer holds the WaveState borrow by the time we
1573            // reach here, so this borrow is uncontested.
1574            if !auto_resolve_inserts.is_empty() {
1575                with_wave_state(|ws| ws.pending_auto_resolve.extend(auto_resolve_inserts));
1576            }
1577        }
1578    }
1579
1580    /// Slice G: when a multi-emit wave is detected at `node_id` (a second
1581    /// emit arrives while a prior tier-3 message is still pending), rewrite
1582    /// any `Resolved` entries from earlier emits to `Data(snapshot_cache)`
1583    /// so the wave conforms to R1.3.3.a (≥1 DATA OR exactly 1 RESOLVED).
1584    /// Touches both `pending_notify` (immediate-flush path) and the per-node
1585    /// pause buffer (paused path).
1586    fn rewrite_prior_resolved_to_data(&self, node_id: NodeId) {
1587        let mut s = self.lock_state();
1588        // Q-beyond Sub-slice 1 + 2 (D108, 2026-05-09): wave_cache_snapshots
1589        // and pending_notify both live on per-thread WaveState. Single
1590        // WaveState borrow handles both the snapshot lookup and the
1591        // pending_notify rewrite; the pause-buffer path uses the state
1592        // lock and is independent of WaveState.
1593        let snapshot = match with_wave_state(|ws| ws.wave_cache_snapshots.get(&node_id).copied()) {
1594            Some(h) if h != NO_HANDLE => h,
1595            // No snapshot available — the prior Resolved was queued without
1596            // a cache (sentinel pre-emit). Nothing to rewrite to; the
1597            // multi-emit case from sentinel is fine (verbatim Data path).
1598            _ => return,
1599        };
1600        let mut retains_needed = 0u32;
1601        // Pending_notify path. Walk all batches' messages — Slice-G
1602        // coalescing reasons about wave-content per node, not per-batch.
1603        with_wave_state(|ws| {
1604            if let Some(entry) = ws.pending_notify.get_mut(&node_id) {
1605                for msg in entry.iter_messages_mut() {
1606                    if matches!(msg, Message::Resolved) {
1607                        *msg = Message::Data(snapshot);
1608                        retains_needed += 1;
1609                    }
1610                }
1611            }
1612        });
1613        // Pause-buffer path.
1614        if let Some(rec) = s.nodes.get_mut(&node_id) {
1615            if let crate::node::PauseState::Paused { buffer, .. } = &mut rec.pause_state {
1616                for msg in &mut *buffer {
1617                    if matches!(msg, Message::Resolved) {
1618                        *msg = Message::Data(snapshot);
1619                        retains_needed += 1;
1620                    }
1621                }
1622            }
1623        }
1624        drop(s);
1625        // Each rewritten Resolved → Data adds a payload retain that
1626        // queue_notify would otherwise have taken at emit time. The
1627        // snapshot already owns one retain (taken when cache was
1628        // snapshotted); we need one fresh retain per rewrite.
1629        for _ in 0..retains_needed {
1630            self.binding.retain_handle(snapshot);
1631        }
1632    }
1633
1634    /// Equals check that crosses the binding boundary lock-released for
1635    /// `EqualsMode::Custom`. Caller must NOT hold the state lock.
1636    fn handles_equal_lock_released(&self, mode: EqualsMode, a: HandleId, b: HandleId) -> bool {
1637        if a == b {
1638            return true; // identity-on-handles always sufficient
1639        }
1640        if a == NO_HANDLE || b == NO_HANDLE {
1641            return false;
1642        }
1643        match mode {
1644            EqualsMode::Identity => false,
1645            EqualsMode::Custom(handle) => self.binding.custom_equals(handle, a, b),
1646        }
1647    }
1648
1649    /// Commit a DATA emission **without** equals substitution — used by
1650    /// `FnResult::Batch` processing where multi-message waves pass through
1651    /// verbatim per R1.3.2.d / R1.3.3.c. DIRTY auto-prefix respects
1652    /// R1.3.1.a condition (b): only queued if node not already dirty.
1653    ///
1654    /// Structurally identical to the DATA branch of [`Self::commit_emission`]
1655    /// but skips the Phase 2 equals check entirely.
1656    fn commit_emission_verbatim(&self, node_id: NodeId, new_handle: HandleId) {
1657        assert!(
1658            new_handle != NO_HANDLE,
1659            "NO_HANDLE is not a valid DATA payload (R1.2.4) for node {node_id:?}",
1660        );
1661
1662        let mut s = self.lock_state();
1663        let rec = s.require_node(node_id);
1664        if rec.terminal.is_some() {
1665            drop(s);
1666            self.binding.release_handle(new_handle);
1667            return;
1668        }
1669
1670        // R1.3.1.a condition (b): DIRTY only if not already dirty.
1671        let already_dirty = s.require_node(node_id).dirty;
1672        s.require_node_mut(node_id).dirty = true;
1673        if !already_dirty {
1674            self.queue_notify(&mut s, node_id, Message::Dirty);
1675        }
1676
1677        // Always DATA — no equals substitution for Batch emissions.
1678        // Q-beyond Sub-slice 1 (D108, 2026-05-09): wave_cache_snapshots
1679        // lives on per-thread WaveState. /qa F1 reverted (2026-05-10);
1680        // D252 (S5) collapsed to one-Core-per-OS-thread `Cell<u64>` —
1681        // `in_tick` is read on the wave-owner thread.
1682        let current_cache = s.require_node(node_id).cache;
1683        let snapshot_taken = if self.in_tick() && current_cache != NO_HANDLE {
1684            use std::collections::hash_map::Entry;
1685            with_wave_state(|ws| match ws.wave_cache_snapshots.entry(node_id) {
1686                Entry::Vacant(slot) => {
1687                    slot.insert(current_cache);
1688                    true
1689                }
1690                Entry::Occupied(_) => false,
1691            })
1692        } else {
1693            false
1694        };
1695        s.require_node_mut(node_id).cache = new_handle;
1696        if current_cache != NO_HANDLE && !snapshot_taken {
1697            self.binding.release_handle(current_cache);
1698        }
1699        // Slice E1: replay buffer push (R2.6.5 / Lock 6.G).
1700        self.push_replay_buffer(&mut s, node_id, new_handle);
1701        // Slice G QA fix (A2, 2026-05-07) / D1 patch (2026-05-09): mark
1702        // tier3_emitted_this_wave on the per-thread tracker even on the
1703        // verbatim path. A subsequent commit_emission at the same node
1704        // in the same wave needs this flag to detect multi-emit and
1705        // skip equals substitution; without it, a Batch-then-standard
1706        // sequence would queue Resolved into a wave that already has
1707        // Data — violating R1.3.3.a. The Batch path itself still
1708        // passes verbatim per R1.3.3.c (we don't re-run equals here);
1709        // we just record that "this node has emitted tier-3 in this
1710        // wave."
1711        tier3_mark(node_id);
1712        self.queue_notify(&mut s, node_id, Message::Data(new_handle));
1713        // Propagate to children
1714        let child_ids: Vec<NodeId> = s
1715            .children
1716            .get(&node_id)
1717            .map(|c| c.iter().copied().collect())
1718            .unwrap_or_default();
1719        for child_id in child_ids {
1720            let dep_idx = s.require_node(child_id).dep_index_of(node_id);
1721            if let Some(idx) = dep_idx {
1722                self.deliver_data_to_consumer(&mut s, child_id, idx, new_handle);
1723            }
1724        }
1725    }
1726
1727    /// Slice E1 (R2.6.5 / Lock 6.G): push a DATA handle into the node's
1728    /// replay buffer if opted in. Evicts oldest if cap exceeded; takes a
1729    /// fresh retain on push. RESOLVED is NOT buffered per canonical
1730    /// "DATA only" — call sites only invoke this for Data emissions.
1731    ///
1732    /// Evicted handle is queued into `cps.deferred_handle_releases`
1733    /// (released lock-released at flush time) per the binding-boundary
1734    /// lock-release discipline — `release_handle` may re-enter Core via
1735    /// finalizers and must not run while the state lock is held
1736    /// (QA A3, 2026-05-07). Q2 (2026-05-09): the queue moved to
1737    /// CrossPartitionState; this fn acquires `cross_partition` only
1738    /// when an eviction actually happens (the common case is no
1739    /// eviction → no second-mutex acquire).
1740    fn push_replay_buffer(&self, s: &mut CoreState, node_id: NodeId, new_handle: HandleId) {
1741        let rec = s.require_node_mut(node_id);
1742        let cap = match rec.replay_buffer_cap {
1743            Some(c) if c > 0 => c,
1744            _ => return,
1745        };
1746        self.binding.retain_handle(new_handle);
1747        rec.replay_buffer.push_back(new_handle);
1748        let evicted = if rec.replay_buffer.len() > cap {
1749            rec.replay_buffer.pop_front()
1750        } else {
1751            None
1752        };
1753        if let Some(h) = evicted {
1754            with_wave_state(|ws| ws.deferred_handle_releases.push(h));
1755        }
1756    }
1757
1758    // ===================================================================
1759    // Operator dispatch (Slice C-1, D009).
1760    //
1761    // `fire_operator` is the entry point for nodes whose `kind` is
1762    // `NodeKind::Operator(_)`. It branches on the `OperatorOp` discriminant
1763    // to per-operator helpers that snapshot inputs under the lock, drop the
1764    // lock to call the binding's bulk projection FFI, and reacquire to
1765    // apply emissions via `commit_emission_verbatim` (no per-item equals
1766    // dedup at the wire — operator output passes verbatim per the same
1767    // R1.3.2.d / R1.3.3.c rule that governs `FnResult::Batch`).
1768    //
1769    // **Refcount discipline:** inputs sourced from `dep_records[i].data_batch`
1770    // share retains owned by the wave's data-batch slot (released at
1771    // wave-end rotation in `clear_wave_state`). Operators that emit those
1772    // handles unchanged (`Filter`, `DistinctUntilChanged`, `Pairwise`'s
1773    // `prev` carry-over) take an additional retain via `retain_handle`
1774    // before passing to `commit_emission_verbatim` — the cache slot owns
1775    // its own share, independent of the data-batch slot's. Operators that
1776    // produce fresh handles (`Map` / `Scan` / `Reduce` / `Pairwise`'s
1777    // packed tuples) receive retains pre-bumped by the binding's bulk-
1778    // projection method.
1779    // ===================================================================
1780
1781    /// Operator dispatch entry. Pre-checks (terminal short-circuit, first-
1782    /// run gate accounting for `partial`, terminal-aware fire for `Reduce`)
1783    /// happen here; per-operator behavior lives in the `fire_op_*` helpers.
1784    fn fire_operator(&self, node_id: NodeId, op: OperatorOp) {
1785        // Phase 1 (lock-held): remove from pending_fires, evaluate skip.
1786        // Q-beyond Sub-slice 2 (D108, 2026-05-09): pending_fires lives on
1787        // per-thread WaveState; state lock + WaveState borrow are
1788        // independent.
1789        let proceed = {
1790            let s = self.lock_state();
1791            with_wave_state(|ws| {
1792                ws.pending_fires.remove(&node_id);
1793            });
1794            let rec = s.require_node(node_id);
1795            if rec.terminal.is_some() {
1796                false
1797            } else {
1798                // First-run gate (R2.5.3 / R5.4). Partial-mode operators
1799                // (D011) opt out of the gate; otherwise we wait for every
1800                // dep to have delivered at least one real handle. Terminal-
1801                // aware operators (currently `Reduce`) additionally count a
1802                // dep terminal as "real input" so they can fire on
1803                // upstream COMPLETE-without-DATA and emit the seed.
1804                let has_real_input = !rec.has_sentinel_deps()
1805                    || rec.dep_records.iter().any(|dr| dr.terminal.is_some());
1806                rec.partial || has_real_input
1807            }
1808        };
1809        if !proceed {
1810            return;
1811        }
1812
1813        // A6 (Slice F, 2026-05-07): track operator fire on the
1814        // `currently_firing` stack so a binding-side project/predicate/fold
1815        // FFI callback that re-enters `Core::set_deps(node_id, ...)` is
1816        // rejected with `SetDepsError::ReentrantOnFiringNode`. Drop pops
1817        // the stack on panic too.
1818        let _firing = FiringGuard::new(self, node_id);
1819
1820        match op {
1821            OperatorOp::Map { fn_id } => self.fire_op_map(node_id, fn_id),
1822            OperatorOp::Filter { fn_id } => self.fire_op_filter(node_id, fn_id),
1823            OperatorOp::Scan { fn_id, .. } => self.fire_op_scan(node_id, fn_id),
1824            OperatorOp::Reduce { fn_id, .. } => self.fire_op_reduce(node_id, fn_id),
1825            OperatorOp::DistinctUntilChanged { equals_fn_id } => {
1826                self.fire_op_distinct(node_id, equals_fn_id);
1827            }
1828            OperatorOp::Pairwise { fn_id } => self.fire_op_pairwise(node_id, fn_id),
1829            OperatorOp::Combine { pack_fn } => self.fire_op_combine(node_id, pack_fn),
1830            OperatorOp::WithLatestFrom { pack_fn } => {
1831                self.fire_op_with_latest_from(node_id, pack_fn);
1832            }
1833            OperatorOp::Merge => self.fire_op_merge(node_id),
1834            OperatorOp::Take { count } => self.fire_op_take(node_id, count),
1835            OperatorOp::Skip { count } => self.fire_op_skip(node_id, count),
1836            OperatorOp::TakeWhile { fn_id } => self.fire_op_take_while(node_id, fn_id),
1837            // The variant carries `default` for `register_operator`'s
1838            // `make_op_scratch` path; once registered, the live default
1839            // is read from `LastState::default` inside `fire_op_last`.
1840            OperatorOp::Last { .. } => self.fire_op_last(node_id),
1841            OperatorOp::Tap { fn_id } => self.fire_op_tap(node_id, fn_id),
1842            OperatorOp::TapFirst { fn_id } => self.fire_op_tap_first(node_id, fn_id),
1843            OperatorOp::Valve => self.fire_op_valve(node_id),
1844            OperatorOp::Settle {
1845                quiet_waves,
1846                max_waves,
1847            } => self.fire_op_settle(node_id, quiet_waves, max_waves),
1848        }
1849    }
1850
1851    /// Snapshot the operator's single dep batch (transform constraint —
1852    /// R5.7 single-dep). Returns `(inputs, terminal)` where `inputs` is a
1853    /// fresh `Vec<HandleId>` (no retains) and `terminal` reflects
1854    /// `dep_records[0].terminal` at snapshot time.
1855    fn snapshot_op_dep0(&self, node_id: NodeId) -> (Vec<HandleId>, Option<TerminalKind>) {
1856        let s = self.lock_state();
1857        let rec = s.require_node(node_id);
1858        debug_assert!(
1859            !rec.dep_records.is_empty(),
1860            "transform operator must have ≥1 dep"
1861        );
1862        let dr = &rec.dep_records[0];
1863        (dr.data_batch.iter().copied().collect(), dr.terminal)
1864    }
1865
1866    /// Emit DIRTY (if not already dirty) followed by RESOLVED. Used by
1867    /// silent-drop operators (Filter / DistinctUntilChanged / Pairwise)
1868    /// when a wave's inputs all suppress and the operator needs to settle
1869    /// the wave for its subscribers (D018 — let DIRTY ride; queue RESOLVED
1870    /// on full-reject).
1871    fn settle_dirty_resolved(&self, node_id: NodeId) {
1872        let mut s = self.lock_state();
1873        if s.require_node(node_id).terminal.is_some() {
1874            return;
1875        }
1876        let already_dirty = s.require_node(node_id).dirty;
1877        s.require_node_mut(node_id).dirty = true;
1878        if !already_dirty {
1879            self.queue_notify(&mut s, node_id, Message::Dirty);
1880        }
1881        // Slice G: skip Resolved if pending_notify already has a tier-3
1882        // message — adding Resolved would violate R1.3.3.a.
1883        // Q-beyond Sub-slice 2 (D108, 2026-05-09): pending_notify lives
1884        // on per-thread WaveState; borrow scoped so queue_notify can
1885        // re-borrow.
1886        let already_tier3 = with_wave_state(|ws| {
1887            ws.pending_notify
1888                .get(&node_id)
1889                .is_some_and(|entry| entry.iter_messages().any(|m| m.tier() == 3))
1890        });
1891        if !already_tier3 {
1892            self.queue_notify(&mut s, node_id, Message::Resolved);
1893        }
1894    }
1895
1896    /// `OperatorOp::Map` dispatch.
1897    fn fire_op_map(&self, node_id: NodeId, fn_id: crate::handle::FnId) {
1898        let (inputs, _terminal) = self.snapshot_op_dep0(node_id);
1899        // Mark fired regardless of input count (activation gate already
1900        // satisfied or partial-mode).
1901        {
1902            let mut s = self.lock_state();
1903            s.require_node_mut(node_id).has_fired_once = true;
1904        }
1905        if inputs.is_empty() {
1906            return;
1907        }
1908        // Phase 2 (lock-released): bulk project. Binding returns one
1909        // handle per input, each with a retain share already taken.
1910        let outputs = self.binding.project_each(fn_id, &inputs);
1911        // Phase 3: emit each output. `commit_emission_verbatim` consumes
1912        // the retain into the cache slot (and releases the prior cache
1913        // handle internally).
1914        for h in outputs {
1915            self.commit_emission_verbatim(node_id, h);
1916        }
1917    }
1918
1919    /// `OperatorOp::Filter` dispatch (D012/D018).
1920    fn fire_op_filter(&self, node_id: NodeId, fn_id: crate::handle::FnId) {
1921        let (inputs, _terminal) = self.snapshot_op_dep0(node_id);
1922        {
1923            let mut s = self.lock_state();
1924            s.require_node_mut(node_id).has_fired_once = true;
1925        }
1926        if inputs.is_empty() {
1927            return;
1928        }
1929        // Phase 2: predicate per input.
1930        let pass = self.binding.predicate_each(fn_id, &inputs);
1931        // Slice V2: promoted from debug_assert! — binding contract violation
1932        // should fail loud in release builds too.
1933        assert!(
1934            pass.len() == inputs.len(),
1935            "predicate_each returned {} bools for {} inputs",
1936            pass.len(),
1937            inputs.len()
1938        );
1939        // Phase 3: emit passing items verbatim. Take a fresh retain for
1940        // each — the data_batch slot still owns its retain (released at
1941        // wave-end rotation), and the cache slot needs its own.
1942        let mut emitted = 0usize;
1943        for (i, &h) in inputs.iter().enumerate() {
1944            if pass.get(i).copied().unwrap_or(false) {
1945                self.binding.retain_handle(h);
1946                self.commit_emission_verbatim(node_id, h);
1947                emitted += 1;
1948            }
1949        }
1950        // D018: full-reject settles with DIRTY+RESOLVED.
1951        if emitted == 0 {
1952            self.settle_dirty_resolved(node_id);
1953        }
1954    }
1955
1956    /// `OperatorOp::Scan` dispatch — left-fold emitting each new acc.
1957    fn fire_op_scan(&self, node_id: NodeId, fn_id: crate::handle::FnId) {
1958        use crate::op_state::ScanState;
1959        let (inputs, _terminal) = self.snapshot_op_dep0(node_id);
1960        let acc = {
1961            let s = self.lock_state();
1962            scratch_ref::<ScanState>(&s, node_id).acc
1963        };
1964        {
1965            let mut s = self.lock_state();
1966            s.require_node_mut(node_id).has_fired_once = true;
1967        }
1968        if inputs.is_empty() {
1969            return;
1970        }
1971        // Phase 2: fold each input through. Returns N new handles, each
1972        // with a fresh retain.
1973        let new_states = self.binding.fold_each(fn_id, acc, &inputs);
1974        // Slice V2: promoted from debug_assert! — binding contract violation.
1975        assert!(
1976            new_states.len() == inputs.len(),
1977            "fold_each returned {} accs for {} inputs",
1978            new_states.len(),
1979            inputs.len()
1980        );
1981        // Phase 3a: update ScanState.acc to the LAST new acc. Take an
1982        // extra retain for the slot; release the prior acc's slot retain.
1983        let last_acc = new_states.last().copied();
1984        if let Some(last) = last_acc {
1985            let prev_acc = {
1986                let mut s = self.lock_state();
1987                let scratch = scratch_mut::<ScanState>(&mut s, node_id);
1988                let prev = scratch.acc;
1989                scratch.acc = last;
1990                prev
1991            };
1992            // Take the slot's retain on the new acc.
1993            self.binding.retain_handle(last);
1994            // Release the prior slot's retain (post-lock to keep binding
1995            // free to re-enter Core safely).
1996            if prev_acc != crate::handle::NO_HANDLE {
1997                self.binding.release_handle(prev_acc);
1998            }
1999        }
2000        // Phase 3b: emit each intermediate acc verbatim. `new_states`
2001        // entries each carry one retain from `fold_each`; that retain is
2002        // consumed by `commit_emission_verbatim` into the cache slot.
2003        for h in new_states {
2004            self.commit_emission_verbatim(node_id, h);
2005        }
2006    }
2007
2008    /// `OperatorOp::Reduce` dispatch — accumulates silently; emits acc on
2009    /// upstream COMPLETE (cascades ERROR verbatim).
2010    fn fire_op_reduce(&self, node_id: NodeId, fn_id: crate::handle::FnId) {
2011        use crate::op_state::ReduceState;
2012        let (inputs, terminal) = self.snapshot_op_dep0(node_id);
2013        let acc = {
2014            let s = self.lock_state();
2015            scratch_ref::<ReduceState>(&s, node_id).acc
2016        };
2017        {
2018            let mut s = self.lock_state();
2019            s.require_node_mut(node_id).has_fired_once = true;
2020        }
2021        // Phase 2: accumulate (silent — no per-input emit).
2022        let new_states = if inputs.is_empty() {
2023            SmallVec::<[HandleId; 1]>::new()
2024        } else {
2025            self.binding.fold_each(fn_id, acc, &inputs)
2026        };
2027        // Slice V2: promoted from debug_assert! — binding contract violation.
2028        assert!(
2029            new_states.len() == inputs.len(),
2030            "fold_each returned {} accs for {} inputs",
2031            new_states.len(),
2032            inputs.len()
2033        );
2034        // Update ReduceState.acc to last new acc; release intermediate
2035        // states (we don't emit them) and the prior acc's slot retain.
2036        let last_acc = new_states.last().copied();
2037        let intermediates_to_release: Vec<HandleId> = if new_states.len() > 1 {
2038            new_states[..new_states.len() - 1].to_vec()
2039        } else {
2040            Vec::new()
2041        };
2042        let prev_acc_to_release = if let Some(last) = last_acc {
2043            let prev_acc = {
2044                let mut s = self.lock_state();
2045                let scratch = scratch_mut::<ReduceState>(&mut s, node_id);
2046                let prev = scratch.acc;
2047                scratch.acc = last;
2048                prev
2049            };
2050            self.binding.retain_handle(last);
2051            if prev_acc == crate::handle::NO_HANDLE {
2052                None
2053            } else {
2054                Some(prev_acc)
2055            }
2056        } else {
2057            None
2058        };
2059        // Release intermediate fold results (Reduce only emits the LAST,
2060        // but only on terminal). Each was retained by `fold_each`.
2061        for h in intermediates_to_release {
2062            self.binding.release_handle(h);
2063        }
2064        if let Some(h) = prev_acc_to_release {
2065            self.binding.release_handle(h);
2066        }
2067
2068        // Phase 3: emit on terminal.
2069        match terminal {
2070            None => {
2071                // Still accumulating; no emit. Subscribers see no message
2072                // for this wave (silent accumulation). The first wave that
2073                // pushes Reduce to fire produces a Dirty entry on the
2074                // upstream's commit, but Reduce itself doesn't queue any
2075                // tier-3 since R5 silently absorbs. v1: leave the
2076                // post-drain auto-resolve sweep to settle nothing —
2077                // pending_notify has no entry for Reduce so the sweep is
2078                // a no-op.
2079            }
2080            Some(TerminalKind::Complete) => {
2081                // Read the live acc (may be the seed if no DATA arrived)
2082                // and emit Data(acc) + Complete.
2083                let final_acc = {
2084                    let s = self.lock_state();
2085                    scratch_ref::<ReduceState>(&s, node_id).acc
2086                };
2087                if final_acc != crate::handle::NO_HANDLE {
2088                    // Emission needs its own retain (slot's retain is
2089                    // owned by ReduceState.acc until reset/Drop).
2090                    self.binding.retain_handle(final_acc);
2091                    self.commit_emission_verbatim(node_id, final_acc);
2092                }
2093                self.complete(node_id);
2094            }
2095            Some(TerminalKind::Error(h)) => {
2096                // Core::error transfers the caller's share into the
2097                // cascade (node.terminal + per-child dep_terminal slots);
2098                // no release at the error() boundary. Take a fresh share
2099                // here so the cascade owns it independently of the
2100                // dep_records[0].terminal slot's share.
2101                self.binding.retain_handle(h);
2102                self.error(node_id, h);
2103            }
2104        }
2105    }
2106
2107    /// `OperatorOp::DistinctUntilChanged` dispatch.
2108    fn fire_op_distinct(&self, node_id: NodeId, equals_fn_id: crate::handle::FnId) {
2109        use crate::op_state::DistinctState;
2110        let (inputs, _terminal) = self.snapshot_op_dep0(node_id);
2111        let mut prev = {
2112            let s = self.lock_state();
2113            scratch_ref::<DistinctState>(&s, node_id).prev
2114        };
2115        {
2116            let mut s = self.lock_state();
2117            s.require_node_mut(node_id).has_fired_once = true;
2118        }
2119        if inputs.is_empty() {
2120            return;
2121        }
2122        // Take a working-copy retain on the initial prev so both the loop
2123        // (which releases old_prev on each non-equal item) and phase 3
2124        // (which releases the slot's original handle) each have their own
2125        // share. Without this, the loop's release of old_prev (== original
2126        // DistinctState.prev) double-releases against phase 3's stale_slot
2127        // release.
2128        if prev != crate::handle::NO_HANDLE {
2129            self.binding.retain_handle(prev);
2130        }
2131        // Phase 2: per-input equals(prev, current). Each non-equal input
2132        // is emitted and becomes the new prev. Equals fn_id reuses
2133        // `BindingBoundary::custom_equals`.
2134        let mut emitted = 0usize;
2135        for &h in &inputs {
2136            let equal = if prev == crate::handle::NO_HANDLE {
2137                false
2138            } else if prev == h {
2139                true
2140            } else {
2141                self.binding.custom_equals(equals_fn_id, prev, h)
2142            };
2143            if !equal {
2144                // Emit this input verbatim.
2145                self.binding.retain_handle(h);
2146                self.commit_emission_verbatim(node_id, h);
2147                // Update prev: take retain on new prev, release old
2148                // (working-copy retain from above or from prior iteration).
2149                self.binding.retain_handle(h);
2150                let old_prev = prev;
2151                prev = h;
2152                if old_prev != crate::handle::NO_HANDLE {
2153                    self.binding.release_handle(old_prev);
2154                }
2155                emitted += 1;
2156            }
2157        }
2158        // Phase 3: persist prev into DistinctState.prev slot. Release the
2159        // slot's original retain (stale_slot) — this is the slot-owned
2160        // share, independent of the working-copy share released in the
2161        // loop above.
2162        {
2163            let mut s = self.lock_state();
2164            let scratch = scratch_mut::<DistinctState>(&mut s, node_id);
2165            let stale_slot = scratch.prev;
2166            scratch.prev = prev;
2167            if stale_slot != prev && stale_slot != crate::handle::NO_HANDLE {
2168                drop(s);
2169                self.binding.release_handle(stale_slot);
2170            }
2171        }
2172        // Release the working-copy retain on the final prev if it was
2173        // never released in the loop (i.e. no non-equal items passed,
2174        // prev == original). In that case stale_slot == prev, so phase 3
2175        // didn't release it either — but the working-copy retain is still
2176        // outstanding. Release it now.
2177        if emitted == 0 && prev != crate::handle::NO_HANDLE {
2178            self.binding.release_handle(prev);
2179        }
2180        if emitted == 0 {
2181            self.settle_dirty_resolved(node_id);
2182        }
2183    }
2184
2185    /// `OperatorOp::Pairwise` dispatch — emits `(prev, current)` tuples
2186    /// starting after the second value (first input swallowed, sets `prev`).
2187    fn fire_op_pairwise(&self, node_id: NodeId, fn_id: crate::handle::FnId) {
2188        use crate::op_state::PairwiseState;
2189        let (inputs, _terminal) = self.snapshot_op_dep0(node_id);
2190        let mut prev = {
2191            let s = self.lock_state();
2192            scratch_ref::<PairwiseState>(&s, node_id).prev
2193        };
2194        {
2195            let mut s = self.lock_state();
2196            s.require_node_mut(node_id).has_fired_once = true;
2197        }
2198        if inputs.is_empty() {
2199            return;
2200        }
2201        let mut emitted = 0usize;
2202        for &h in &inputs {
2203            if prev == crate::handle::NO_HANDLE {
2204                // First-ever value — swallow, set prev. Retain for the
2205                // PairwiseState.prev slot (persisted in phase 3 below).
2206                self.binding.retain_handle(h);
2207                prev = h;
2208                continue;
2209            }
2210            // Pack (prev, current) into a tuple handle. Binding returns a
2211            // fresh retain on the packed handle.
2212            let packed = self.binding.pairwise_pack(fn_id, prev, h);
2213            self.commit_emission_verbatim(node_id, packed);
2214            // Advance prev: take retain on h, release old prev.
2215            self.binding.retain_handle(h);
2216            let old_prev = prev;
2217            prev = h;
2218            self.binding.release_handle(old_prev);
2219            emitted += 1;
2220        }
2221        // Persist prev into PairwiseState.prev slot.
2222        {
2223            let mut s = self.lock_state();
2224            let scratch = scratch_mut::<PairwiseState>(&mut s, node_id);
2225            let stale_slot = scratch.prev;
2226            scratch.prev = prev;
2227            if stale_slot != prev && stale_slot != crate::handle::NO_HANDLE {
2228                drop(s);
2229                self.binding.release_handle(stale_slot);
2230            }
2231        }
2232        if emitted == 0 {
2233            self.settle_dirty_resolved(node_id);
2234        }
2235    }
2236
2237    // =================================================================
2238    // Slice C-2: multi-dep combinator operators (D020)
2239    // =================================================================
2240
2241    /// Snapshot all deps' "latest" handle for multi-dep combinators.
2242    /// For each dep: returns `data_batch.last()` if non-empty (dep fired
2243    /// this wave), else `prev_data` (last handle from previous wave).
2244    /// Also returns whether dep[0] (primary) had DATA this wave —
2245    /// needed by `fire_op_with_latest_from`.
2246    fn snapshot_op_all_latest(&self, node_id: NodeId) -> (SmallVec<[HandleId; 4]>, bool) {
2247        let s = self.lock_state();
2248        let rec = s.require_node(node_id);
2249        let primary_fired = rec
2250            .dep_records
2251            .first()
2252            .is_some_and(|dr| !dr.data_batch.is_empty());
2253        let latest: SmallVec<[HandleId; 4]> = rec
2254            .dep_records
2255            .iter()
2256            .map(|dr| dr.data_batch.last().copied().unwrap_or(dr.prev_data))
2257            .collect();
2258        (latest, primary_fired)
2259    }
2260
2261    /// `OperatorOp::Combine` dispatch — N-dep combineLatest. Packs the
2262    /// latest handle per dep into a tuple via `pack_tuple`, emits on
2263    /// any dep fire. First-run gate (R2.5.3, partial: false) guarantees
2264    /// all deps have a real handle on first fire. Post-warmup INVALIDATE
2265    /// guard: if any dep's prev_data was cleared, settles with RESOLVED
2266    /// instead of packing a NO_HANDLE into the tuple.
2267    fn fire_op_combine(&self, node_id: NodeId, pack_fn: crate::handle::FnId) {
2268        let (latest, _primary_fired) = self.snapshot_op_all_latest(node_id);
2269        {
2270            let mut s = self.lock_state();
2271            s.require_node_mut(node_id).has_fired_once = true;
2272        }
2273        // Post-warmup INVALIDATE guard: a dep may have been invalidated
2274        // (prev_data cleared to NO_HANDLE) and not yet re-delivered.
2275        if latest.contains(&crate::handle::NO_HANDLE) {
2276            self.settle_dirty_resolved(node_id);
2277            return;
2278        }
2279        let tuple_handle = self.binding.pack_tuple(pack_fn, &latest);
2280        self.commit_emission_verbatim(node_id, tuple_handle);
2281    }
2282
2283    /// `OperatorOp::WithLatestFrom` dispatch — 2-dep, fire-on-primary-only
2284    /// (D021 / Phase 10.5). Emits `[primary, secondary]` pair only when
2285    /// dep[0] (primary) has DATA in the wave. If only dep[1] fires →
2286    /// RESOLVED. Post-warmup INVALIDATE guard: if secondary latest is
2287    /// `NO_HANDLE` (INVALIDATE cleared it), settles with RESOLVED.
2288    fn fire_op_with_latest_from(&self, node_id: NodeId, pack_fn: crate::handle::FnId) {
2289        let (latest, primary_fired) = self.snapshot_op_all_latest(node_id);
2290        let first_fire = {
2291            let mut s = self.lock_state();
2292            let rec = s.require_node_mut(node_id);
2293            let was_first = !rec.has_fired_once;
2294            rec.has_fired_once = true;
2295            was_first
2296        };
2297        // On first fire (gate release), always emit — the first-run gate
2298        // guarantees both deps have values (via prev_data fallback in
2299        // snapshot). On subsequent fires, only emit when primary fires.
2300        if !first_fire && !primary_fired {
2301            // Secondary-only update — no downstream DATA.
2302            self.settle_dirty_resolved(node_id);
2303            return;
2304        }
2305        // Post-warmup INVALIDATE guard: secondary may have been invalidated
2306        // (prev_data cleared to NO_HANDLE) and not yet re-delivered.
2307        debug_assert!(latest.len() == 2, "withLatestFrom requires exactly 2 deps");
2308        if latest[1] == crate::handle::NO_HANDLE {
2309            self.settle_dirty_resolved(node_id);
2310            return;
2311        }
2312        let tuple_handle = self.binding.pack_tuple(pack_fn, &latest);
2313        self.commit_emission_verbatim(node_id, tuple_handle);
2314    }
2315
2316    /// `OperatorOp::Merge` dispatch — N-dep, forward all DATA handles
2317    /// verbatim (D022). Zero FFI on fire: no transformation. Each dep's
2318    /// batch handles are collected, retained, and emitted individually.
2319    fn fire_op_merge(&self, node_id: NodeId) {
2320        // Collect all batch handles from all deps (flat).
2321        let all_handles: Vec<HandleId> = {
2322            let s = self.lock_state();
2323            let rec = s.require_node(node_id);
2324            rec.dep_records
2325                .iter()
2326                .flat_map(|dr| dr.data_batch.iter().copied())
2327                .collect()
2328        };
2329        {
2330            let mut s = self.lock_state();
2331            s.require_node_mut(node_id).has_fired_once = true;
2332        }
2333        if all_handles.is_empty() {
2334            // All deps settled RESOLVED this wave — no DATA to forward.
2335            self.settle_dirty_resolved(node_id);
2336            return;
2337        }
2338        // Emit each handle verbatim. Take a fresh retain per handle
2339        // (independent of the dep batch's retain which gets released at
2340        // wave-end). Matches Filter's discipline for passing inputs.
2341        for &h in &all_handles {
2342            self.binding.retain_handle(h);
2343            self.commit_emission_verbatim(node_id, h);
2344        }
2345    }
2346
2347    // =================================================================
2348    // Slice C-3: flow operators (D024)
2349    // =================================================================
2350
2351    /// `OperatorOp::Take` dispatch — emits the first `count` DATA values
2352    /// then self-completes via `Core::complete`. When `count == 0`, the
2353    /// first fire emits zero items then immediately self-completes
2354    /// (D027). Cross-wave counter lives in
2355    /// [`TakeState::count_emitted`](super::op_state::TakeState::count_emitted).
2356    fn fire_op_take(&self, node_id: NodeId, count: u32) {
2357        use crate::op_state::TakeState;
2358        let (inputs, terminal) = self.snapshot_op_dep0(node_id);
2359        // Snapshot current counter; mark fired regardless of input count
2360        // (activation gate already satisfied or partial-mode).
2361        let mut count_emitted = {
2362            let s = self.lock_state();
2363            scratch_ref::<TakeState>(&s, node_id).count_emitted
2364        };
2365        {
2366            let mut s = self.lock_state();
2367            s.require_node_mut(node_id).has_fired_once = true;
2368        }
2369        // Already at quota before any input this wave — self-complete
2370        // immediately. Covers `count == 0` (first-fire short-circuit) and
2371        // any defensive re-entry after the terminal-skip in `fire_operator`
2372        // already guards against double-complete.
2373        if count_emitted >= count {
2374            self.complete(node_id);
2375            return;
2376        }
2377        // Per-input emission loop. Each pass takes a fresh retain for the
2378        // cache slot; data_batch slot's retain is released at wave-end
2379        // rotation independently.
2380        for &h in &inputs {
2381            self.binding.retain_handle(h);
2382            self.commit_emission_verbatim(node_id, h);
2383            count_emitted = count_emitted.saturating_add(1);
2384            if count_emitted >= count {
2385                break;
2386            }
2387        }
2388        // Persist the updated counter.
2389        {
2390            let mut s = self.lock_state();
2391            scratch_mut::<TakeState>(&mut s, node_id).count_emitted = count_emitted;
2392        }
2393        // Self-complete if we hit the quota this wave. Upstream COMPLETE
2394        // (terminal == Some(Complete)) without us hitting the count
2395        // propagates via the standard auto-cascade — we don't intercept it.
2396        if count_emitted >= count {
2397            self.complete(node_id);
2398            return;
2399        }
2400        // If upstream is already Errored and we haven't hit count, the
2401        // standard cascade will propagate it. If the wave delivered no
2402        // inputs (e.g. RESOLVED from upstream), settle DIRTY+RESOLVED so
2403        // subscribers see the wave close.
2404        if inputs.is_empty() && terminal.is_none() {
2405            self.settle_dirty_resolved(node_id);
2406        }
2407    }
2408
2409    /// `OperatorOp::Skip` dispatch — drops the first `count` DATA values,
2410    /// then forwards the rest. Cross-wave counter lives in
2411    /// [`SkipState::count_skipped`](super::op_state::SkipState::count_skipped).
2412    /// On a wave where every input is still in the skip window, settles
2413    /// DIRTY+RESOLVED (D018 pattern) so subscribers see the wave close.
2414    fn fire_op_skip(&self, node_id: NodeId, count: u32) {
2415        use crate::op_state::SkipState;
2416        let (inputs, _terminal) = self.snapshot_op_dep0(node_id);
2417        let mut count_skipped = {
2418            let s = self.lock_state();
2419            scratch_ref::<SkipState>(&s, node_id).count_skipped
2420        };
2421        {
2422            let mut s = self.lock_state();
2423            s.require_node_mut(node_id).has_fired_once = true;
2424        }
2425        // No early-return on empty inputs: the post-loop `emitted == 0`
2426        // settle handles the empty-inputs case identically to the
2427        // all-swallowed-by-skip-window case (Slice C-3 /qa P6 — symmetry
2428        // with `fire_op_take`).
2429        let mut emitted = 0usize;
2430        for &h in &inputs {
2431            if count_skipped < count {
2432                count_skipped = count_skipped.saturating_add(1);
2433                // Drop this input — the data_batch slot still owns its
2434                // retain (released at wave-end rotation). No emission.
2435                continue;
2436            }
2437            // Past the skip window — emit verbatim. Take a fresh retain
2438            // for the cache slot.
2439            self.binding.retain_handle(h);
2440            self.commit_emission_verbatim(node_id, h);
2441            emitted += 1;
2442        }
2443        // Persist the updated counter.
2444        {
2445            let mut s = self.lock_state();
2446            scratch_mut::<SkipState>(&mut s, node_id).count_skipped = count_skipped;
2447        }
2448        if emitted == 0 {
2449            self.settle_dirty_resolved(node_id);
2450        }
2451    }
2452
2453    /// `OperatorOp::TakeWhile` dispatch — emits while the predicate
2454    /// holds; on the first `false`, emits any preceding passes from the
2455    /// same batch then self-completes via `Core::complete`. Reuses
2456    /// [`BindingBoundary::predicate_each`] (D029).
2457    fn fire_op_take_while(&self, node_id: NodeId, fn_id: crate::handle::FnId) {
2458        let (inputs, _terminal) = self.snapshot_op_dep0(node_id);
2459        {
2460            let mut s = self.lock_state();
2461            s.require_node_mut(node_id).has_fired_once = true;
2462        }
2463        if inputs.is_empty() {
2464            return;
2465        }
2466        // Phase 2: predicate per input.
2467        let pass = self.binding.predicate_each(fn_id, &inputs);
2468        // Slice V2: promoted from debug_assert! — binding contract violation
2469        // should fail loud in release builds too.
2470        assert!(
2471            pass.len() == inputs.len(),
2472            "predicate_each returned {} bools for {} inputs",
2473            pass.len(),
2474            inputs.len()
2475        );
2476        // Phase 3: emit each input until the first false; then
2477        // self-complete. `fire_operator`'s `terminal.is_some()`
2478        // short-circuit gates re-entry after the self-complete cascade
2479        // installs the terminal slot — no extra `done` flag needed.
2480        let mut emitted = 0usize;
2481        let mut first_false_seen = false;
2482        for (i, &h) in inputs.iter().enumerate() {
2483            if pass.get(i).copied().unwrap_or(false) {
2484                self.binding.retain_handle(h);
2485                self.commit_emission_verbatim(node_id, h);
2486                emitted += 1;
2487            } else {
2488                first_false_seen = true;
2489                break;
2490            }
2491        }
2492        if first_false_seen {
2493            self.complete(node_id);
2494            return;
2495        }
2496        if emitted == 0 {
2497            // Whole batch passed but was empty (impossible here since
2498            // inputs.is_empty() returned early above) — defensive only.
2499            self.settle_dirty_resolved(node_id);
2500        }
2501    }
2502
2503    /// `OperatorOp::Last` dispatch — buffers the latest DATA; emits
2504    /// `Data(latest)` (or `Data(default)` if no DATA arrived and a
2505    /// default was registered) then `Complete` on upstream COMPLETE.
2506    /// On upstream ERROR, propagates verbatim. Storage:
2507    /// [`LastState`](super::op_state::LastState).
2508    ///
2509    /// **Silent-buffer semantics (mirrors Reduce):** on a non-terminal
2510    /// wave (`terminal == None`), `fire_op_last` updates the buffered
2511    /// `latest` handle but produces NO downstream wire message —
2512    /// subscribers observe the operator only when upstream
2513    /// COMPLETE/ERROR triggers the terminal branch. Intermediate
2514    /// inputs from the dep's batch are dropped on the floor (their
2515    /// `data_batch` retains release at wave-end rotation
2516    /// independently). Per-wave settlement on intermediate waves is
2517    /// the canonical behavior for terminal-aware operators.
2518    fn fire_op_last(&self, node_id: NodeId) {
2519        use crate::op_state::LastState;
2520        let (inputs, terminal) = self.snapshot_op_dep0(node_id);
2521        {
2522            let mut s = self.lock_state();
2523            s.require_node_mut(node_id).has_fired_once = true;
2524        }
2525
2526        // Phase 2: buffer the latest input handle (if any). Retain new,
2527        // release old. data_batch slot's retain is released at wave-end
2528        // rotation independently — the LastState slot keeps its own
2529        // share so the value survives across waves.
2530        if let Some(&new_latest) = inputs.last() {
2531            let prev_latest = {
2532                let mut s = self.lock_state();
2533                let scratch = scratch_mut::<LastState>(&mut s, node_id);
2534                let prev = scratch.latest;
2535                scratch.latest = new_latest;
2536                prev
2537            };
2538            self.binding.retain_handle(new_latest);
2539            if prev_latest != crate::handle::NO_HANDLE {
2540                self.binding.release_handle(prev_latest);
2541            }
2542        }
2543
2544        // Phase 3: emit on terminal. Buffer-only fires (no terminal yet)
2545        // produce no downstream message — Reduce-style silent
2546        // accumulation. The post-drain auto-resolve sweep is a no-op
2547        // because pending_notify has no entry for Last.
2548        match terminal {
2549            None => {}
2550            Some(TerminalKind::Complete) => {
2551                // Read the live latest + default. If latest != NO_HANDLE,
2552                // emit it. Otherwise, if default != NO_HANDLE, emit default.
2553                // Otherwise, emit only Complete (empty stream, no default).
2554                let (latest, default) = {
2555                    let s = self.lock_state();
2556                    let scratch = scratch_ref::<LastState>(&s, node_id);
2557                    (scratch.latest, scratch.default)
2558                };
2559                let to_emit = if latest != crate::handle::NO_HANDLE {
2560                    Some(latest)
2561                } else if default != crate::handle::NO_HANDLE {
2562                    Some(default)
2563                } else {
2564                    None
2565                };
2566                if let Some(h) = to_emit {
2567                    // Emission needs its own retain — the LastState slot
2568                    // keeps its share until reset/Drop.
2569                    self.binding.retain_handle(h);
2570                    self.commit_emission_verbatim(node_id, h);
2571                }
2572                self.complete(node_id);
2573            }
2574            Some(TerminalKind::Error(h)) => {
2575                // Take a fresh share for the error cascade — the
2576                // dep_records[0].terminal slot keeps its own share
2577                // (released by reset_for_fresh_lifecycle / Drop).
2578                self.binding.retain_handle(h);
2579                self.error(node_id, h);
2580            }
2581        }
2582    }
2583
2584    // -----------------------------------------------------------------
2585    // Slice U: control operators — fire_op impls
2586    // -----------------------------------------------------------------
2587
2588    /// Tap — side-effect passthrough. Invoke tap fn on each DATA, then
2589    /// emit each input handle unchanged (zero allocation).
2590    fn fire_op_tap(&self, node_id: NodeId, fn_id: FnId) {
2591        let (inputs, terminal) = self.snapshot_op_dep0(node_id);
2592        {
2593            let mut s = self.lock_state();
2594            s.require_node_mut(node_id).has_fired_once = true;
2595        }
2596        if inputs.is_empty() {
2597            if terminal.is_none() {
2598                self.settle_dirty_resolved(node_id);
2599            }
2600        } else {
2601            for &h in &inputs {
2602                self.binding.invoke_tap_fn(fn_id, h);
2603                self.binding.retain_handle(h);
2604                self.commit_emission_verbatim(node_id, h);
2605            }
2606        }
2607        // Terminal forwarding.
2608        match terminal {
2609            None => {}
2610            Some(TerminalKind::Complete) => {
2611                self.binding.invoke_tap_complete_fn(fn_id);
2612                self.complete(node_id);
2613            }
2614            Some(TerminalKind::Error(h)) => {
2615                self.binding.invoke_tap_error_fn(fn_id, h);
2616                self.binding.retain_handle(h);
2617                self.error(node_id, h);
2618            }
2619        }
2620    }
2621
2622    /// TapFirst — one-shot side-effect on first DATA. After the first
2623    /// qualifying DATA, acts as pure passthrough.
2624    fn fire_op_tap_first(&self, node_id: NodeId, fn_id: FnId) {
2625        use crate::op_state::TapFirstState;
2626        let (inputs, terminal) = self.snapshot_op_dep0(node_id);
2627        {
2628            let mut s = self.lock_state();
2629            s.require_node_mut(node_id).has_fired_once = true;
2630        }
2631        if inputs.is_empty() {
2632            if terminal.is_none() {
2633                self.settle_dirty_resolved(node_id);
2634            }
2635        } else {
2636            let fired = {
2637                let s = self.lock_state();
2638                scratch_ref::<TapFirstState>(&s, node_id).fired
2639            };
2640            for &h in &inputs {
2641                if !fired {
2642                    self.binding.invoke_tap_fn(fn_id, h);
2643                    let mut s = self.lock_state();
2644                    scratch_mut::<TapFirstState>(&mut s, node_id).fired = true;
2645                }
2646                self.binding.retain_handle(h);
2647                self.commit_emission_verbatim(node_id, h);
2648            }
2649        }
2650        if let Some(TerminalKind::Complete) = terminal {
2651            self.complete(node_id);
2652        } else if let Some(TerminalKind::Error(h)) = terminal {
2653            self.binding.retain_handle(h);
2654            self.error(node_id, h);
2655        }
2656    }
2657
2658    /// Valve — conditional forward. dep[0]=source, dep[1]=control.
2659    /// When control is truthy, forwards source DATA; else RESOLVED.
2660    fn fire_op_valve(&self, node_id: NodeId) {
2661        // Snapshot both deps.
2662        let (src_inputs, src_terminal, ctrl_latest) = {
2663            let s = self.lock_state();
2664            let rec = s.require_node(node_id);
2665            debug_assert!(rec.dep_records.len() == 2, "valve must have exactly 2 deps");
2666            let dr0 = &rec.dep_records[0];
2667            let dr1 = &rec.dep_records[1];
2668            let src_inputs: Vec<HandleId> = dr0.data_batch.iter().copied().collect();
2669            let src_term = dr0.terminal;
2670            // Latest control: last of this wave's batch, or prev_data.
2671            let ctrl = dr1.data_batch.last().copied().unwrap_or(dr1.prev_data);
2672            (src_inputs, src_term, ctrl)
2673        };
2674        {
2675            let mut s = self.lock_state();
2676            s.require_node_mut(node_id).has_fired_once = true;
2677        }
2678
2679        // Source terminal forwarding (D3).
2680        if let Some(TerminalKind::Complete) = src_terminal {
2681            self.complete(node_id);
2682            return;
2683        }
2684        if let Some(TerminalKind::Error(h)) = src_terminal {
2685            self.binding.retain_handle(h);
2686            self.error(node_id, h);
2687            return;
2688        }
2689
2690        // Gate: NO_HANDLE means "gate closed" (control never sent DATA);
2691        // any real handle means "gate open". Proper value-level truthiness
2692        // would require BindingBoundary::is_truthy (deferred — D048).
2693        let gate_open = ctrl_latest != crate::handle::NO_HANDLE;
2694
2695        if !gate_open {
2696            self.settle_dirty_resolved(node_id);
2697            return;
2698        }
2699
2700        if src_inputs.is_empty() {
2701            // Control opened but no source DATA this wave. Re-emit
2702            // prev source value if available.
2703            let prev_src = {
2704                let s = self.lock_state();
2705                s.require_node(node_id).dep_records[0].prev_data
2706            };
2707            if prev_src == crate::handle::NO_HANDLE {
2708                self.settle_dirty_resolved(node_id);
2709            } else {
2710                self.binding.retain_handle(prev_src);
2711                self.commit_emission_verbatim(node_id, prev_src);
2712            }
2713        } else {
2714            for &h in &src_inputs {
2715                self.binding.retain_handle(h);
2716                self.commit_emission_verbatim(node_id, h);
2717            }
2718        }
2719    }
2720
2721    /// Settle — convergence detector. Forwards DATA, counts quiet waves,
2722    /// self-completes when converged.
2723    fn fire_op_settle(&self, node_id: NodeId, quiet_waves: u32, max_waves: Option<u32>) {
2724        use crate::op_state::SettleState;
2725        let (inputs, terminal) = self.snapshot_op_dep0(node_id);
2726        {
2727            let mut s = self.lock_state();
2728            s.require_node_mut(node_id).has_fired_once = true;
2729        }
2730
2731        // Terminal forwarding.
2732        if let Some(TerminalKind::Complete) = terminal {
2733            self.complete(node_id);
2734            return;
2735        }
2736        if let Some(TerminalKind::Error(h)) = terminal {
2737            self.binding.retain_handle(h);
2738            self.error(node_id, h);
2739            return;
2740        }
2741
2742        let saw_data = !inputs.is_empty();
2743
2744        // Forward all DATA.
2745        for &h in &inputs {
2746            self.binding.retain_handle(h);
2747            self.commit_emission_verbatim(node_id, h);
2748        }
2749
2750        // Update counters.
2751        let should_complete = {
2752            let mut s = self.lock_state();
2753            let scratch = scratch_mut::<SettleState>(&mut s, node_id);
2754            scratch.wave_count += 1;
2755            if saw_data {
2756                scratch.has_value = true;
2757                scratch.quiet_count = 0;
2758            } else {
2759                scratch.quiet_count += 1;
2760            }
2761            let settled = scratch.has_value && scratch.quiet_count >= quiet_waves;
2762            let exhausted = max_waves.is_some_and(|max| scratch.wave_count >= max);
2763            settled || exhausted
2764        };
2765
2766        if should_complete {
2767            self.complete(node_id);
2768        } else if !saw_data {
2769            self.settle_dirty_resolved(node_id);
2770        }
2771    }
2772
2773    pub(crate) fn deliver_data_to_consumer(
2774        &self,
2775        s: &mut CoreState,
2776        consumer_id: NodeId,
2777        dep_idx: usize,
2778        handle: HandleId,
2779    ) {
2780        // Retain the handle for the batch accumulation slot — each DATA
2781        // handle in `data_batch` owns a retain share, released at wave-end
2782        // rotation in `clear_wave_state`.
2783        self.binding.retain_handle(handle);
2784
2785        let is_dynamic;
2786        let is_state;
2787        let tracked_or_first_fire;
2788        // Slice F audit close (2026-05-07): default-mode pause suppression.
2789        // If the consumer is paused with `PausableMode::Default`, the
2790        // canonical-spec §2.6 behavior is to suppress fn-fire and consolidate
2791        // pause-window dep deliveries into one fn execution on RESUME.
2792        // Mark `pending_wave` on the pause state instead of adding to
2793        // `pending_fires`. The dep state still advances (the data_batch push
2794        // above is unchanged), and clear_wave_state still rotates the latest
2795        // dep DATA into prev_data — so when the fn ultimately fires on
2796        // RESUME, it sees the consolidated post-pause state.
2797        let suppressed_for_default_pause;
2798        {
2799            let consumer = s.require_node_mut(consumer_id);
2800            consumer.dep_records[dep_idx].data_batch.push(handle);
2801            consumer.dep_records[dep_idx].involved_this_wave = true;
2802            consumer.involved_this_wave = true;
2803            // §10.13 perf (D047): set received_mask bit on first DATA
2804            // delivery for this dep.
2805            if dep_idx < 64 {
2806                consumer.received_mask |= 1u64 << dep_idx;
2807                // §10.3 perf (Slice V1): set involved_mask bit for
2808                // O(1) per-dep involvement query during fire.
2809                consumer.involved_mask |= 1u64 << dep_idx;
2810            }
2811            is_dynamic = consumer.is_dynamic;
2812            is_state = consumer.is_state();
2813            tracked_or_first_fire = !consumer.has_fired_once || consumer.tracked.contains(&dep_idx);
2814            suppressed_for_default_pause = consumer.pause_state.is_paused()
2815                && consumer.pausable == crate::node::PausableMode::Default;
2816            if suppressed_for_default_pause {
2817                consumer.pause_state.mark_pending_wave();
2818            }
2819        }
2820        if suppressed_for_default_pause {
2821            // Default-mode pause: don't add to pending_fires; RESUME will
2822            // schedule one consolidated fire.
2823            return;
2824        }
2825        // Q-beyond Sub-slice 2 (D108, 2026-05-09): pending_fires lives on
2826        // per-thread WaveState. State lock + WaveState borrow are
2827        // independent.
2828        if is_state {
2829            // State nodes don't have deps; unreachable in practice.
2830        } else if is_dynamic {
2831            if tracked_or_first_fire {
2832                with_wave_state(|ws| {
2833                    ws.pending_fires.insert(consumer_id);
2834                });
2835            }
2836        } else {
2837            // Derived / Operator / Producer (Producer has no deps so won't
2838            // reach here, but the predicate-based dispatch handles it
2839            // uniformly).
2840            with_wave_state(|ws| {
2841                ws.pending_fires.insert(consumer_id);
2842            });
2843        }
2844    }
2845
2846    // -------------------------------------------------------------------
2847    // Subscriber notification
2848    // -------------------------------------------------------------------
2849
2850    /// Queue a wave-end message for `node_id`'s subscribers.
2851    ///
2852    /// **Revision-tracked sink-snapshot batches (Slice X4 / D2,
2853    /// 2026-05-08):** each push for a given node either appends the
2854    /// message to the open batch (if `NodeRecord::subscribers_revision`
2855    /// hasn't advanced since that batch opened — the common case — no
2856    /// extra allocation), or opens a fresh batch with a current sink
2857    /// snapshot frozen at the new revision. A sub installed mid-wave
2858    /// bumps `subscribers_revision`; the next `queue_notify` for the
2859    /// same node observes the bump and starts a new batch that includes
2860    /// the new sub. Pre-subscribe batches retain their original snapshot,
2861    /// so earlier emits flush to their original sink list — the new sub
2862    /// does NOT double-receive them via flush AND handshake replay,
2863    /// closing the late-subscriber + multi-emit-per-wave R1.3.5.a gap.
2864    ///
2865    /// Pause routing decision (R1.3.7.b tier table, §10.2 buffering):
2866    ///   Tier 3 (DATA / RESOLVED) and Tier 4 (INVALIDATE) buffer while
2867    ///   paused; all other tiers (DIRTY tier 1, PAUSE/RESUME tier 2,
2868    ///   COMPLETE/ERROR tier 5, TEARDOWN tier 6) bypass the buffer and
2869    ///   flush immediately. START (tier 0) is per-subscription and never
2870    ///   transits queue_notify.
2871    pub(crate) fn queue_notify(&self, s: &mut crate::node::St<'_>, node_id: NodeId, msg: Message) {
2872        // R1.3.3.a / R1.3.3.d (Slice G — re-added 2026-05-07): dev-mode
2873        // wave-content invariant assertion. The tier-3 slot at one node in
2874        // one wave is either ≥1 DATA or exactly 1 RESOLVED — never mixed,
2875        // never multiple RESOLVED. Slice G moved equals substitution from
2876        // per-emit to wave-end coalescing; this assert pins that the
2877        // dispatcher itself never queues a violating combination at the
2878        // queue_notify granularity. Resolved arrivals come from:
2879        //   1. The auto-resolve sweep in `drain_and_flush` (gates on
2880        //      `!any tier-3` so it can't add to a wave with Data).
2881        //   2. The wave-end equals-substitution pass (rewrites in place,
2882        //      doesn't go through queue_notify).
2883        // Both honor R1.3.3.a by construction post-Slice-G.
2884        // Q-beyond Sub-slice 2 (D108, 2026-05-09): pending_notify lives
2885        // on per-thread WaveState. The dev-mode invariant assertion
2886        // borrows WaveState briefly and drops before the rest of
2887        // queue_notify proceeds.
2888        #[cfg(debug_assertions)]
2889        if matches!(msg.tier(), 3) {
2890            with_wave_state(|ws| {
2891                if let Some(entry) = ws.pending_notify.get(&node_id) {
2892                    // Walk all batches' messages — R1.3.3.a is a per-node
2893                    // wave-content invariant, not per-batch (the X4 batches
2894                    // are subscriber-snapshot epochs; the protocol-level
2895                    // tier-3 invariant spans the whole wave for the node).
2896                    let has_data = entry.iter_messages().any(|m| matches!(m, Message::Data(_)));
2897                    let resolved_count = entry
2898                        .iter_messages()
2899                        .filter(|m| matches!(m, Message::Resolved))
2900                        .count();
2901                    let incoming_is_data = matches!(msg, Message::Data(_));
2902                    if incoming_is_data {
2903                        debug_assert!(
2904                            resolved_count == 0,
2905                            "R1.3.3.a violation at {node_id:?}: queueing Data into a \
2906                             wave that already contains Resolved — Slice G should have \
2907                             prevented this via wave-end coalescing"
2908                        );
2909                    } else {
2910                        debug_assert!(
2911                            !has_data,
2912                            "R1.3.3.a violation at {node_id:?}: queueing Resolved into a \
2913                             wave that already contains Data"
2914                        );
2915                        debug_assert!(
2916                            resolved_count == 0,
2917                            "R1.3.3.a violation at {node_id:?}: multiple Resolved in one \
2918                             wave at one node"
2919                        );
2920                    }
2921                }
2922            });
2923        }
2924
2925        let buffered_tier = matches!(msg.tier(), 3 | 4);
2926        let cap = s.shared.pause_buffer_cap;
2927
2928        // Pause-routing branch — handles its own retain/release and returns
2929        // before we touch `pending_notify`, so the rec borrow is contained.
2930        {
2931            let rec = s.require_node_mut(node_id);
2932            if rec.subscribers.is_empty() {
2933                return;
2934            }
2935            // Slice F audit close (2026-05-07); amended 2026-05-17 for
2936            // canonical §2.6 R2.6.0 ("Option A"). Pause routing depends on
2937            // mode:
2938            //   - `ResumeAll`: buffer tier-3/4 for verbatim replay on RESUME.
2939            //   - `Default` + STATE node (leaf source — no deps): a state
2940            //     node's value is intrinsic, NOT produced by an fn/dep
2941            //     settle pipeline. PAUSE/RESUME gating is fn/dep-pipeline-
2942            //     scoped only (R2.6.0). A leaf source that holds its own
2943            //     pause lock and then self-emits via a direct external
2944            //     `down([[DATA, v]])` is pushing OUTSIDE that pipeline, so
2945            //     the DATA MUST flush immediately (cache advances now, no
2946            //     PAUSE synthesized, nothing replayed on RESUME). Therefore
2947            //     Default-mode state nodes do NOT buffer — they fall
2948            //     through to the immediate queue path, matching the
2949            //     `@graphrefly/pure-ts` reference (only `pausable:
2950            //     "resumeAll"` buffers a leaf source's direct `down()`).
2951            //   - `Default` + COMPUTE node: suppression happens upstream at
2952            //     fn-fire scheduling (see `deliver_data_to_consumer`); no
2953            //     outgoing tier-3 is produced from this node while paused,
2954            //     so this branch is unreachable for compute-default-paused.
2955            //     Fallthrough to the non-paused queue path is fine.
2956            //   - `Off`: pause is ignored entirely — tier-3 flushes
2957            //     immediately. Fallthrough.
2958            let mode_buffers_tier3 = match rec.pausable {
2959                crate::node::PausableMode::ResumeAll => true,
2960                crate::node::PausableMode::Default | crate::node::PausableMode::Off => false,
2961            };
2962            if buffered_tier && mode_buffers_tier3 && rec.pause_state.is_paused() {
2963                if let Some(h) = msg.payload_handle() {
2964                    self.binding.retain_handle(h);
2965                }
2966                let push_result = rec.pause_state.push_buffered(msg, cap);
2967                for dm in push_result.dropped_msgs {
2968                    if let Some(h) = dm.payload_handle() {
2969                        self.binding.release_handle(h);
2970                    }
2971                }
2972                // R1.3.8.c (Slice F, A3): on first overflow this cycle,
2973                // schedule a synthesized ERROR for wave-end emission.
2974                // `cap` is `Some` here (an overflow can only happen with a
2975                // configured cap), so `unwrap` is safe.
2976                if push_result.first_overflow_this_cycle {
2977                    if let Some((dropped_count, lock_held_ns)) =
2978                        rec.pause_state.overflow_diagnostic()
2979                    {
2980                        // Q-beyond Sub-slice 1 (D108, 2026-05-09):
2981                        // pending_pause_overflow lives on per-thread WaveState.
2982                        with_wave_state(|ws| {
2983                            ws.pending_pause_overflow
2984                                .push(crate::node::PendingPauseOverflow {
2985                                    node_id,
2986                                    dropped_count,
2987                                    configured_max: cap.unwrap_or(0),
2988                                    lock_held_ns,
2989                                });
2990                        });
2991                    }
2992                }
2993                return;
2994            }
2995        }
2996
2997        // Non-paused queue path: retain payload handle and queue into
2998        // pending_notify. Released in `flush_notifications` after sinks
2999        // fire.
3000        if let Some(h) = msg.payload_handle() {
3001            self.binding.retain_handle(h);
3002        }
3003        Self::push_into_pending_notify(s, node_id, msg);
3004    }
3005
3006    /// Slice X4 / D2: revision-tracked batch decision for `queue_notify`'s
3007    /// non-paused path. Either appends `msg` to the open batch (if
3008    /// `subscribers_revision` hasn't advanced since it opened — common
3009    /// case, no extra allocation) or opens a fresh batch with a current
3010    /// sink snapshot frozen at the new revision.
3011    ///
3012    /// Borrow discipline: reads `subscribers_revision` and the snapshot
3013    /// from `s.nodes` BEFORE borrowing WaveState's `pending_notify` to
3014    /// keep the two scopes disjoint.
3015    ///
3016    /// Q-beyond Sub-slice 2 (D108, 2026-05-09): `pending_notify` moved
3017    /// to per-thread WaveState. The state-side read of
3018    /// `subscribers_revision` / `subscribers` happens before the
3019    /// `with_wave_state` block opens, then the WaveState borrow
3020    /// performs the entry insertion / append. State lock + WaveState
3021    /// borrow remain independent.
3022    ///
3023    /// Lock-discipline assumption: this read of `subscribers_revision`
3024    /// is safe because both the subscribe install path
3025    /// ([`crate::node::Core::subscribe`]) and `queue_notify` hold
3026    /// `CoreState`'s mutex when they bump / read the revision —
3027    /// concurrent subscribe/unsubscribe cannot interleave. **If
3028    /// `Core::subscribe` ever moves the sink-install lock-released
3029    /// (mirroring the lock-released drain refactor), the revision read
3030    /// here must re-validate post-borrow — otherwise a fresh batch
3031    /// could open with a stale snapshot.**
3032    fn push_into_pending_notify(s: &mut CoreState, node_id: NodeId, msg: Message) {
3033        let current_rev = s.require_node(node_id).subscribers_revision;
3034        let needs_new_batch = with_wave_state(|ws| {
3035            ws.pending_notify.get(&node_id).is_none_or(|entry| {
3036                entry
3037                    .batches
3038                    .last()
3039                    .is_none_or(|b| b.snapshot_revision != current_rev)
3040            })
3041        });
3042        let sinks_snapshot: SmallVec<[Sink; 1]> = if needs_new_batch {
3043            s.require_node(node_id)
3044                .subscribers
3045                .values()
3046                .cloned()
3047                .collect()
3048        } else {
3049            SmallVec::new()
3050        };
3051        with_wave_state(|ws| match ws.pending_notify.entry(node_id) {
3052            Entry::Vacant(slot) => {
3053                let mut batches: SmallVec<[PendingBatch; 1]> = SmallVec::new();
3054                batches.push(PendingBatch {
3055                    snapshot_revision: current_rev,
3056                    sinks: sinks_snapshot,
3057                    messages: smallvec::smallvec![msg],
3058                });
3059                slot.insert(PendingPerNode { batches });
3060            }
3061            Entry::Occupied(mut slot) => {
3062                let entry = slot.get_mut();
3063                if needs_new_batch {
3064                    entry.batches.push(PendingBatch {
3065                        snapshot_revision: current_rev,
3066                        sinks: sinks_snapshot,
3067                        messages: smallvec::smallvec![msg],
3068                    });
3069                } else {
3070                    entry
3071                        .batches
3072                        .last_mut()
3073                        .expect("non-empty by construction (entry exists implies batch exists)")
3074                        .messages
3075                        .push(msg);
3076                }
3077            }
3078        });
3079    }
3080
3081    /// Collect wave-end sink-fire jobs into `ws.deferred_flush_jobs` and the
3082    /// payload-handle releases owed for `pending_notify` into
3083    /// `ws.deferred_handle_releases`. The actual sink fires + handle releases
3084    /// run **after** the state lock is dropped — see [`Core::run_wave`].
3085    ///
3086    /// R1.3.1.b two-phase propagation: phase 1 (DIRTY) propagates through
3087    /// the entire graph before phase 2 (DATA / RESOLVED) begins. Implemented
3088    /// here as cross-node tier-then-node collect — phase 1's jobs sit before
3089    /// phase 2's in `deferred_flush_jobs`, so when `run_wave` drains the
3090    /// queue lock-released, multi-node subscribers see all DIRTYs before any
3091    /// settle. Matches TS's drainPhase model without the per-tier queue
3092    /// indirection.
3093    ///
3094    /// Phase ordering:
3095    ///   1 → tier 1   (DIRTY)
3096    ///   2 → tier 3+4 (DATA/RESOLVED + INVALIDATE — the "settle slice")
3097    ///   3 → tier 5   (COMPLETE/ERROR)
3098    ///   4 → tier 6   (TEARDOWN)
3099    ///
3100    /// Tier 0 (START) is per-subscription (never enters pending_notify) and
3101    /// tier 2 (PAUSE/RESUME) is delivered through dedicated paths, also
3102    /// bypassing pending_notify; both are absent from this enumeration.
3103    ///
3104    /// Within a single phase, per-node insertion order (IndexMap iteration)
3105    /// is preserved — an emit on A before B → A's phase-2 messages flush
3106    /// before B's. Within a single node, message order is preserved.
3107    fn flush_notifications(&self, s: &mut CoreState) {
3108        const PHASES: &[&[u8]] = &[
3109            &[1],    // DIRTY
3110            &[3, 4], // DATA/RESOLVED + INVALIDATE
3111            &[5],    // COMPLETE/ERROR
3112            &[6],    // TEARDOWN
3113        ];
3114        // Q-beyond Sub-slice 1 + 2 + 3 (D108, 2026-05-09): pending_notify,
3115        // deferred_handle_releases, and deferred_flush_jobs all live on
3116        // per-thread WaveState. Take pending_notify under the WaveState
3117        // borrow, drop the borrow, run the per-phase loop (no WaveState
3118        // access in the loop body), then re-borrow WaveState at the end
3119        // to push the collected jobs and payload-handle releases.
3120        //
3121        // /qa F7 (2026-05-10): the `s: &mut CoreState` parameter is
3122        // currently unused inside the per-phase loop — `pending` was
3123        // moved off `s` to WaveState by sub-slice 2, and the per-batch
3124        // sink snapshot is already on the PendingBatch. Kept as a
3125        // parameter to preserve the caller's `let mut s = lock_state();
3126        // self.flush_notifications(&mut s);` invocation shape (caller
3127        // holds the state lock around this call — load-bearing for
3128        // R1.3.5.a per-tier handshake-vs-flush ordering). NOT a "lock
3129        // released" marker; the lock guard belongs to the caller and
3130        // is held throughout this function. A future change that adds
3131        // an in-loop state read should remove the discard below;
3132        // removing the parameter would break the caller's ability to
3133        // express the lock-discipline contract at the call site.
3134        let _ = &*s; // explicit no-op acknowledgement; lock held by caller.
3135                     // D217-AMEND-2 (2026-05-16): recycle the per-wave `pending_notify`
3136                     // map instead of `mem::take`-ing it. `mem::take` installed a
3137                     // fresh `IndexMap::default()` every wave → a new `ahash::
3138                     // RandomState` (entropy via `gen_hasher_seed`/`from_keys`) PLUS
3139                     // RawVec realloc churn (`finish_grow`/`grow_one`) on the next
3140                     // wave's `queue_notify`. Empirical attribution
3141                     // (`examples/profile_st_emit.rs` + macOS `sample`): ~1250 of
3142                     // ~4767 hot-path samples — the dominant §7 floor tax (D217
3143                     // lever-1 "slab store" falsified; `require_node` was minor).
3144                     // Fix: swap the live map with a persistent spare so the next
3145                     // wave fills a capacity-retained, fixed-seed map; process this
3146                     // wave's full map from the spare slot and `.clear()` it (retain
3147                     // capacity + hasher; no drop, no realloc, no reseed). Zero
3148                     // `IndexMap::default()` after thread init.
3149                     //
3150                     // The jobs-building loop now runs INSIDE the single WaveState
3151                     // borrow. This is sound: the loop is pure (iteration +
3152                     // `Arc::clone` + `Vec` collect; no re-entrant `with_wave_state`
3153                     // / `lock_state`), and the caller holds the CoreState lock
3154                     // throughout regardless — so R1.3.5.a per-tier
3155                     // handshake-vs-flush ordering is unchanged. Refcount discipline
3156                     // is unchanged: payload-handle releases are still collected into
3157                     // `deferred_handle_releases` (released post-lock-drop by
3158                     // `BatchGuard::drop`); `.clear()` runs the same element drops as
3159                     // the old map-drop and the `PendingPerNode`/`Message` payloads
3160                     // carry no refcount-releasing `Drop`.
3161        with_wave_state(|ws| {
3162            core::mem::swap(&mut ws.pending_notify, &mut ws.pending_notify_recycle);
3163            // ws.pending_notify         = empty spare (next wave fills it)
3164            // ws.pending_notify_recycle = THIS wave's full map (below)
3165            let mut jobs: DeferredJobs = Vec::new();
3166            let mut releases: Vec<HandleId> = Vec::new();
3167            {
3168                let full = &ws.pending_notify_recycle;
3169                for &phase_tiers in PHASES {
3170                    for (_node_id, entry) in full {
3171                        // Slice X4 / D2: iterate batches in arrival
3172                        // order. Each batch carries its own sink
3173                        // snapshot frozen at open-time; a batch's
3174                        // messages flush to ITS sinks only. Within a
3175                        // single (phase, node), batches stay in arrival
3176                        // order so emit-order semantics are preserved.
3177                        for batch in &entry.batches {
3178                            if batch.sinks.is_empty() {
3179                                continue;
3180                            }
3181                            let phase_msgs: Vec<Message> = batch
3182                                .messages
3183                                .iter()
3184                                .copied()
3185                                .filter(|m| phase_tiers.contains(&m.tier()))
3186                                .collect();
3187                            if phase_msgs.is_empty() {
3188                                continue;
3189                            }
3190                            let sinks_clone: Vec<Sink> =
3191                                batch.sinks.iter().map(Arc::clone).collect();
3192                            jobs.push((sinks_clone, phase_msgs));
3193                        }
3194                    }
3195                }
3196                // Refcount release balances the retain done in
3197                // `queue_notify` for every payload-bearing message that
3198                // landed in pending_notify (across ALL batches per
3199                // node); deferred to post-lock-drop so the binding's
3200                // release path can't re-enter Core under our lock.
3201                for entry in full.values() {
3202                    for msg in entry.iter_messages() {
3203                        if let Some(h) = msg.payload_handle() {
3204                            releases.push(h);
3205                        }
3206                    }
3207                }
3208            }
3209            ws.deferred_flush_jobs.append(&mut jobs);
3210            ws.deferred_handle_releases.append(&mut releases);
3211            // Retain capacity + the existing ahash seed for next wave's
3212            // swap-in. No drop, no realloc, no reseed.
3213            ws.pending_notify_recycle.clear();
3214        });
3215    }
3216
3217    /// Take the deferred sink-fire jobs, payload-handle releases,
3218    /// cleanup-hook fire queue, and pending-wipe queue from `WaveState`.
3219    /// Callers pair this with `drop(state_guard)` and a subsequent
3220    /// [`Self::fire_deferred`] call to deliver the wave's sinks, handle
3221    /// releases, Slice E2 OnInvalidate cleanup hooks, and Slice E2 /qa
3222    /// Q2(b) eager wipe_ctx fires lock-released.
3223    ///
3224    /// Q-beyond Sub-slice 1 (D108, 2026-05-09): `deferred_handle_releases`
3225    /// source moved to per-thread WaveState — signature takes `&mut WaveState`.
3226    /// Q-beyond Sub-slice 3 (D108, 2026-05-09): `deferred_flush_jobs`,
3227    /// `deferred_cleanup_hooks`, and `pending_wipes` all moved to
3228    /// WaveState. The `_s: &mut CoreState` parameter is now unused but
3229    /// kept to preserve the call-site lock-discipline ordering (caller
3230    /// holds the state lock around this call to interleave with prior
3231    /// `clear_wave_state` per-NodeRecord work).
3232    pub(crate) fn drain_deferred(_s: &mut CoreState, ws: &mut WaveState) -> WaveDeferred {
3233        (
3234            std::mem::take(&mut ws.deferred_flush_jobs),
3235            std::mem::take(&mut ws.deferred_handle_releases),
3236            std::mem::take(&mut ws.deferred_cleanup_hooks),
3237            std::mem::take(&mut ws.pending_wipes),
3238        )
3239    }
3240
3241    /// Fire deferred sink-fire jobs in collected order, then release the
3242    /// payload handles owed for messages that landed in `pending_notify`
3243    /// during the wave, then fire any queued Slice E2 OnInvalidate cleanup
3244    /// hooks. All three phases run lock-released so:
3245    /// - Sinks that call back into Core (emit, pause, etc.) re-acquire the
3246    ///   state lock cleanly and run their own nested wave.
3247    /// - The binding's `release_handle` path can't deadlock against a
3248    ///   binding-side mutex held by Core.
3249    /// - User cleanup closures (invoked via `BindingBoundary::cleanup_for`)
3250    ///   may safely re-enter Core for unrelated nodes.
3251    ///
3252    /// **Cleanup-drain panic discipline (D060):** each `cleanup_for` call
3253    /// is wrapped in `catch_unwind` so a single binding panic doesn't
3254    /// short-circuit the per-wave drain. All queued cleanup attempts run;
3255    /// if any panicked, the LAST panic re-raises after the loop completes
3256    /// (preserving wave-end discipline while still surfacing failures).
3257    /// Per D060, Core stays panic-naive about user code — bindings own
3258    /// their host-language panic policy inside `cleanup_for`; this
3259    /// `catch_unwind` is purely about drain-don't-short-circuit.
3260    pub(crate) fn fire_deferred(
3261        &self,
3262        jobs: DeferredJobs,
3263        releases: Vec<HandleId>,
3264        cleanup_hooks: Vec<(crate::handle::NodeId, crate::boundary::CleanupTrigger)>,
3265        pending_wipes: Vec<crate::handle::NodeId>,
3266    ) {
3267        // Slice E2 /qa P1 (2026-05-07): wrap each sink-fire in
3268        // `catch_unwind` so a panicking sink doesn't unwind out of
3269        // `fire_deferred` and drop the queued `releases` +
3270        // `cleanup_hooks`. Mirrors Slice F audit fix A7's per-tier
3271        // handshake-fire discipline. Without this guard, a sink panic
3272        // here would silently leak handle retains AND silently drop
3273        // OnInvalidate cleanup hooks. AssertUnwindSafe is safe because
3274        // we re-raise the last panic at the end after running every
3275        // queued fire — drain ordering is preserved.
3276        let mut last_panic: Option<Box<dyn std::any::Any + Send>> = None;
3277        for (sinks, msgs) in jobs {
3278            for sink in &sinks {
3279                let sink = sink.clone();
3280                let msgs_ref = &msgs;
3281                let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
3282                    sink(msgs_ref);
3283                }));
3284                if let Err(payload) = result {
3285                    last_panic = Some(payload);
3286                }
3287            }
3288        }
3289        for h in releases {
3290            self.binding.release_handle(h);
3291        }
3292        // Slice E2 (D060): drain cleanup hooks with per-item panic
3293        // isolation so the loop always completes. AssertUnwindSafe is
3294        // safe here because we don't rely on logical state being valid
3295        // post-panic — the panic propagates anyway after the drain ends.
3296        for (node_id, trigger) in cleanup_hooks {
3297            let binding = &self.binding;
3298            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
3299                binding.cleanup_for(node_id, trigger);
3300            }));
3301            if let Err(payload) = result {
3302                last_panic = Some(payload);
3303            }
3304        }
3305        // Slice E2 /qa Q2(b) (D069): drain eager wipe_ctx queue with the
3306        // same per-item panic isolation. Fires AFTER cleanup hooks so a
3307        // resubscribable node's OnInvalidate (or any tier-3+ cleanup that
3308        // fires in the same wave) sees pre-wipe binding state if it
3309        // landed in the same wave as the terminal cascade. Mutually
3310        // exclusive with `Subscription::Drop`'s direct-fire site, but
3311        // even concurrent fires are idempotent (binding's `wipe_ctx`
3312        // calls `HashMap::remove` which is a no-op on absent keys).
3313        for node_id in pending_wipes {
3314            let binding = &self.binding;
3315            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
3316                binding.wipe_ctx(node_id);
3317            }));
3318            if let Err(payload) = result {
3319                last_panic = Some(payload);
3320            }
3321        }
3322        if let Some(payload) = last_panic {
3323            std::panic::resume_unwind(payload);
3324        }
3325    }
3326
3327    // -------------------------------------------------------------------
3328    // User-facing batch — coalesce multiple emits into one wave
3329    // -------------------------------------------------------------------
3330
3331    /// Coalesce multiple emissions into a single wave. Every `emit` /
3332    /// `complete` / `error` / `teardown` / `invalidate` call inside `f`
3333    /// queues its downstream work; the wave drains when `f` returns.
3334    ///
3335    /// **R1.3.6.a** — DIRTY still propagates immediately (tier 1 isn't
3336    /// deferred); only tier-3+ delivery is held until scope exit. **R1.3.6.b**
3337    /// — repeated emits on the same node coalesce into a single multi-message
3338    /// delivery (one [`Message::Dirty`] for the wave + one [`Message::Data`]
3339    /// per emit, all delivered together in the per-node phase-2 pass).
3340    ///
3341    /// Nested `batch()` calls share the outer wave; only the outermost call
3342    /// drives the drain. Re-entrant calls from inside an `emit`/fn (the wave
3343    /// engine's own `in_tick` re-entrance) compose with this method
3344    /// transparently — they observe `in_tick = true` and skip drain just
3345    /// like nested `batch()`.
3346    ///
3347    /// On panic inside `f`, the `BatchGuard` returned by the internal
3348    /// `begin_batch` call drops normally and discards pending tier-3+ work
3349    /// (subscribers do not observe the half-built wave). See
3350    /// [`Core::begin_batch`] for the RAII variant if you need explicit control
3351    /// over the scope boundary.
3352    pub fn batch<F>(&self, f: F)
3353    where
3354        F: FnOnce(),
3355    {
3356        let _guard = self.begin_batch();
3357        f();
3358    }
3359
3360    /// RAII batch handle — opens a wave when constructed, drains on drop.
3361    ///
3362    /// Mirrors the closure-based [`Self::batch`] but exposes the scope
3363    /// boundary so callers can compose batches with non-`FnOnce` control
3364    /// flow (e.g. async-state-machine code paths, or splitting setup and
3365    /// drain across helper functions).
3366    ///
3367    /// ```
3368    /// use graphrefly_core::{Core, BindingBoundary, NodeRegistration, NodeOpts,
3369    ///     HandleId, NodeId, FnId, FnResult, DepBatch};
3370    /// use std::sync::Arc;
3371    ///
3372    /// struct Stub;
3373    /// impl BindingBoundary for Stub {
3374    ///     fn invoke_fn(&self, _: NodeId, _: FnId, _: &[DepBatch]) -> FnResult {
3375    ///         FnResult::Noop { tracked: None }
3376    ///     }
3377    ///     fn custom_equals(&self, _: FnId, _: HandleId, _: HandleId) -> bool { false }
3378    ///     fn release_handle(&self, _: HandleId) {}
3379    /// }
3380    ///
3381    /// let core = Core::new(Arc::new(Stub) as Arc<dyn BindingBoundary>);
3382    /// let state_a = core.register(NodeRegistration {
3383    ///     deps: vec![], fn_or_op: None,
3384    ///     opts: NodeOpts { initial: HandleId::new(1), ..Default::default() },
3385    /// }).unwrap();
3386    /// let state_b = core.register(NodeRegistration {
3387    ///     deps: vec![], fn_or_op: None,
3388    ///     opts: NodeOpts { initial: HandleId::new(2), ..Default::default() },
3389    /// }).unwrap();
3390    ///
3391    /// let g = core.begin_batch();
3392    /// core.emit(state_a, HandleId::new(10));
3393    /// core.emit(state_b, HandleId::new(20));
3394    /// drop(g); // wave drains here
3395    /// ```
3396    ///
3397    /// Like the closure form, nested `begin_batch` calls share the outer
3398    /// wave (only the outermost guard drains).
3399    ///
3400    #[must_use = "BatchGuard drains the wave on drop; assign to a named binding"]
3401    pub fn begin_batch(&self) -> BatchGuard<'_> {
3402        // D246/S2c: single-owner ⇒ a `Core` is driven by exactly one
3403        // thread, so there is no cross-thread wave serialization to
3404        // acquire (the §7 group/global wave-locks are deleted) and no
3405        // shard to route to (single shard always).
3406        self.begin_batch_with_guards()
3407    }
3408
3409    /// Begin a batch for a wave seeded at `seed`. Historically this
3410    /// acquired the per-partition `wave_owner` `ReentrantMutex`es for
3411    /// every partition transitively touched from `seed` (the Slice Y1
3412    /// parallelism win). **S2c/D248 deleted that machinery:** `Core` is
3413    /// single-owner `!Send + !Sync`, so a wave is one uninterrupted
3414    /// owner-side drain with nothing to lock. This now delegates to the
3415    /// infallible [`Self::try_begin_batch_for`], which acquires nothing
3416    /// (the all-`None` single-owner floor); the `seed` parameter is
3417    /// retained for the declared-group identity routing + D211
3418    /// minimal-churn (callers compile unchanged). Cross-`Core`
3419    /// parallelism is host-native via independent per-worker Cores
3420    /// (actor model), not per-partition locks.
3421    ///
3422    /// # Panics
3423    ///
3424    /// Panics only if [`Self::try_begin_batch_for`] returns `Err` —
3425    /// **unreachable**: it is now always `Ok` (scheduling groups are
3426    /// static identity; no `PartitionOrderViolation`, no epoch retry).
3427    ///
3428    /// Slice Y1 / Phase E (2026-05-08); infallible-since S2c (D246).
3429    #[must_use = "BatchGuard drains the wave on drop; assign to a named binding"]
3430    pub fn begin_batch_for(&self, seed: crate::handle::NodeId) -> BatchGuard<'_> {
3431        match self.try_begin_batch_for(seed) {
3432            Ok(guard) => guard,
3433            Err(e) => panic!("{e}"),
3434        }
3435    }
3436
3437    /// §7: now-infallible variant of [`Self::begin_batch_for`]. The
3438    /// `Result` is retained so existing callers (`try_run_wave_for`,
3439    /// the `?`-using wave entry points) compile unchanged (D211); it is
3440    /// **always `Ok`** — scheduling groups are static + user-declared
3441    /// and the touched-group set is acquired sorted upfront, so there is
3442    /// no `PartitionOrderViolation` and no epoch retry. For an
3443    /// all-`None` cascade this acquires nothing (single-threaded floor).
3444    #[allow(clippy::unnecessary_wraps)]
3445    pub(crate) fn try_begin_batch_for(
3446        &self,
3447        seed: crate::handle::NodeId,
3448    ) -> Result<BatchGuard<'_>, crate::node::PartitionOrderViolation> {
3449        // D246/S2c: single-owner ⇒ no cross-thread wave serialization
3450        // and no shard routing. The `Result`/`seed` are retained so
3451        // callers (`try_run_wave_for`, the `?`-using wave entry points)
3452        // compile unchanged (D211); always `Ok`. `seed` is unused now —
3453        // the §7 touched-group walk is deleted.
3454        let _ = seed;
3455        Ok(self.begin_batch_with_guards())
3456    }
3457
3458    /// Is this thread currently inside an owning wave on this Core?
3459    /// Reads the one-Core-per-thread [`IN_TICK_OWNED`] slot (D252) —
3460    /// `true` iff the slot holds this Core's `generation`. Read on the
3461    /// wave-owner thread (e.g. by `commit_emission` to decide cache-
3462    /// snapshot taking). `#[must_use]`: a discarded result silently
3463    /// loses the ownership/nesting decision (a classic predicate-misuse
3464    /// bug).
3465    #[must_use]
3466    fn in_tick(&self) -> bool {
3467        IN_TICK_OWNED.with(|s| s.get() == self.generation)
3468    }
3469
3470    /// Claim wave ownership for this Core on this thread (D252 "one
3471    /// Core per OS thread" hard invariant). Returns `true` iff this call
3472    /// is the outermost entry (slot was `0`) — i.e. `owns_tick`; `false`
3473    /// for nested same-Core re-entry (slot already holds our
3474    /// `generation`). **Panics fail-loud** if the slot holds any *other*
3475    /// nonzero generation — that is the D252-forbidden cross-Core
3476    /// owner-side nesting on a single thread (one OS thread mid-wave on
3477    /// Core-A entering a wave on Core-B). Under D248 single-owner Core
3478    /// the only call path that could produce it is a `DeferFn` capturing
3479    /// & driving a *second* `&Core`; no in-tree consumer does this, and
3480    /// adding one would violate the actor-model "one worker = one Core"
3481    /// framing — surfaced loudly here rather than silently masking the
3482    /// foreign Core's ownership.
3483    fn claim_in_tick(&self) -> bool {
3484        IN_TICK_OWNED.with(|s| {
3485            let cur = s.get();
3486            if cur == 0 {
3487                s.set(self.generation);
3488                true
3489            } else if cur == self.generation {
3490                false
3491            } else {
3492                // D252 hard invariant: one Core per OS thread. A nonzero
3493                // mismatch means a foreign Core's wave is live on this
3494                // thread — structurally forbidden under D248 single-
3495                // owner (a `DeferFn` driving a second `&Core` on the
3496                // same owner thread). Panic before nesting silently.
3497                //
3498                // D258 (S7, 2026-05-20) — message softened to be useful
3499                // for both in-tree Rust devs and JS `@graphrefly/native`
3500                // consumers (the only common path that surfaces this
3501                // panic is `BenchCore` misuse). Each `BenchCore` spawns
3502                // its own dedicated actor worker thread; this panic
3503                // means TWO `BenchCore` instances are sharing one
3504                // actor thread (out-of-tree only — in-tree the actor
3505                // model prevents it by construction, per D255). No
3506                // `cfg(napi)` gate is needed — the substrate panic is
3507                // already only reachable from a binding-layer
3508                // misconfiguration.
3509                panic!(
3510                    "GraphReFly invariant violated — cross-Core wave nesting \
3511                     on a single OS thread (this Core's generation {self_gen}, \
3512                     observed foreign generation {cur}). One Core per OS \
3513                     thread (D248/D252). \
3514                     \n\
3515                     Rust callers: a `DeferFn` or owner-side seam appears to \
3516                     be driving a *second* `&Core` mid-wave; the substrate \
3517                     does not support cross-Core same-thread nesting. \
3518                     \n\
3519                     `@graphrefly/native` (BenchCore) callers: two BenchCore \
3520                     instances are sharing one actor worker thread — each \
3521                     `BenchCore` MUST own its dedicated actor thread (the \
3522                     S6/D255 invariant). Verify you constructed each \
3523                     `BenchCore` via the supported factories (which spawn \
3524                     a per-instance worker). \
3525                     \n\
3526                     Internal reference: `docs/rust-port-decisions.md` \
3527                     D248/D252/D255/D258.",
3528                    self_gen = self.generation,
3529                );
3530            }
3531        })
3532    }
3533
3534    /// Release wave ownership for this Core on this thread. Called by the
3535    /// owning [`BatchGuard::drop`] only — after the `!owns_tick`
3536    /// early-return, so a nested guard never releases — explicitly at
3537    /// each of the three exit points, always AFTER the wave drain +
3538    /// WaveState cleanup and BEFORE `fire_deferred` (so a re-entrant sink
3539    /// emit runs as a fresh owning wave): (1) the closure-body-panic
3540    /// branch, (2) the drain-phase-panic `catch_unwind` arm (before
3541    /// `resume_unwind`), (3) the success path's locked cleanup block.
3542    /// Clears the [`IN_TICK_OWNED`] slot back to `0` (D252). Released
3543    /// exactly once per (Core, wave) on this thread; idempotent (a
3544    /// double-clear of `0` is a no-op).
3545    fn clear_in_tick(&self) {
3546        IN_TICK_OWNED.with(|s| {
3547            debug_assert!(
3548                s.get() == 0 || s.get() == self.generation,
3549                "BatchGuard::clear_in_tick: slot holds foreign \
3550                 generation {observed} (this Core: {self_gen}) — \
3551                 D252 invariant violated",
3552                observed = s.get(),
3553                self_gen = self.generation,
3554            );
3555            s.set(0);
3556        });
3557    }
3558
3559    /// Internal helper: claim `in_tick` and assemble a [`BatchGuard`].
3560    /// D246/S2c: single-owner ⇒ no wave-owner / shard guards to carry.
3561    fn begin_batch_with_guards(&self) -> BatchGuard<'_> {
3562        // Claim wave ownership in the one-Core-per-OS-thread
3563        // [`IN_TICK_OWNED`] slot (D252; see its doc for the same-Core
3564        // nested-re-entry semantics and the cross-Core panic invariant)
3565        // — no state lock needed, since `in_tick` has no cross-thread
3566        // read requirement.
3567        let owns_tick = self.claim_in_tick();
3568        // D1 patch (2026-05-09): defensive wave-start clear of the
3569        // per-thread Slice G tier3 tracker on outermost owning entry.
3570        // The thread-local is cleared at outermost BatchGuard drop on
3571        // both success + panic paths; this start-clear is belt-and-
3572        // suspenders against panic paths that bypass Drop (catch_unwind
3573        // can interleave with thread reuse — e.g. cargo's test-runner
3574        // thread pool — and propagate stale entries from a prior
3575        // panicked test's wave that didn't fully unwind through
3576        // BatchGuard::drop).
3577        if owns_tick {
3578            tier3_clear();
3579            // Q-beyond Sub-slice 1 (D108, 2026-05-09): defensive wave-start
3580            // clear of WaveState's non-retain-holding fields. Mirrors the
3581            // tier3 defensive-clear above. Retain-holding fields
3582            // (wave_cache_snapshots / deferred_handle_releases) MUST be
3583            // empty here — outermost BatchGuard::drop drains them on both
3584            // success + panic paths.
3585            wave_state_clear_outermost();
3586        }
3587        BatchGuard {
3588            core: self,
3589            owns_tick,
3590            _not_send: std::marker::PhantomData,
3591        }
3592    }
3593}
3594
3595/// RAII guard returned by [`Core::begin_batch`].
3596///
3597/// While alive, suppresses per-emit wave drains — multiple `emit` /
3598/// `complete` / `error` / `teardown` / `invalidate` calls coalesce into one
3599/// wave. On drop:
3600/// - Outermost guard: drains the wave (fires sinks, runs cleanup, clears
3601///   in-tick).
3602/// - Nested guard (an outer `BatchGuard` or an in-progress wave already owns
3603///   the in-tick flag): silently no-ops.
3604///
3605/// On thread panic during the closure body, the drop path discards pending
3606/// tier-3+ delivery rather than firing sinks (avoids cascading panics).
3607/// Subscribers observe **no tier-3+ delivery for the panicked wave**.
3608/// State-node cache writes that already executed inside the closure are
3609/// rolled back via wave-cache snapshots — `cache_of(s)` returns the pre-
3610/// panic value. The atomicity guarantee covers both sink-observability and
3611/// cache state.
3612///
3613/// # Thread safety
3614///
3615/// `BatchGuard` is **`!Send`** by design. `begin_batch` claims the
3616/// one-Core-per-OS-thread `in_tick` ownership slot (D252) on the
3617/// calling thread; sending the guard to another thread and dropping it
3618/// there would clear `in_tick` against the wrong thread's slot,
3619/// breaking the "I own the wave scope" semantic. D246/S2c: single-owner
3620/// ⇒ the §7 per-partition `wave_owner` re-entrant mutex(es) are
3621/// deleted; `!Send` is now enforced solely by the
3622/// `PhantomData<*const ()>` marker.
3623///
3624/// ```compile_fail
3625/// use graphrefly_core::{BatchGuard, BindingBoundary, Core, DepBatch, FnId, FnResult, HandleId, NodeId};
3626/// use std::sync::Arc;
3627///
3628/// struct Stub;
3629/// impl BindingBoundary for Stub {
3630///     fn invoke_fn(&self, _: NodeId, _: FnId, _: &[DepBatch]) -> FnResult {
3631///         FnResult::Noop { tracked: None }
3632///     }
3633///     fn custom_equals(&self, _: FnId, _: HandleId, _: HandleId) -> bool { false }
3634///     fn release_handle(&self, _: HandleId) {}
3635/// }
3636/// fn requires_send<T: Send>(_: T) {}
3637/// let core = Core::new(Arc::new(Stub) as Arc<dyn BindingBoundary>);
3638/// let guard = core.begin_batch();
3639/// requires_send(guard); // <- compile_fail: BatchGuard is !Send.
3640/// ```
3641#[must_use = "BatchGuard drains the wave on drop; assign to a named binding"]
3642pub struct BatchGuard<'a> {
3643    // S2b (D223): borrows `&'a Core` — `Core` is no longer `Clone`
3644    // (owned-by-value, relocates between workers). The guard lives
3645    // entirely within the wave scope of the `&self` that produced it
3646    // (`begin_batch*` takes `&self`), so `self` strictly outlives the
3647    // guard — identical to S1's `FiringGuard<'a>`. `!Send` via
3648    // `_not_send`.
3649    core: &'a Core,
3650    owns_tick: bool,
3651    /// D246/S2c: single-owner ⇒ no per-partition wave-owner guards and
3652    /// no ambient shard-key guard (both were shared-Core-era §7
3653    /// machinery, now deleted). `BatchGuard` stays `!Send` purely via
3654    /// this `PhantomData<*const ()>` — a wave guard is wave-scoped to
3655    /// the one owner thread and must not cross threads.
3656    _not_send: std::marker::PhantomData<*const ()>,
3657}
3658
3659impl BatchGuard<'_> {
3660    /// Panic-discard cleanup for the owning guard: drop pending wave
3661    /// work, release queued payload + handle retains lock-released,
3662    /// restore pre-wave cache snapshots, clear per-thread `WaveState` +
3663    /// the Slice-G tier3 tracker, and discard deferred producer ops.
3664    ///
3665    /// Shared by BOTH panic origins so a drain-phase fn/sink panic gets
3666    /// the identical `BatchGuard` atomicity guarantee as a closure-body
3667    /// panic: (1) the `std::thread::panicking()` branch (panic propagated
3668    /// from the wave's *closure body* — drop runs during that unwind),
3669    /// and (2) the success-path `catch_unwind` around `drain_and_flush()`
3670    /// (a fn/sink panic that escaped the inner per-call `catch_unwind`
3671    /// isolation while drop was NOT already unwinding). /qa D047.
3672    ///
3673    /// Does NOT release `in_tick` — each `BatchGuard::drop` exit path
3674    /// calls `clear_in_tick()` explicitly, after this cleanup and before
3675    /// `fire_deferred` (so a re-entrant sink emit runs as a fresh owning
3676    /// wave).
3677    fn discard_wave_cleanup(&self) {
3678        let (pending, pending_recycle, deferred_releases, restored_releases) = {
3679            let mut s = self.core.lock_state();
3680            // WaveState borrowed alongside state for panic-discard
3681            // cleanup. The WaveState borrow is per-thread, independent of
3682            // state. `in_tick` is the one-Core-per-OS-thread
3683            // [`IN_TICK_OWNED`] slot (D252), released separately by the
3684            // explicit `clear_in_tick` on each
3685            // exit path; this method only drains/cleans the per-thread
3686            // WaveState retain-fields.
3687            with_wave_state(|ws| {
3688                let pending = std::mem::take(&mut ws.pending_notify);
3689                // D217-AMEND-2 / QA: `pending_notify_recycle` is the
3690                // ONE retain-capable WaveState field whose retains live
3691                // in a *persistent* slot (not an owned local that drops
3692                // on unwind). On the success path it is empty here
3693                // (`flush_notifications` cleared it). But if a wave
3694                // panic-discards mid-`flush_notifications` AFTER the
3695                // swap but before `.clear()`, this slot holds the full
3696                // wave's payload-retaining map while `pending_notify` is
3697                // the empty spare. Drain it symmetrically so the same
3698                // "every retain field released on the panic path"
3699                // invariant the sibling fields uphold also covers
3700                // recycle (closes the leak + the stale-entry-injected-
3701                // into-next-wave hazard; success path: this is a no-op
3702                // take of an already-empty map).
3703                let pending_recycle = std::mem::take(&mut ws.pending_notify_recycle);
3704                let _: DeferredJobs = std::mem::take(&mut ws.deferred_flush_jobs);
3705                ws.pending_fires.clear();
3706                let restored = self.core.restore_wave_cache_snapshots(&mut s, ws);
3707                // clear_wave_state pushes batch-handle releases into
3708                // ws.deferred_handle_releases, so take ws's queue AFTER
3709                // the clear.
3710                s.clear_wave_state(ws);
3711                // Step 2a (D220-EXEC): defensive `currently_firing`
3712                // clear, relocated here from `CoreState::clear_wave_state`
3713                // (the field moved to the separate `CoreShared` region;
3714                // `St`'s `.shared` reaches it, a `&mut CoreState` can't).
3715                // Same wave-end point; `FiringGuard` RAII already
3716                // balances push/pop — this is the belt-and-suspenders
3717                // net for a future guard-bypassing path.
3718                s.shared.currently_firing.clear();
3719                ws.clear_wave_state();
3720                let deferred_releases = std::mem::take(&mut ws.deferred_handle_releases);
3721                // Slice E2 (D061): panic-discard wave drops queued
3722                // OnInvalidate cleanup hooks SILENTLY. Bindings using
3723                // OnInvalidate for external-resource cleanup MUST
3724                // idempotent-cleanup at process exit / next successful
3725                // invalidate. Mirrors A3 `pending_pause_overflow`
3726                // panic-discard precedent.
3727                let _: Vec<(crate::handle::NodeId, crate::boundary::CleanupTrigger)> =
3728                    std::mem::take(&mut ws.deferred_cleanup_hooks);
3729                // Slice E2 /qa Q2(b) (D069): same panic-discard discipline
3730                // for the eager-wipe queue. A panic-discarded wave drops
3731                // queued `wipe_ctx` fires silently; the binding-side
3732                // `NodeCtxState` entry remains until the next successful
3733                // terminate-with-no-subs cycle (or until `Core` drops).
3734                // This mirrors D061's external-resource-cleanup gap and
3735                // is documented similarly.
3736                let _: Vec<crate::handle::NodeId> = std::mem::take(&mut ws.pending_wipes);
3737                (pending, pending_recycle, deferred_releases, restored)
3738            })
3739        };
3740        // Lock dropped — release retains lock-released so the binding
3741        // can't deadlock against an internal binding mutex.
3742        for entry in pending.values() {
3743            for msg in entry.iter_messages() {
3744                if let Some(h) = msg.payload_handle() {
3745                    self.core.binding.release_handle(h);
3746                }
3747            }
3748        }
3749        // Symmetric with the `pending` loop above (D217-AMEND-2 / QA):
3750        // releases the full-map retains stranded in the recycle slot by
3751        // a panic between `flush_notifications`'s swap and clear. Empty
3752        // (no-op) on every non-panic path.
3753        for entry in pending_recycle.values() {
3754            for msg in entry.iter_messages() {
3755                if let Some(h) = msg.payload_handle() {
3756                    self.core.binding.release_handle(h);
3757                }
3758            }
3759        }
3760        for h in deferred_releases {
3761            self.core.binding.release_handle(h);
3762        }
3763        for h in restored_releases {
3764            self.core.binding.release_handle(h);
3765        }
3766        // D1 patch (2026-05-09): clear the per-thread Slice G tier3
3767        // tracker on outermost wave-end (panic-discard path). The
3768        // thread-local outlives the BatchGuard otherwise — cargo's
3769        // thread reuse across tests would propagate stale entries.
3770        tier3_clear();
3771        // §7 (D208–D211): the panic-path "discard deferred producer
3772        // ops" block is DELETED. There is no `deferred_producer_ops`
3773        // queue — producer ops execute immediately
3774        // (`Core::push_deferred_producer_op`), so on a panic-discard
3775        // there is nothing queued to release/drop.
3776    }
3777}
3778
3779/// D260: cap on the outer wave-end drain-to-quiescence loop. Realistic
3780/// legitimate cascades stay ≤3 passes; 32 gives 10× headroom and
3781/// panics loudly on a real emit-loop. See [`Drop for BatchGuard`] body.
3782const D260_MAX_REDRAIN_PASSES: u32 = 32;
3783
3784impl Drop for BatchGuard<'_> {
3785    fn drop(&mut self) {
3786        if !self.owns_tick {
3787            // Nested / non-owning guard: never claimed ownership, so it
3788            // must never release it. The owning guard's RAII releaser
3789            // (below) is the single clear site.
3790            return;
3791        }
3792        // Wave-ownership (`in_tick`) release discipline. `clear_in_tick`
3793        // must run AFTER the wave's drain + WaveState cleanup but BEFORE
3794        // `fire_deferred` (sinks), on every exit path:
3795        //
3796        // - **Before `fire_deferred` (load-bearing):** a sink re-entering
3797        //   `Core::emit` / `complete` from a flush callback must run as a
3798        //   fresh OWNING wave (so its own emissions drain + deliver). If
3799        //   `in_tick` were still owned during `fire_deferred`, that
3800        //   re-entrant emit would be a non-owning no-op and its data
3801        //   silently lost (regression caught by
3802        //   `lock_discipline::sink_can_reenter_core_via_emit`). This is
3803        //   why each path clears explicitly at the right point — NOT via
3804        //   an end-of-`drop` RAII guard (which would clear *after*
3805        //   `fire_deferred`).
3806        // - **/qa hardening (D047):** a fn/sink panic in the drain phase
3807        //   can escape the per-call `catch_unwind` isolation (e.g. a
3808        //   derived fn panicking when fired). Drop is NOT already
3809        //   unwinding, so it would otherwise skip BOTH the WaveState
3810        //   drain (→ next owning wave trips `wave_state_clear_outermost`)
3811        //   AND the `in_tick` clear (pre-D047 the explicit clear had this
3812        //   same window). Catching the drain panic, running the shared
3813        //   discard cleanup + `clear_in_tick`, then `resume_unwind` gives
3814        //   a drain-phase panic the identical atomicity as a
3815        //   closure-body panic.
3816        if std::thread::panicking() {
3817            // Closure-body panic — drop runs during that unwind. Discard
3818            // pending wave work (don't fire sinks mid-unwind — a sink
3819            // panic then aborts the process), release queued retains,
3820            // restore caches, then release ownership.
3821            self.discard_wave_cleanup();
3822            self.core.clear_in_tick();
3823            return;
3824        }
3825        // D260 / S7 (2026-05-20): wave-end drain-to-quiescence past
3826        // `fire_deferred`. The S2b/D232-AMEND contract is "the drain
3827        // loop applies mailbox/DeferQueue ops **in-wave, immediately**";
3828        // pre-D260 the BatchGuard ended after one `fire_deferred` pass,
3829        // so posts made by sinks firing **inside** `fire_deferred`
3830        // (post-`drain_and_flush`-exit) were stranded until the next
3831        // external wave entry. D260 completes the D232-AMEND promise:
3832        // loops the full drain → extract → clear-in_tick → fire_deferred
3833        // → release cycle until BOTH `mailbox` AND `deferred` quiesce.
3834        //
3835        // **Primary same-thread case (the actual bug surface).** Post-
3836        // S2b/S2c, producer-build sinks (e.g. `graphrefly_operators::
3837        // buffer::buffer`'s `notifier_sink`, the reactive-log `view`'s
3838        // internal sink) capture `MailboxEmitter` / `SinkEmitter` and
3839        // emit via `mailbox.post_emit(...)` instead of the pre-S2b
3840        // `core.emit_or_defer(...)` direct-call. The post is supposed
3841        // to be drained by the wave's `drain_and_flush` loop (top-of-
3842        // iteration `is_runnable()` check), but `fire_deferred` runs
3843        // AFTER `drain_and_flush` exits. Same-thread same-wave: a
3844        // producer-build sink in `fire_deferred` posts to mailbox →
3845        // stranded → 35 parity failures (buffer / stratify / higher-
3846        // order / zip / control / messaging — all uniform "emissions
3847        // lost"). The cross-thread autonomous-timer-task case (D227/
3848        // D230) is the secondary motivation for `MailboxEmitter`'s
3849        // `Send + Sync` shape, but the in-tree bug surface was the
3850        // same-thread sink case D260 plugs.
3851        //
3852        // **Why iteration not nested recursion.** Pre-S2b, sinks
3853        // captured `Core` directly and `core.emit_or_defer` ran a
3854        // *nested wave* per emit (recursive RAII; depth-first). D260's
3855        // iteration at the wave-end frontier coalesces all post-
3856        // `fire_deferred` mailbox ops into one outer wave (breadth-
3857        // first at the boundary; fewer nested-wave entries; identical
3858        // quiescence semantics).
3859        //
3860        // **Canonical timing convergence (A3, user-locked 2026-05-20).**
3861        // Rust IS the canonical for this drain-to-quiescence shape;
3862        // TS/PY MUST converge if/when they expose an equivalent
3863        // mailbox-posting sink seam. Pure-ts today implements the same
3864        // observable behavior via a direct-call sink path (no mailbox
3865        // indirection → no "stranded post" hazard → naturally quiescent
3866        // at wave end); cross-arm parity scenarios (buffer, view(slice),
3867        // stratify, ...) verify the observable agreement empirically.
3868        //
3869        // **Bounded-iteration:** D260's outer loop is capped at
3870        // `D260_MAX_REDRAIN_PASSES` (32) — realistic legitimate
3871        // cascades stay ≤3 (each iteration drains a fresh post produced
3872        // by the previous fire_deferred); 32 gives 10× headroom and
3873        // panics loudly on a real emit-loop. Per-iteration
3874        // `drain_and_flush` is independently capped by
3875        // `max_batch_drain_iterations` (configurable via
3876        // `Core::set_max_batch_drain_iterations`). A user sink that
3877        // emit-loops forever was a stack overflow pre-S2b — same
3878        // hazard, now iteration-shaped (no stack growth, bounded by
3879        // the cap, fail-loud).
3880        let mut redrain_passes: u32 = 0;
3881        loop {
3882            redrain_passes += 1;
3883            assert!(
3884                redrain_passes <= D260_MAX_REDRAIN_PASSES,
3885                "D260: wave-end drain-to-quiescence loop did not converge in \
3886                 {D260_MAX_REDRAIN_PASSES} passes (mailbox_runnable={mb}, \
3887                 deferred_runnable={df}). A producer-build sink is likely \
3888                 in an emit-loop: each `fire_deferred` pass posts a fresh \
3889                 `MailboxOp` that retriggers another `fire_deferred` pass. \
3890                 Pre-S2b this would have been a stack overflow; D260 \
3891                 iteration-shapes the hazard with this cap. Investigate \
3892                 the producer-build sink that consumes its own output.",
3893                mb = self.core.mailbox.is_runnable(),
3894                df = self.core.deferred.is_runnable(),
3895            );
3896            if let Err(payload) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
3897                self.core.drain_and_flush();
3898            })) {
3899                self.discard_wave_cleanup();
3900                self.core.clear_in_tick();
3901                std::panic::resume_unwind(payload);
3902            }
3903            // Wave cleanup + extract deferred jobs under the lock.
3904            let (jobs, releases, cleanup_hooks, pending_wipes, snapshot_releases) = {
3905                let mut s = self.core.lock_state();
3906                // Q-beyond Sub-slice 1 + 3 (D108, 2026-05-09): WaveState
3907                // borrowed alongside state for wave-end cleanup. Per-thread;
3908                // independent of state. Sub-slice 3 moved deferred_* drains
3909                // into WaveState. /qa F1+F2 (2026-05-10) reverted in_tick +
3910                // currently_firing back to CoreState — clear via
3911                // CoreState::clear_wave_state under the held state lock.
3912                let result = with_wave_state(|ws| {
3913                    s.clear_wave_state(ws);
3914                    // Step 2a (D220-EXEC): defensive `currently_firing`
3915                    // clear, relocated here from `CoreState::clear_wave_state`
3916                    // (the field moved to the separate `CoreShared` region;
3917                    // `St`'s `.shared` reaches it, a `&mut CoreState` can't).
3918                    // Same wave-end point; `FiringGuard` RAII already
3919                    // balances push/pop — this is the belt-and-suspenders
3920                    // net for a future guard-bypassing path.
3921                    s.shared.currently_firing.clear();
3922                    ws.clear_wave_state();
3923                    // /qa A1 (2026-05-09) discipline preserved: drain snapshot
3924                    // retains under lock, release lock-released below to avoid
3925                    // binding re-entrance under held mutex / borrow.
3926                    let snapshot_releases = Core::drain_wave_cache_snapshots(ws);
3927                    // `drain_deferred` takes `deferred_flush_jobs` +
3928                    // `deferred_handle_releases` (incl. rotation releases pushed
3929                    // by `clear_wave_state` above) + Slice E2
3930                    // `deferred_cleanup_hooks` + Slice E2 /qa Q2(b)
3931                    // `pending_wipes` — all from WaveState post-Sub-slice-3.
3932                    let (jobs, releases, hooks, wipes) = Core::drain_deferred(&mut s, ws);
3933                    (jobs, releases, hooks, wipes, snapshot_releases)
3934                });
3935                // Release wave ownership now — AFTER drain + WaveState
3936                // cleanup, BEFORE `fire_deferred` below. Load-bearing: a sink
3937                // re-entering Core from a flush callback must observe
3938                // `in_tick` clear so its emit runs as a fresh owning wave.
3939                // (Mirrors the placement of the pre-D047 `s.in_tick = false`;
3940                // the drain-phase-panic window that placement had is closed
3941                // by the `catch_unwind` above.)
3942                self.core.clear_in_tick();
3943                result
3944            };
3945            // Lock dropped — fire deferred sinks + release retains + fire
3946            // cleanup hooks (Slice E2 OnInvalidate, D060 catch_unwind drain)
3947            // + fire eager wipes (D069).
3948            //
3949            // D260 /qa P1 (2026-05-20): wrap `fire_deferred` in `catch_unwind`
3950            // so a sink panic inside this iteration (`fire_deferred`'s own
3951            // `last_panic` + `resume_unwind`-at-end discipline propagates a
3952            // panic out) doesn't bypass the per-iteration post-`fire_deferred`
3953            // cleanup (snapshot_releases at line ~3910, plus the outer
3954            // wave-end `tier3_clear` + `drain_deferred_producer_ops` after
3955            // the loop). Mirrors the L3844 drain-phase wrap. On panic:
3956            // release the queued `snapshot_releases` defensively
3957            // lock-released, run the outer wave-end finalization
3958            // (`tier3_clear` + `drain_deferred_producer_ops` — even though
3959            // the latter is a D211 no-op shim today, it's part of the
3960            // documented wave-end contract), then `resume_unwind` so the
3961            // caller observes the panic.
3962            let fire_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
3963                self.core
3964                    .fire_deferred(jobs, releases, cleanup_hooks, pending_wipes);
3965            }));
3966            // /qa A1 fix (2026-05-09): release wave_cache_snapshots retains
3967            // lock-released. Pre-A1 these were released inside the held
3968            // state + cross_partition locks; binding finalizers re-entering
3969            // Core would deadlock against either mutex. Drained earlier
3970            // under the lock; released here after both mutexes dropped and
3971            // sinks have fired. Runs even on `fire_deferred` panic — these
3972            // retains were lifted out of the wave state already and need
3973            // releasing regardless.
3974            for h in snapshot_releases {
3975                self.core.binding.release_handle(h);
3976            }
3977            if let Err(payload) = fire_result {
3978                // /qa P1: run wave-end finalization defensively before
3979                // propagating the panic. tier3_clear avoids stale-entry
3980                // leakage across cargo's thread-reuse (mirrors the
3981                // wave-start defensive clear in `begin_batch_with_guards`).
3982                // drain_deferred_producer_ops is a D211 no-op shim today
3983                // but is part of the documented wave-end contract.
3984                tier3_clear();
3985                self.core.drain_deferred_producer_ops();
3986                std::panic::resume_unwind(payload);
3987            }
3988            // D260: check if `fire_deferred` posted new work to mailbox/
3989            // deferred. Quiescent ⇒ done. Else: re-claim `in_tick` (cleared
3990            // above, before `fire_deferred`) and loop the full sequence.
3991            if !self.core.mailbox.is_runnable() && !self.core.deferred.is_runnable() {
3992                break;
3993            }
3994            // Re-claim wave ownership for the secondary drain pass. The
3995            // previous iteration's `clear_in_tick` ran before its
3996            // `fire_deferred`, so the slot is `0` here. `claim_in_tick`
3997            // panics fail-loud on cross-Core mismatch (D252); a
3998            // same-thread same-Core re-claim must succeed-outermost.
3999            let owns = self.core.claim_in_tick();
4000            debug_assert!(
4001                owns,
4002                "D260: secondary drain pass should always succeed-outermost \
4003                 (in_tick was cleared by the previous iteration's pre-fire_deferred clear)"
4004            );
4005            // /qa P2 (release-build safety): if `claim_in_tick` silently
4006            // returned `false` (slot already held — should be impossible
4007            // by-construction under D255 single-owner / D248 actor model,
4008            // but defense-in-depth), break the loop cleanly rather than
4009            // running `drain_and_flush` without ownership. A subsequent
4010            // outer wave entry will catch the still-runnable mailbox.
4011            if !owns {
4012                break;
4013            }
4014        }
4015        // D1 patch (2026-05-09): clear the per-thread Slice G tier3
4016        // tracker at outermost wave-end (success path). Mirrors the
4017        // panic-discard branch above. Thread-local outlives BatchGuard
4018        // by default; cargo's thread-reuse across tests would propagate
4019        // stale entries. Cleared after sinks fire (sink callbacks may
4020        // re-enter Core via emit and could read the tier3 set
4021        // mid-wave; the wave is over here so clearing is safe).
4022        tier3_clear();
4023        // D246/S2c: no per-partition wave-owner guards to release
4024        // (single-owner ⇒ the §7 wave-locks are deleted).
4025        // Phase H+ STRICT (D115): drain deferred producer ops at
4026        // wave-end (now a no-op shim — §7 deleted the deferred-producer
4027        // queue; retained so call sites compile unchanged, D211).
4028        self.core.drain_deferred_producer_ops();
4029    }
4030}