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
// 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)]

//! Control operators — side-effect, gating, error recovery, convergence.
//!
//! # Operators
//!
//! - [`tap`] / [`tap_observer`] — side-effect passthrough.
//! - [`on_first_data`] — one-shot side-effect on first DATA.
//! - [`rescue`] — error recovery via user callback.
//! - [`valve`] — boolean-gated passthrough with optional cancellation.
//! - [`settle`] — wave-count convergence detector.
//! - [`repeat`] — sequential resubscribe loop.

#![allow(clippy::too_many_lines, clippy::items_after_statements)]

use std::sync::Arc;

use parking_lot::Mutex;

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

use crate::producer::{ProducerBinding, ProducerBuildFn, ProducerCtx, SubscribeOutcome};

// =========================================================================
// tap(source, fn_id) — side-effect passthrough
// =========================================================================

/// Passthrough operator that forwards all DATA unchanged. On each DATA,
/// calls `binding.invoke_tap_fn(fn_id, handle)` as a side-effect.
/// Forwards COMPLETE and ERROR unchanged.
#[must_use]
pub fn tap(core: &Core, binding: &Arc<dyn ProducerBinding>, source: NodeId, fn_id: FnId) -> NodeId {
    let build: ProducerBuildFn = Box::new(move |ctx: ProducerCtx<'_>| {
        let core_s = ctx.core();
        let binding_s = ctx.core().binding();
        let em = ctx.emitter();
        let pid = ctx.node_id();
        let bb: Arc<dyn BindingBoundary> = binding_s.clone();
        let core_sink = em.clone();

        let source_sink: Sink = Arc::new(move |msgs| {
            enum Act {
                EmitAndTap(HandleId),
                Complete,
                Error(HandleId),
            }
            let mut actions: SmallVec<[Act; 4]> = SmallVec::new();
            for m in msgs {
                match m.tier() {
                    3 => {
                        if let Some(h) = m.payload_handle() {
                            bb.retain_handle(h);
                            actions.push(Act::EmitAndTap(h));
                        }
                    }
                    5 => {
                        if let Some(h) = m.payload_handle() {
                            bb.retain_handle(h);
                            actions.push(Act::Error(h));
                        } else {
                            actions.push(Act::Complete);
                        }
                    }
                    _ => {}
                }
            }
            for a in actions {
                match a {
                    Act::EmitAndTap(h) => {
                        bb.invoke_tap_fn(fn_id, h);
                        core_sink.emit_or_defer(pid, h);
                    }
                    Act::Complete => core_sink.complete_or_defer(pid),
                    Act::Error(h) => core_sink.error_or_defer(pid, h),
                }
            }
        });

        let outcome = ctx.subscribe_to(source, source_sink);
        if matches!(outcome, SubscribeOutcome::Dead { .. }) {
            core_s.complete_or_defer(pid);
        }
    });

    let fn_id_reg = binding.register_producer_build(build);
    core.register_producer(fn_id_reg)
        .expect("tap: register_producer failed")
}

// =========================================================================
// tap_observer(source, data_fn, error_fn, complete_fn)
// =========================================================================

/// Like [`tap`] but with lifecycle observer callbacks. Each callback is
/// optional (`None` = skip that lifecycle event).
///
/// - `data_fn_id`: called on each DATA via `invoke_tap_fn`.
/// - `error_fn_id`: called on ERROR via `invoke_tap_error_fn`.
/// - `complete_fn_id`: called on COMPLETE via `invoke_tap_complete_fn`.
///
/// All messages are forwarded unchanged regardless of callback presence.
#[must_use]
pub fn tap_observer(
    core: &Core,
    binding: &Arc<dyn ProducerBinding>,
    source: NodeId,
    data_fn_id: Option<FnId>,
    error_fn_id: Option<FnId>,
    complete_fn_id: Option<FnId>,
) -> NodeId {
    let build: ProducerBuildFn = Box::new(move |ctx: ProducerCtx<'_>| {
        let core_s = ctx.core();
        let binding_s = ctx.core().binding();
        let em = ctx.emitter();
        let pid = ctx.node_id();
        let bb: Arc<dyn BindingBoundary> = binding_s.clone();
        let core_sink = em.clone();

        let source_sink: Sink = Arc::new(move |msgs| {
            enum Act {
                Emit(HandleId),
                Complete,
                Error(HandleId),
            }
            let mut actions: SmallVec<[Act; 4]> = SmallVec::new();
            for m in msgs {
                match m.tier() {
                    3 => {
                        if let Some(h) = m.payload_handle() {
                            bb.retain_handle(h);
                            actions.push(Act::Emit(h));
                        }
                    }
                    5 => {
                        if let Some(h) = m.payload_handle() {
                            bb.retain_handle(h);
                            actions.push(Act::Error(h));
                        } else {
                            actions.push(Act::Complete);
                        }
                    }
                    _ => {}
                }
            }
            for a in actions {
                match a {
                    Act::Emit(h) => {
                        if let Some(fid) = data_fn_id {
                            bb.invoke_tap_fn(fid, h);
                        }
                        core_sink.emit_or_defer(pid, h);
                    }
                    Act::Complete => {
                        if let Some(fid) = complete_fn_id {
                            bb.invoke_tap_complete_fn(fid);
                        }
                        core_sink.complete_or_defer(pid);
                    }
                    Act::Error(h) => {
                        if let Some(fid) = error_fn_id {
                            bb.invoke_tap_error_fn(fid, h);
                        }
                        core_sink.error_or_defer(pid, h);
                    }
                }
            }
        });

        let outcome = ctx.subscribe_to(source, source_sink);
        if matches!(outcome, SubscribeOutcome::Dead { .. }) {
            if let Some(fid) = complete_fn_id {
                binding_s.invoke_tap_complete_fn(fid);
            }
            core_s.complete_or_defer(pid);
        }
    });

    let fn_id = binding.register_producer_build(build);
    core.register_producer(fn_id)
        .expect("tap_observer: register_producer failed")
}

// =========================================================================
// on_first_data(source, fn_id) — one-shot tap
// =========================================================================

/// One-shot side-effect tap. Calls `invoke_tap_fn(fn_id, handle)` on
/// the first DATA only, then becomes a pure passthrough. All messages
/// are forwarded unchanged.
#[must_use]
pub fn on_first_data(
    core: &Core,
    binding: &Arc<dyn ProducerBinding>,
    source: NodeId,
    fn_id: FnId,
) -> NodeId {
    struct OnFirstState {
        fired: bool,
    }

    let build: ProducerBuildFn = Box::new(move |ctx: ProducerCtx<'_>| {
        let core_s = ctx.core();
        let binding_s = ctx.core().binding();
        let em = ctx.emitter();
        let pid = ctx.node_id();
        let bb: Arc<dyn BindingBoundary> = binding_s.clone();
        let core_sink = em.clone();
        let state: Arc<Mutex<OnFirstState>> = Arc::new(Mutex::new(OnFirstState { fired: false }));

        let source_sink: Sink = Arc::new(move |msgs| {
            enum Act {
                EmitWithTap(HandleId),
                Emit(HandleId),
                Complete,
                Error(HandleId),
            }
            let mut actions: SmallVec<[Act; 4]> = SmallVec::new();
            {
                let mut s = state.lock();
                for m in msgs {
                    match m.tier() {
                        3 => {
                            if let Some(h) = m.payload_handle() {
                                bb.retain_handle(h);
                                if s.fired {
                                    actions.push(Act::Emit(h));
                                } else {
                                    s.fired = true;
                                    actions.push(Act::EmitWithTap(h));
                                }
                            }
                        }
                        5 => {
                            if let Some(h) = m.payload_handle() {
                                bb.retain_handle(h);
                                actions.push(Act::Error(h));
                            } else {
                                actions.push(Act::Complete);
                            }
                        }
                        _ => {}
                    }
                }
            }
            for a in actions {
                match a {
                    Act::EmitWithTap(h) => {
                        bb.invoke_tap_fn(fn_id, h);
                        core_sink.emit_or_defer(pid, h);
                    }
                    Act::Emit(h) => core_sink.emit_or_defer(pid, h),
                    Act::Complete => core_sink.complete_or_defer(pid),
                    Act::Error(h) => core_sink.error_or_defer(pid, h),
                }
            }
        });

        let outcome = ctx.subscribe_to(source, source_sink);
        if matches!(outcome, SubscribeOutcome::Dead { .. }) {
            core_s.complete_or_defer(pid);
        }
    });

    let fn_id_reg = binding.register_producer_build(build);
    core.register_producer(fn_id_reg)
        .expect("on_first_data: register_producer failed")
}

// =========================================================================
// rescue(source, fn_id) — error recovery
// =========================================================================

/// Error recovery operator. On ERROR, calls
/// `binding.invoke_rescue_fn(fn_id, error_handle)`:
///
/// - `Ok(recovered_handle)` — emit DATA with the recovered value.
/// - `Err(())` — forward the original ERROR unchanged.
///
/// DATA and COMPLETE pass through unchanged.
#[must_use]
pub fn rescue(
    core: &Core,
    binding: &Arc<dyn ProducerBinding>,
    source: NodeId,
    fn_id: FnId,
) -> NodeId {
    let build: ProducerBuildFn = Box::new(move |ctx: ProducerCtx<'_>| {
        let core_s = ctx.core();
        let binding_s = ctx.core().binding();
        let em = ctx.emitter();
        let pid = ctx.node_id();
        let bb: Arc<dyn BindingBoundary> = binding_s.clone();
        let core_sink = em.clone();

        let source_sink: Sink = Arc::new(move |msgs| {
            enum Act {
                Emit(HandleId),
                Complete,
                TryRescue(HandleId),
            }
            let mut actions: SmallVec<[Act; 4]> = SmallVec::new();
            for m in msgs {
                match m.tier() {
                    3 => {
                        if let Some(h) = m.payload_handle() {
                            bb.retain_handle(h);
                            actions.push(Act::Emit(h));
                        }
                    }
                    5 => {
                        if let Some(h) = m.payload_handle() {
                            bb.retain_handle(h);
                            actions.push(Act::TryRescue(h));
                        } else {
                            actions.push(Act::Complete);
                        }
                    }
                    _ => {}
                }
            }
            for a in actions {
                match a {
                    Act::Emit(h) => core_sink.emit_or_defer(pid, h),
                    Act::Complete => core_sink.complete_or_defer(pid),
                    Act::TryRescue(err_h) => {
                        match bb.invoke_rescue_fn(fn_id, err_h) {
                            Ok(recovered_h) => {
                                // Recovery succeeded — release original error,
                                // emit recovered value as DATA.
                                bb.release_handle(err_h);
                                core_sink.emit_or_defer(pid, recovered_h);
                            }
                            Err(()) => {
                                // Recovery failed — forward original ERROR.
                                core_sink.error_or_defer(pid, err_h);
                            }
                        }
                    }
                }
            }
        });

        let outcome = ctx.subscribe_to(source, source_sink);
        if matches!(outcome, SubscribeOutcome::Dead { .. }) {
            core_s.complete_or_defer(pid);
        }
    });

    let fn_id_reg = binding.register_producer_build(build);
    core.register_producer(fn_id_reg)
        .expect("rescue: register_producer failed")
}

// =========================================================================
// valve(source, control, gate_fn_id, cancel) — boolean gate
// =========================================================================

/// Boolean-gated passthrough. Subscribes to both `source` and `control`.
///
/// - **Control DATA**: evaluates `binding.predicate_each(gate_fn_id,
///   &[handle])` to determine gate state. `true` = open, `false` = closed.
///   On transition from open to closed, if `cancel` is `Some`, invokes
///   `cancel.cancel()`.
/// - **Source DATA**: if gate is open, retains + emits. If closed, drops
///   the handle (source DATA while gate is closed is silently discarded).
/// - **Source COMPLETE/ERROR**: forwarded unchanged.
/// - **Control COMPLETE**: does NOT auto-complete the valve (per TS
///   `completeWhenDepsComplete: false` equivalent).
/// - **Control ERROR**: terminates the valve with ERROR.
#[must_use]
pub fn valve(
    core: &Core,
    binding: &Arc<dyn ProducerBinding>,
    source: NodeId,
    control: NodeId,
    gate_fn_id: FnId,
    cancel: Option<tokio_util::sync::CancellationToken>,
) -> NodeId {
    struct ValveState {
        open: bool,
        terminated: bool,
    }

    let build: ProducerBuildFn = Box::new(move |ctx: ProducerCtx<'_>| {
        let core_s = ctx.core();
        let binding_s = ctx.core().binding();
        let em = ctx.emitter();
        let pid = ctx.node_id();
        let state: Arc<Mutex<ValveState>> = Arc::new(Mutex::new(ValveState {
            open: false,
            terminated: false,
        }));

        // --- control sink ---
        let st_ctrl = state.clone();
        let bb_ctrl: Arc<dyn BindingBoundary> = binding_s.clone();
        let core_ctrl = em.clone();
        let cancel_ctrl = cancel.clone();
        let control_sink: Sink = Arc::new(move |msgs| {
            let mut should_cancel = false;
            let mut error_action: Option<HandleId> = None;
            {
                let mut s = st_ctrl.lock();
                if s.terminated {
                    return;
                }
                for m in msgs {
                    match m.tier() {
                        3 => {
                            if let Some(h) = m.payload_handle() {
                                let results = bb_ctrl.predicate_each(gate_fn_id, &[h]);
                                let new_open = results.first().copied().unwrap_or(false);
                                let was_open = s.open;
                                s.open = new_open;
                                // Transition open -> closed: trigger cancel.
                                if was_open && !new_open && cancel_ctrl.is_some() {
                                    should_cancel = true;
                                }
                            }
                        }
                        5 => {
                            if let Some(h) = m.payload_handle() {
                                // Control ERROR terminates valve.
                                if !s.terminated {
                                    s.terminated = true;
                                    bb_ctrl.retain_handle(h);
                                    error_action = Some(h);
                                }
                            }
                            // Control COMPLETE: do NOT auto-complete.
                        }
                        _ => {}
                    }
                }
            }
            if should_cancel {
                if let Some(ref ct) = cancel_ctrl {
                    ct.cancel();
                }
            }
            if let Some(h) = error_action {
                core_ctrl.error_or_defer(pid, h);
            }
        });

        let ctrl_outcome = ctx.subscribe_to(control, control_sink);
        if matches!(ctrl_outcome, SubscribeOutcome::Dead { .. }) {
            // Control is dead — gate state remains as-is (closed by default).
            // No auto-complete; source can still flow if gate was already opened.
        }

        // --- source sink ---
        let st_src = state.clone();
        let bb_src: Arc<dyn BindingBoundary> = binding_s.clone();
        let core_src = em.clone();
        let source_sink: Sink = Arc::new(move |msgs| {
            enum Act {
                Emit(HandleId),
                Complete,
                Error(HandleId),
            }
            let mut actions: SmallVec<[Act; 4]> = SmallVec::new();
            {
                let s = st_src.lock();
                if s.terminated {
                    return;
                }
                for m in msgs {
                    match m.tier() {
                        3 => {
                            if let Some(h) = m.payload_handle() {
                                if s.open {
                                    bb_src.retain_handle(h);
                                    actions.push(Act::Emit(h));
                                }
                                // Closed gate: silently discard.
                            }
                        }
                        5 => {
                            if let Some(h) = m.payload_handle() {
                                bb_src.retain_handle(h);
                                actions.push(Act::Error(h));
                            } else {
                                actions.push(Act::Complete);
                            }
                        }
                        _ => {}
                    }
                }
            }
            for a in actions {
                match a {
                    Act::Emit(h) => core_src.emit_or_defer(pid, h),
                    Act::Complete => core_src.complete_or_defer(pid),
                    Act::Error(h) => core_src.error_or_defer(pid, h),
                }
            }
        });

        let src_outcome = ctx.subscribe_to(source, source_sink);
        if matches!(src_outcome, SubscribeOutcome::Dead { .. }) {
            let mut s = state.lock();
            if !s.terminated {
                s.terminated = true;
                drop(s);
                core_s.complete_or_defer(pid);
            }
        }
    });

    let fn_id = binding.register_producer_build(build);
    core.register_producer(fn_id)
        .expect("valve: register_producer failed")
}

// =========================================================================
// settle(source, quiet_waves, max_waves) — convergence detector
// =========================================================================

/// Wave-count convergence detector.
///
/// - On DATA: resets `quiet_count` to 0, increments `wave_count`. Forwards
///   DATA unchanged. If `max_waves` is set and `wave_count >= max_waves`,
///   completes.
/// - On RESOLVED (tier 3, no payload): increments `quiet_count`. If
///   `quiet_count >= quiet_waves`, completes.
/// - On COMPLETE/ERROR: forwarded unchanged.
#[must_use]
pub fn settle(
    core: &Core,
    binding: &Arc<dyn ProducerBinding>,
    source: NodeId,
    quiet_waves: u32,
    max_waves: Option<u32>,
) -> NodeId {
    struct SettleState {
        wave_count: u32,
        quiet_count: u32,
        completed: bool,
    }

    let build: ProducerBuildFn = Box::new(move |ctx: ProducerCtx<'_>| {
        let core_s = ctx.core();
        let binding_s = ctx.core().binding();
        let em = ctx.emitter();
        let pid = ctx.node_id();
        let bb: Arc<dyn BindingBoundary> = binding_s.clone();
        let core_sink = em.clone();
        let state: Arc<Mutex<SettleState>> = Arc::new(Mutex::new(SettleState {
            wave_count: 0,
            quiet_count: 0,
            completed: false,
        }));

        let source_sink: Sink = Arc::new(move |msgs| {
            enum Act {
                Emit(HandleId),
                Complete,
                Error(HandleId),
                SelfComplete,
            }
            let mut actions: SmallVec<[Act; 4]> = SmallVec::new();
            {
                let mut s = state.lock();
                if s.completed {
                    return;
                }
                for m in msgs {
                    if s.completed {
                        break;
                    }
                    match m.tier() {
                        3 => {
                            if let Some(h) = m.payload_handle() {
                                // DATA: reset quiet, increment waves.
                                s.quiet_count = 0;
                                s.wave_count += 1;
                                bb.retain_handle(h);
                                actions.push(Act::Emit(h));
                                // Check max_waves.
                                if let Some(max) = max_waves {
                                    if s.wave_count >= max {
                                        s.completed = true;
                                        actions.push(Act::SelfComplete);
                                    }
                                }
                            } else {
                                // RESOLVED (tier 3, no payload): quiet wave.
                                s.quiet_count += 1;
                                if s.quiet_count >= quiet_waves {
                                    s.completed = true;
                                    actions.push(Act::SelfComplete);
                                }
                            }
                        }
                        5 => {
                            if let Some(h) = m.payload_handle() {
                                s.completed = true;
                                bb.retain_handle(h);
                                actions.push(Act::Error(h));
                            } else {
                                s.completed = true;
                                actions.push(Act::Complete);
                            }
                        }
                        _ => {}
                    }
                }
            }
            for a in actions {
                match a {
                    Act::Emit(h) => core_sink.emit_or_defer(pid, h),
                    Act::Complete | Act::SelfComplete => core_sink.complete_or_defer(pid),
                    Act::Error(h) => core_sink.error_or_defer(pid, h),
                }
            }
        });

        let outcome = ctx.subscribe_to(source, source_sink);
        if matches!(outcome, SubscribeOutcome::Dead { .. }) {
            core_s.complete_or_defer(pid);
        }
    });

    let fn_id = binding.register_producer_build(build);
    core.register_producer(fn_id)
        .expect("settle: register_producer failed")
}

// =========================================================================
// repeat(source, count) — sequential resubscribe loop
// =========================================================================

/// Sequential resubscribe loop. Forwards all DATA from `source`. On
/// source COMPLETE, if `remaining > 0`, resubscribes to `source` and
/// decrements `remaining`. On ERROR, terminates immediately (no retry).
///
/// `count` is the number of ADDITIONAL subscriptions after the initial
/// one. `count = 0` is identity passthrough. `count = 2` means the
/// source will be subscribed up to 3 times total.
#[must_use]
pub fn repeat(
    core: &Core,
    binding: &Arc<dyn ProducerBinding>,
    source: NodeId,
    count: u32,
) -> NodeId {
    struct RepeatState {
        remaining: u32,
        terminated: bool,
    }

    let build: ProducerBuildFn = Box::new(move |ctx: ProducerCtx<'_>| {
        let core_s = ctx.core();
        let binding_s = ctx.core().binding();
        let em = ctx.emitter();
        let pid = ctx.node_id();
        let state: Arc<Mutex<RepeatState>> = Arc::new(Mutex::new(RepeatState {
            remaining: count,
            terminated: false,
        }));

        // We need to store the subscription in producer storage and be able
        // to replace it on resubscribe. S2b/D231: storage via the new
        // `ProducerCtx::storage()` accessor (the build closure no longer
        // holds a `ProducerBinding`). Resubscribe re-enters Core to
        // `try_subscribe`, which a long-lived sink can only do via
        // `em.defer` (D234) — see the `Act::Resubscribe` arm.
        let storage = ctx.storage();

        // Build the sink closure. It needs to reference itself for
        // resubscription, so we use a shared slot.
        let sink_slot: Arc<Mutex<Option<Sink>>> = Arc::new(Mutex::new(None));
        let sink_slot_inner = sink_slot.clone();
        let bb: Arc<dyn BindingBoundary> = binding_s.clone();
        let core_sink = em.clone();
        let storage_inner = storage.clone();

        let source_sink: Sink = Arc::new(move |msgs| {
            enum Act {
                Emit(HandleId),
                Error(HandleId),
                Resubscribe,
                Complete,
            }
            let mut actions: SmallVec<[Act; 4]> = SmallVec::new();
            {
                let mut s = state.lock();
                if s.terminated {
                    return;
                }
                for m in msgs {
                    if s.terminated {
                        break;
                    }
                    match m.tier() {
                        3 => {
                            if let Some(h) = m.payload_handle() {
                                bb.retain_handle(h);
                                actions.push(Act::Emit(h));
                            }
                        }
                        5 => {
                            if let Some(h) = m.payload_handle() {
                                // ERROR — terminate immediately.
                                s.terminated = true;
                                bb.retain_handle(h);
                                actions.push(Act::Error(h));
                            } else {
                                // COMPLETE — resubscribe if remaining > 0.
                                if s.remaining > 0 {
                                    s.remaining -= 1;
                                    actions.push(Act::Resubscribe);
                                } else {
                                    s.terminated = true;
                                    actions.push(Act::Complete);
                                }
                            }
                        }
                        _ => {}
                    }
                }
            }
            for a in actions {
                match a {
                    Act::Emit(h) => core_sink.emit_or_defer(pid, h),
                    Act::Error(h) => core_sink.error_or_defer(pid, h),
                    Act::Complete => core_sink.complete_or_defer(pid),
                    Act::Resubscribe => {
                        // Get our own sink from the shared slot.
                        let maybe_sink = sink_slot_inner.lock().clone();
                        if let Some(new_sink) = maybe_sink {
                            // D234: a long-lived sink can't hold `&Core`;
                            // route the re-subscribe through `em.defer`
                            // (owner-side, in-wave, FIFO-ordered). The
                            // returned `SubscriptionId` is recorded
                            // (D229 `(source, sub)` pair) inside the
                            // closure; the dead/violation path completes
                            // self there too.
                            let storage_d = storage_inner.clone();
                            let state_d = state.clone();
                            let _ = core_sink.defer(move |c| {
                                if let Ok(sub) = c.try_subscribe(source, new_sink) {
                                    storage_d
                                        .lock()
                                        .entry(pid)
                                        .or_default()
                                        .subs
                                        .push((source, sub));
                                } else {
                                    // Source dead / partition
                                    // violation — terminal complete.
                                    let mut s = state_d.lock();
                                    if !s.terminated {
                                        s.terminated = true;
                                        drop(s);
                                        c.complete(pid);
                                    }
                                }
                            });
                        }
                    }
                }
            }
        });

        // Store sink in the shared slot so resubscribe can access it.
        *sink_slot.lock() = Some(source_sink.clone());

        let outcome = ctx.subscribe_to(source, source_sink);
        if matches!(outcome, SubscribeOutcome::Dead { .. }) {
            // Dead source (non-resubscribable + terminated) will stay
            // dead — resubscribing won't help. Complete immediately.
            core_s.complete_or_defer(pid);
        }
    });

    let fn_id = binding.register_producer_build(build);
    core.register_producer(fn_id)
        .expect("repeat: register_producer failed")
}