graphrefly-operators 0.0.7

Built-in operator node types for GraphReFly (map, filter, scan, switchMap, valve, gate, retry, …)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
// D248: post-S2c the substrate is `!Send + !Sync` single-owner Core; the
// Sink/TopologySink callbacks were deliberately relaxed to `Arc<dyn Fn>`
// (dropped `+ Send + Sync`). Rc would suffice and is the architecturally
// correct type for inherently single-owner sinks — the Arc→Rc cleanup is
// a separate slice tracked in porting-deferred.md. Until then, `Arc` is
// over-conservative but correct, and this file's Arc<Sink> sites cite
// the deliberate D248 relaxation, not a missed Send+Sync bound.
#![allow(clippy::arc_with_non_send_sync)]

//! Concrete implementations of the four subscription-managed combinators
//! (zip / concat / race / takeUntil). Built on the
//! [`super::producer::ProducerCtx`] substrate.

// Each sink closure runs a small phase-1/phase-2 dance (lock state,
// collect actions, drop lock, replay actions). The match-then-if
// structure inside phase 1 is intentional for readability; collapsing
// to `match { Some(...) if cond => ... }` obscures the lock-discipline.
#![allow(clippy::collapsible_if, clippy::collapsible_match)]
// `zip` is genuinely large (multi-arity tuple-pack with terminal-
// cascade handling). Splitting would obscure the concurrent state-
// machine logic across helpers without clear benefit.
#![allow(clippy::too_many_lines)]

use std::collections::VecDeque;
use std::sync::{Arc, Mutex};

use graphrefly_core::{Core, HandleId, NodeId, Sink};
use smallvec::SmallVec;

use super::error::OperatorFactoryError;
use super::producer::{ProducerBinding, ProducerCtx};

// =====================================================================
// zip — pair handles N-wise across N sources
// =====================================================================

/// Per-zip-node state: one FIFO queue per source, plus a flag for each
/// source's terminal. Lives behind `Arc<Mutex<_>>` captured by the
/// build + sink closures.
struct ZipState {
    queues: Vec<VecDeque<HandleId>>,
    completed: Vec<bool>,
    errored: bool,
    terminated: bool,
}

impl ZipState {
    fn new(n: usize) -> Self {
        Self {
            queues: (0..n).map(|_| VecDeque::new()).collect(),
            completed: vec![false; n],
            errored: false,
            terminated: false,
        }
    }
}

/// `zip(s1, s2, ..., sN)` — collect one value from each source, emit a
/// tuple, repeat. Models RxJS / TS `zip`:
///
/// - Each upstream DATA pushes into that source's per-source queue.
/// - When **every** queue has at least one entry, pop one from each,
///   pack into a tuple via [`graphrefly_core::BindingBoundary::pack_tuple`],
///   and emit on the producer.
/// - On any source's COMPLETE: if its queue is empty, terminate the
///   producer with COMPLETE. Otherwise continue draining; terminate
///   when this source's queue becomes empty (zip can't produce a
///   tuple without input from every source).
/// - On any source's ERROR: terminate the producer with the same
///   ERROR (first error wins, like merge per Slice C-2 D022).
///
/// Empty source list (`n == 0`) emits a single empty-tuple event then
/// completes. Single source (`n == 1`) is identity-passthrough.
///
/// # Refcount discipline
///
/// Each upstream DATA handle is `retain_handle`-bumped before being
/// pushed onto a queue (the inbound message's payload retain belongs
/// to the wave-end-flush release path; we take our own share for the
/// queue). On pop, component handles are passed to `pack_tuple` which
/// must NOT consume or release them — the caller (zip) retains
/// ownership throughout the call and releases each component handle's
/// queue share after `pack_tuple` returns. The returned tuple handle
/// has a pre-bumped retain (binding convention per D020 doc on
/// [`BindingBoundary::pack_tuple`]).
/// # Errors
///
/// Returns [`OperatorFactoryError::EmptySources`] when `sources` is empty
/// (R5.7.x — zip requires ≥1 source; vacuous-tuple semantics rejected).
pub fn zip(
    core: &Core,
    binding: &Arc<dyn ProducerBinding>,
    sources: Vec<NodeId>,
    pack_fn_id: graphrefly_core::FnId,
) -> Result<NodeId, OperatorFactoryError> {
    // R5.7.x — zip requires ≥1 source. Mirrors `combine::combine` (which
    // raises the same factory-shape invariant) so all bindings can route
    // through `operator_factory_error_to_napi` / equivalent.
    if sources.is_empty() {
        return Err(OperatorFactoryError::EmptySources);
    }
    let n = sources.len();
    // Weak-Arc captures break the BenchBinding → registry → producer_builds
    // → closure → strong-Arc<dyn ProducerBinding> cycle that would otherwise
    // pin the entire graph state when the host BenchCore drops with active
    // producer registrations. See `Core::weak_handle` doc + Slice Y close.

    let build = Box::new(move |ctx: ProducerCtx<'_>| {
        let producer_id = ctx.node_id();
        let binding_clone = ctx.core().binding();
        let em = ctx.emitter();
        // R5.7.x — n >= 1 guaranteed by factory-level empty-sources check.
        let state: Arc<Mutex<ZipState>> = Arc::new(Mutex::new(ZipState::new(n)));

        for (idx, &source) in sources.iter().enumerate() {
            let state_inner = state.clone();
            // Sinks live only while the producer is active (cleared via
            // producer_deactivate on last-subscriber unsubscribe), so they
            // can safely capture strong refs cloned from the upgraded weaks.
            let core_inner = em.clone();
            let binding_inner = binding_clone.clone();
            let sink: Sink = Arc::new(move |msgs| {
                // Phase 1 (lock held): mutate queues + collect actions.
                // Phase 2 (lock released): pack tuples + re-enter Core.
                enum PostLockAction {
                    /// Pack popped handles into a tuple, release components, emit.
                    PackAndEmit(Vec<HandleId>),
                    Complete,
                    Error(HandleId),
                }
                let mut post_actions: SmallVec<[PostLockAction; 4]> = SmallVec::new();
                // Handles to release after the lock drops (P2:
                // drain queues on terminate to avoid handle leaks).
                let mut to_release: SmallVec<[HandleId; 8]> = SmallVec::new();
                {
                    let mut s = state_inner.lock().unwrap();
                    if s.terminated {
                        return;
                    }
                    // Tier-based dispatch (canonical §4.2; see
                    // `feedback_use_tier_for_signal_routing.md`). Tier 3
                    // payload_handle.is_some() = DATA; tier 5
                    // payload_handle.is_some() = ERROR else COMPLETE.
                    for m in msgs {
                        match m.tier() {
                            3 => {
                                if let Some(h) = m.payload_handle() {
                                    binding_inner.retain_handle(h);
                                    s.queues[idx].push_back(h);
                                    // Collect complete tuples — pack_tuple runs
                                    // after the lock drops (P5).
                                    while s.queues.iter().all(|q| !q.is_empty()) {
                                        let popped: Vec<HandleId> = s
                                            .queues
                                            .iter_mut()
                                            .map(|q| q.pop_front().unwrap())
                                            .collect();
                                        post_actions.push(PostLockAction::PackAndEmit(popped));
                                    }
                                }
                                // else: Resolved on a source — no action.
                            }
                            5 => {
                                if let Some(h) = m.payload_handle() {
                                    // Error
                                    if !s.errored && !s.terminated {
                                        s.errored = true;
                                        s.terminated = true;
                                        binding_inner.retain_handle(h);
                                        // P2: release all remaining queued handles.
                                        for q in &mut s.queues {
                                            to_release.extend(q.drain(..));
                                        }
                                        post_actions.push(PostLockAction::Error(h));
                                    }
                                } else {
                                    // Complete
                                    s.completed[idx] = true;
                                    // If this source's queue is empty, no more
                                    // tuples from it — terminate.
                                    if s.queues[idx].is_empty() && !s.terminated {
                                        s.terminated = true;
                                        // P2: release all remaining queued handles.
                                        for q in &mut s.queues {
                                            to_release.extend(q.drain(..));
                                        }
                                        post_actions.push(PostLockAction::Complete);
                                    }
                                }
                            }
                            _ => {} // Tiers 0/1/2/4/6 — no action.
                        }
                    }
                }
                // Release leaked queue handles outside the lock.
                for h in to_release {
                    binding_inner.release_handle(h);
                }
                // Phase 2 (lock released): pack tuples + re-enter Core.
                // P5: pack_tuple runs outside the per-zip lock to avoid
                // deadlock if the binding's pack_tuple re-enters.
                for action in post_actions {
                    match action {
                        PostLockAction::PackAndEmit(popped) => {
                            let tuple_h = binding_inner.pack_tuple(pack_fn_id, &popped);
                            for h in &popped {
                                binding_inner.release_handle(*h);
                            }
                            core_inner.emit_or_defer(producer_id, tuple_h);
                        }
                        PostLockAction::Complete => core_inner.complete_or_defer(producer_id),
                        PostLockAction::Error(h) => core_inner.error_or_defer(producer_id, h),
                    }
                }
            });
            // F2 /qa: on Dead, synthesize the per-source Complete in
            // zip's state machine — `s.completed[idx] = true` and (if
            // queue is empty, which it always is at activation since
            // DATA hasn't yet flowed) self-Complete the producer.
            // Pre-F2 a Dead source left zip waiting on a queue that
            // would never fill → silent wedge.
            let outcome = ctx.subscribe_to(source, sink);
            if matches!(outcome, crate::producer::SubscribeOutcome::Dead { .. }) {
                let core_dead = em.clone();
                let binding_dead = binding_clone.clone();
                let mut should_complete = false;
                let mut to_release: SmallVec<[HandleId; 8]> = SmallVec::new();
                {
                    let mut s = state.lock().unwrap();
                    if !s.terminated {
                        s.completed[idx] = true;
                        if s.queues[idx].is_empty() {
                            s.terminated = true;
                            for q in &mut s.queues {
                                to_release.extend(q.drain(..));
                            }
                            should_complete = true;
                        }
                    }
                }
                for h in to_release {
                    binding_dead.release_handle(h);
                }
                if should_complete {
                    core_dead.complete_or_defer(producer_id);
                }
            }
        }
    });

    let fn_id = binding.register_producer_build(build);
    Ok(core
        .register_producer(fn_id)
        .expect("invariant: register_producer has no deps; no error variants reachable"))
}

// =====================================================================
// concat — sequentially forward `first` then `second`
// =====================================================================

struct ConcatState {
    /// 0 = forwarding `first`; 1 = `first` complete, forwarding `second`.
    phase: u8,
    /// Buffered DATA from `second` that arrived during phase 0 (before
    /// `first` completed). Drained on phase transition.
    pending: VecDeque<HandleId>,
    /// Set to true if `second` completed during phase 0. On phase
    /// transition, after draining `pending`, concat self-completes
    /// because `second` won't emit Complete again (D041 / D-ops /qa D4).
    second_completed: bool,
    terminated: bool,
}

impl ConcatState {
    fn new() -> Self {
        Self {
            phase: 0,
            pending: VecDeque::new(),
            second_completed: false,
            terminated: false,
        }
    }
}

/// `concat(first, second)` — forward DATA from `first` until it
/// completes, then drain any DATA `second` emitted during phase 1
/// (buffered) and continue forwarding `second`. ERROR from either
/// source terminates the producer with the same ERROR.
///
/// Subscribes to BOTH sources at activation time (matches TS impl in
/// `extra/operators/combine.ts:332-379` so `second.subscribe` doesn't
/// race after `first` completes). DATA from `second` during phase 0
/// is buffered, not forwarded.
#[must_use]
pub fn concat(
    core: &Core,
    binding: &Arc<dyn ProducerBinding>,
    first: NodeId,
    second: NodeId,
) -> NodeId {
    // Weak captures break the producer-build Arc cycle (see `zip` doc).

    let build = Box::new(move |ctx: ProducerCtx<'_>| {
        let producer_id = ctx.node_id();
        let binding_clone = ctx.core().binding();
        let em = ctx.emitter();
        let state: Arc<Mutex<ConcatState>> = Arc::new(Mutex::new(ConcatState::new()));

        // Subscribe to second FIRST so phase-0 DATA buffering catches
        // synchronous initial emissions. Sinks capture strong refs cloned
        // from the upgraded weaks; sink lifetime tied to producer activation.
        let state_for_second = state.clone();
        let core_for_second = em.clone();
        let binding_for_second = binding_clone.clone();
        let second_sink: Sink = Arc::new(move |msgs| {
            enum Action {
                Emit(HandleId),
                Complete,
                Error(HandleId),
            }
            let mut actions: SmallVec<[Action; 4]> = SmallVec::new();
            let mut to_release: SmallVec<[HandleId; 4]> = SmallVec::new();
            {
                let mut s = state_for_second.lock().unwrap();
                if s.terminated {
                    return;
                }
                // Tier-based dispatch (canonical §4.2).
                for m in msgs {
                    match m.tier() {
                        3 => {
                            if let Some(h) = m.payload_handle() {
                                if s.phase == 0 {
                                    // Buffer for later drain.
                                    binding_for_second.retain_handle(h);
                                    s.pending.push_back(h);
                                } else {
                                    binding_for_second.retain_handle(h);
                                    actions.push(Action::Emit(h));
                                }
                            }
                            // else: Resolved on second source — no action.
                        }
                        5 => {
                            if let Some(h) = m.payload_handle() {
                                // Error
                                if !s.terminated {
                                    s.terminated = true;
                                    binding_for_second.retain_handle(h);
                                    // P2: release buffered pending handles.
                                    to_release.extend(s.pending.drain(..));
                                    actions.push(Action::Error(h));
                                }
                            } else {
                                // Complete
                                if s.phase == 1 && !s.terminated {
                                    s.terminated = true;
                                    actions.push(Action::Complete);
                                } else if s.phase == 0 {
                                    // D041 / D4 fix: remember that second
                                    // completed during phase 0. On phase
                                    // transition, after draining `pending`,
                                    // first_sink will self-complete
                                    // (second's Complete fires once and
                                    // won't be re-observed).
                                    s.second_completed = true;
                                }
                            }
                        }
                        _ => {} // Tiers 0/1/2/4/6 — no action.
                    }
                }
            }
            for h in to_release {
                binding_for_second.release_handle(h);
            }
            for action in actions {
                match action {
                    Action::Emit(h) => core_for_second.emit_or_defer(producer_id, h),
                    Action::Complete => core_for_second.complete_or_defer(producer_id),
                    Action::Error(h) => core_for_second.error_or_defer(producer_id, h),
                }
            }
        });
        // F2 /qa: Dead `second` is observed via `second_completed` flag.
        // First-Complete drains pending and self-Completes if second
        // already completed; same logic handles Dead second.
        let second_outcome = ctx.subscribe_to(second, second_sink);
        if matches!(
            second_outcome,
            crate::producer::SubscribeOutcome::Dead { .. }
        ) {
            let mut s = state.lock().unwrap();
            s.second_completed = true;
            // No additional action — the first-Complete path or first-Dead
            // path below will trigger producer-Complete.
        }

        let state_for_first = state.clone();
        let core_for_first = em.clone();
        let binding_for_first = binding_clone.clone();
        let first_sink: Sink = Arc::new(move |msgs| {
            // first.Complete triggers the phase transition (handled
            // via `s.phase = 1` + draining pending into `actions`),
            // and may also self-complete the producer if `second`
            // already completed during phase 0 (D041 / D4 fix).
            enum Action {
                Emit(HandleId),
                Complete,
                Error(HandleId),
            }
            let mut actions: SmallVec<[Action; 4]> = SmallVec::new();
            let mut to_release: SmallVec<[HandleId; 4]> = SmallVec::new();
            {
                let mut s = state_for_first.lock().unwrap();
                if s.terminated {
                    return;
                }
                if s.phase != 0 {
                    return; // first is done; ignore stale messages.
                }
                for m in msgs {
                    // Slice E /qa: defensive per-iteration `terminated`
                    // guard. The outer guard at the top of the lock
                    // block catches a `terminated` set BEFORE this
                    // batch arrived; this per-iteration check catches
                    // the case where an earlier message in the SAME
                    // batch transitioned us terminal (e.g., post-
                    // Complete the phase moved to 1, but a defensively-
                    // emitted stale `[Data]` later in the same batch
                    // would otherwise queue a useless retain that
                    // `core.emit` would discard on a terminal
                    // producer).
                    if s.terminated || s.phase != 0 {
                        break;
                    }
                    // Tier-based dispatch (canonical §4.2).
                    match m.tier() {
                        3 => {
                            if let Some(h) = m.payload_handle() {
                                binding_for_first.retain_handle(h);
                                actions.push(Action::Emit(h));
                            }
                            // else: Resolved on first source — no action.
                        }
                        5 => {
                            if let Some(h) = m.payload_handle() {
                                // Error
                                if !s.terminated {
                                    s.terminated = true;
                                    binding_for_first.retain_handle(h);
                                    // P2: release buffered pending handles.
                                    to_release.extend(s.pending.drain(..));
                                    actions.push(Action::Error(h));
                                }
                            } else {
                                // Complete — phase transition: drain pending
                                // second-data, then continue forwarding from
                                // second.
                                s.phase = 1;
                                // Pending handles already retained at buffer time.
                                for h in s.pending.drain(..) {
                                    actions.push(Action::Emit(h));
                                }
                                // D041 / D4 fix: if second already completed
                                // during phase 0, self-complete now (its
                                // Complete fired once and won't re-fire).
                                if s.second_completed && !s.terminated {
                                    s.terminated = true;
                                    actions.push(Action::Complete);
                                }
                            }
                        }
                        _ => {} // Tiers 0/1/2/4/6 — no action.
                    }
                }
            }
            for h in to_release {
                binding_for_first.release_handle(h);
            }
            for action in actions {
                match action {
                    Action::Emit(h) => core_for_first.emit_or_defer(producer_id, h),
                    Action::Complete => core_for_first.complete_or_defer(producer_id),
                    Action::Error(h) => core_for_first.error_or_defer(producer_id, h),
                }
            }
        });
        // F2 /qa: Dead `first` triggers the phase transition immediately
        // (treat as first-Complete). If `second` is also dead (or already
        // completed in phase 0), self-Complete; else continue forwarding
        // pending+future from second.
        let first_outcome = ctx.subscribe_to(first, first_sink);
        if matches!(
            first_outcome,
            crate::producer::SubscribeOutcome::Dead { .. }
        ) {
            let core_first_dead = em.clone();
            let mut should_complete = false;
            let mut pending_to_emit: Vec<HandleId> = Vec::new();
            {
                let mut s = state.lock().unwrap();
                if !s.terminated && s.phase == 0 {
                    s.phase = 1;
                    // Drain pending second-DATA buffered during phase 0.
                    pending_to_emit.extend(s.pending.drain(..));
                    // If second already completed (or was Dead), self-Complete.
                    if s.second_completed && !s.terminated {
                        s.terminated = true;
                        should_complete = true;
                    }
                }
            }
            for h in pending_to_emit {
                core_first_dead.emit_or_defer(producer_id, h);
            }
            if should_complete {
                core_first_dead.complete_or_defer(producer_id);
            }
        }
    });

    let fn_id = binding.register_producer_build(build);
    core.register_producer(fn_id)
        .expect("invariant: register_producer has no deps; no error variants reachable")
}

// =====================================================================
// race — first source to emit DATA wins; losers are ignored
// =====================================================================

struct RaceState {
    /// Index of the winning source, or `None` if no winner yet.
    winner: Option<usize>,
    /// Per-source completed flags. When all complete without a winner,
    /// the producer completes (P4: no-winner all-complete termination).
    completed: Vec<bool>,
    terminated: bool,
}

impl RaceState {
    fn new(n: usize) -> Self {
        Self {
            winner: None,
            completed: vec![false; n],
            terminated: false,
        }
    }
}

/// `race(s1, s2, ..., sN)` — subscribes to all sources; the first to
/// emit DATA wins. Subsequent traffic from the winner is forwarded;
/// losers' messages are no-ops (per Q4=(b) — losers stay subscribed
/// but their sink callbacks short-circuit). Saves the dynamic
/// rewiring cost of explicitly unsubscribing losers.
///
/// Empty source list completes immediately. Single source is
/// identity-passthrough.
/// # Errors
///
/// Returns [`OperatorFactoryError::EmptySources`] when `sources` is empty
/// (R5.7.x — race requires ≥1 source; no-winner-possible rejected).
pub fn race(
    core: &Core,
    binding: &Arc<dyn ProducerBinding>,
    sources: Vec<NodeId>,
) -> Result<NodeId, OperatorFactoryError> {
    // R5.7.x — race requires ≥1 source. Mirrors `combine::combine`.
    if sources.is_empty() {
        return Err(OperatorFactoryError::EmptySources);
    }
    let n = sources.len();
    // Weak captures break the producer-build Arc cycle (see `zip` doc).

    let build = Box::new(move |ctx: ProducerCtx<'_>| {
        let producer_id = ctx.node_id();
        let binding_clone = ctx.core().binding();
        let em = ctx.emitter();
        // R5.7.x — n >= 1 guaranteed by factory-level empty-sources check.
        let state: Arc<Mutex<RaceState>> = Arc::new(Mutex::new(RaceState::new(n)));

        for (idx, &source) in sources.iter().enumerate() {
            let state_inner = state.clone();
            let core_inner = em.clone();
            let binding_inner = binding_clone.clone();
            let sink: Sink = Arc::new(move |msgs| {
                enum Action {
                    Emit(HandleId),
                    Complete,
                    Error(HandleId),
                }
                let mut actions: SmallVec<[Action; 4]> = SmallVec::new();
                {
                    let mut s = state_inner.lock().unwrap();
                    if s.terminated {
                        return;
                    }
                    // Tier-based dispatch (canonical §4.2).
                    for m in msgs {
                        match m.tier() {
                            3 => {
                                if let Some(h) = m.payload_handle() {
                                    // P3: check s.winner live each iteration —
                                    // this source may have just become the winner
                                    // earlier in this batch.
                                    if s.winner.is_none() {
                                        s.winner = Some(idx);
                                        binding_inner.retain_handle(h);
                                        actions.push(Action::Emit(h));
                                    } else if s.winner == Some(idx) {
                                        binding_inner.retain_handle(h);
                                        actions.push(Action::Emit(h));
                                    }
                                    // else: loser DATA — ignore.
                                }
                                // else: Resolved on a source — no action.
                            }
                            5 => {
                                if let Some(h) = m.payload_handle() {
                                    // Error — from any source pre-winner OR from
                                    // the winner cascade; loser errors post-winner
                                    // are ignored.
                                    if (s.winner.is_none() || s.winner == Some(idx))
                                        && !s.terminated
                                    {
                                        s.terminated = true;
                                        binding_inner.retain_handle(h);
                                        actions.push(Action::Error(h));
                                    }
                                } else {
                                    // Complete
                                    s.completed[idx] = true;
                                    if s.winner == Some(idx) && !s.terminated {
                                        s.terminated = true;
                                        actions.push(Action::Complete);
                                    } else if s.winner.is_none()
                                        && s.completed.iter().all(|&c| c)
                                        && !s.terminated
                                    {
                                        // P4: all sources completed without a
                                        // winner — terminate the producer.
                                        s.terminated = true;
                                        actions.push(Action::Complete);
                                    }
                                    // else: loser complete — ignore.
                                }
                            }
                            _ => {} // Tiers 0/1/2/4/6 — no action.
                        }
                    }
                }
                for action in actions {
                    match action {
                        Action::Emit(h) => core_inner.emit_or_defer(producer_id, h),
                        Action::Complete => core_inner.complete_or_defer(producer_id),
                        Action::Error(h) => core_inner.error_or_defer(producer_id, h),
                    }
                }
            });
            // F2 /qa: on Dead, treat as `completed[idx] = true`. If
            // all sources are now completed without a winner, self-
            // Complete (matches the P4 "all completed no winner"
            // branch in the per-source sink above).
            let outcome = ctx.subscribe_to(source, sink);
            if matches!(outcome, crate::producer::SubscribeOutcome::Dead { .. }) {
                let core_dead = em.clone();
                let mut should_complete = false;
                {
                    let mut s = state.lock().unwrap();
                    if !s.terminated && s.winner.is_none() {
                        s.completed[idx] = true;
                        if s.completed.iter().all(|&c| c) {
                            s.terminated = true;
                            should_complete = true;
                        }
                    }
                }
                if should_complete {
                    core_dead.complete_or_defer(producer_id);
                }
            }
        }
    });

    let fn_id = binding.register_producer_build(build);
    Ok(core
        .register_producer(fn_id)
        .expect("invariant: register_producer has no deps; no error variants reachable"))
}

// =====================================================================
// takeUntil — terminate when notifier emits DATA
// =====================================================================

struct TakeUntilState {
    terminated: bool,
}

impl TakeUntilState {
    fn new() -> Self {
        Self { terminated: false }
    }
}

/// `take_until(source, notifier)` — forward DATA from `source` until
/// `notifier` emits its first DATA, then terminate the producer with
/// COMPLETE. Errors from either source cascade. Source COMPLETE
/// terminates the producer.
///
/// Notifier DATA is consumed but never forwarded (zero-FFI on the
/// notifier path — we don't dereference its payload, just use the
/// emission as a signal).
#[must_use]
pub fn take_until(
    core: &Core,
    binding: &Arc<dyn ProducerBinding>,
    source: NodeId,
    notifier: NodeId,
) -> NodeId {
    // Weak captures break the producer-build Arc cycle (see `zip` doc).

    let build = Box::new(move |ctx: ProducerCtx<'_>| {
        let producer_id = ctx.node_id();
        let binding_clone = ctx.core().binding();
        let em = ctx.emitter();
        let state: Arc<Mutex<TakeUntilState>> = Arc::new(Mutex::new(TakeUntilState::new()));

        // Source sink: forward DATA, propagate terminals.
        let state_for_source = state.clone();
        let core_for_source = em.clone();
        let binding_for_source = binding_clone.clone();
        let source_sink: Sink = Arc::new(move |msgs| {
            enum Action {
                Emit(HandleId),
                Complete,
                Error(HandleId),
            }
            let mut actions: SmallVec<[Action; 4]> = SmallVec::new();
            {
                let mut s = state_for_source.lock().unwrap();
                if s.terminated {
                    return;
                }
                // Tier-based dispatch (canonical §4.2).
                for m in msgs {
                    match m.tier() {
                        3 => {
                            if let Some(h) = m.payload_handle() {
                                binding_for_source.retain_handle(h);
                                actions.push(Action::Emit(h));
                            }
                            // else: Resolved on source — no action.
                        }
                        5 => {
                            if let Some(h) = m.payload_handle() {
                                // Error
                                if !s.terminated {
                                    s.terminated = true;
                                    binding_for_source.retain_handle(h);
                                    actions.push(Action::Error(h));
                                }
                            } else {
                                // Complete
                                if !s.terminated {
                                    s.terminated = true;
                                    actions.push(Action::Complete);
                                }
                            }
                        }
                        _ => {} // Tiers 0/1/2/4/6 — no action.
                    }
                }
            }
            for action in actions {
                match action {
                    Action::Emit(h) => core_for_source.emit_or_defer(producer_id, h),
                    Action::Complete => core_for_source.complete_or_defer(producer_id),
                    Action::Error(h) => core_for_source.error_or_defer(producer_id, h),
                }
            }
        });
        // F2 /qa: Dead `source` → self-Complete (source is permanently
        // over, so take_until has nothing to forward and the producer
        // is finished).
        let source_outcome = ctx.subscribe_to(source, source_sink);
        if matches!(
            source_outcome,
            crate::producer::SubscribeOutcome::Dead { .. }
        ) {
            let core_dead = em.clone();
            let mut should_complete = false;
            {
                let mut s = state.lock().unwrap();
                if !s.terminated {
                    s.terminated = true;
                    should_complete = true;
                }
            }
            if should_complete {
                core_dead.complete_or_defer(producer_id);
            }
        }

        // Notifier sink: any DATA → terminate; ERROR → cascade.
        let state_for_notifier = state.clone();
        let core_for_notifier = em.clone();
        let binding_for_notifier = binding_clone.clone();
        let notifier_sink: Sink = Arc::new(move |msgs| {
            enum Action {
                Complete,
                Error(HandleId),
            }
            let mut action: Option<Action> = None;
            {
                let mut s = state_for_notifier.lock().unwrap();
                if s.terminated {
                    return;
                }
                // Tier-based dispatch (canonical §4.2).
                for m in msgs {
                    match m.tier() {
                        3 => {
                            // Any DATA on notifier → complete the producer.
                            // (Resolved alone — no payload — no action.)
                            // We don't emit notifier DATA downstream, so we
                            // don't even need to extract the handle.
                            if m.payload_handle().is_some() && !s.terminated {
                                s.terminated = true;
                                action = Some(Action::Complete);
                                break;
                            }
                        }
                        5 => {
                            // Error: cascade. Complete (payload_handle.is_none())
                            // without prior DATA: nothing to do — source
                            // continues independently.
                            if let Some(h) = m.payload_handle() {
                                if !s.terminated {
                                    s.terminated = true;
                                    binding_for_notifier.retain_handle(h);
                                    action = Some(Action::Error(h));
                                    break;
                                }
                            }
                        }
                        _ => {} // Tiers 0/1/2/4/6 — no action.
                    }
                }
            }
            if let Some(a) = action {
                match a {
                    Action::Complete => core_for_notifier.complete_or_defer(producer_id),
                    Action::Error(h) => core_for_notifier.error_or_defer(producer_id, h),
                }
            }
        });
        // F2 /qa: Dead `notifier` → ignore. Notifier signal can never
        // fire, so take_until reduces to a passthrough of source. The
        // source's own Complete/Error will terminate the producer
        // normally; if source is also Dead, the source-Dead branch
        // above already self-Completed.
        let _ = ctx.subscribe_to(notifier, notifier_sink);
    });

    let fn_id = binding.register_producer_build(build);
    core.register_producer(fn_id)
        .expect("invariant: register_producer has no deps; no error variants reachable")
}