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
//! Producer-shape operator substrate (Slice D-ops, Commit 2).
//!
//! Producer ops (zip / concat / race / takeUntil) are nodes with no
//! declared deps that fire their fn ONCE on first activation. The fn
//! body subscribes to upstream sources via [`ProducerCtx::subscribe_to`]
//! and registers per-op state (queues, phase flags, winner index). When
//! upstream emits, the operator's sink closures re-enter Core via
//! `Core::emit` / `Core::complete` / `Core::error` on the producer node.
//!
//! On last-subscriber unsubscribe, Core invokes
//! [`BindingBoundary::producer_deactivate(node_id)`](graphrefly_core::BindingBoundary::producer_deactivate);
//! the binding's impl drops the per-node entry from its
//! `producer_states` map, which cascades:
//!
//! ```text
//! producer_states.remove(node_id) →
//! Vec<Subscription> drops →
//! each Subscription::Drop fires →
//! upstream sinks unsubscribe.
//! ```
//!
//! # Reference-cycle discipline (Slice Y, 2026-05-08)
//!
//! Build closures registered via
//! [`ProducerBinding::register_producer_build`] are stored long-term in
//! the binding's `producer_builds` registry. To avoid the strong-Arc
//! cycle `BenchBinding → registry → producer_builds[fn_id] → closure →
//! strong-Arc<dyn ProducerBinding> → BenchBinding`, factory bodies
//! (`zip` / `concat` / `race` / `take_until` in `ops_impl.rs` plus
//! `switch_map` / `exhaust_map` / `merge_map` / `concat_map` in
//! `higher_order.rs`) capture `WeakCore` and
//! `Weak<dyn ProducerBinding>` (and `Weak<dyn HigherOrderBinding>`
//! for the higher-order factories). The build closure upgrades both
//! on each invocation; if the host `Core` was already dropped, upgrade
//! returns `None` and the build closure no-ops cleanly.
//!
//! Sinks spawned by the build closure capture STRONG refs cloned from
//! the upgraded weaks. Their lifetime is tied to the producer's active
//! subscription — `producer_deactivate` on last-subscriber unsubscribe
//! clears `producer_storage[node_id]`, dropping the upstream
//! `Subscription`s, which drops the sinks, which drops the strong
//! captures. So the strong-ref window is bounded by producer-active
//! state, not by the long-lived `producer_builds` registry.
use Any;
use Arc;
use AHashMap as HashMap;
use Mutex;
use ;
/// Outcome of [`ProducerCtx::subscribe_to`] — the producer-layer
/// translation of [`graphrefly_core::SubscribeError`] into a positive
/// outcome enum that operators (zip / concat / race / take_until /
/// merge_map / switch_map / exhaust_map / concat_map) can match on for
/// per-operator dead-source semantics.
///
/// Introduced /qa F2 (2026-05-10) to close the silent-wedge class of
/// bugs where operators previously couldn't tell that a `subscribe_to`
/// call had been rejected per R2.2.7.b (non-resubscribable terminal
/// source) — pre-F2 the rejection was logged-and-skipped silently,
/// which left zip waiting for a queue that would never fill, concat
/// stuck on a source that would never advance, etc.
///
/// Mirrors the per-domain status-string-union pattern used in TS
/// (`RefineStatus`, `AgentStatus`, process status: `"running" |
/// "completed" | "errored" | "cancelled"`) — each operator-layer
/// outcome lives in its own typed enum rather than sharing a global
/// `Outcome<T, E>` type.
/// Build closure type — the producer's fn body, called once on first
/// activation. The closure receives a [`ProducerCtx`] for setting up
/// upstream subscriptions; emissions on the producer come from sink
/// callbacks the closure registers.
pub type ProducerBuildFn = ;
/// Per-producer-node state owned by the [`ProducerBinding`] impl.
///
/// Holds upstream `Subscription`s (auto-dropped on producer
/// deactivation) plus an optional `Box<dyn Any>` slot for op-specific
/// state shared across the build closure and its sink closures.
/// (Most ops capture state via `Arc<Mutex<...>>` directly in closure
/// captures; the `op_state` slot is reserved for ops that prefer
/// trait-object storage.)
/// Storage shared between the [`ProducerBinding`] impl and the
/// [`ProducerCtx`] passed to build closures. Keyed by producer NodeId.
///
/// Access via `Arc<Mutex<_>>` so the binding's `producer_deactivate`
/// hook can clear an entry while build/sink closures hold their own
/// per-op state via separate Arc captures.
pub type ProducerStorage = ;
/// Closure-registration interface for producer-shape operators —
/// extends [`BindingBoundary`] with one method that bindings shipping
/// producers must implement.
///
/// Bindings that don't ship producers (e.g., minimal test bindings)
/// don't need to implement this trait. The operator factories below
/// (`zip`, `concat`, `race`, `take_until`) require it.
/// Sink-side emit handle (S2b / D231 / D232-AMEND/A′).
///
/// Producer build closures spawn long-lived `Sink`s that fire on every
/// future upstream emit — long after the build closure's `&Core`
/// (`ctx`) is gone. Under the actor model the `Core` is owned by value
/// and relocates between workers, so sinks can no longer capture a
/// cloned `Core` / `WeakCore`. Instead they capture a `ProducerEmitter`
/// (cheap `Clone`: two `Arc`s) and post `MailboxOp`s to the
/// `Core`-owned [`graphrefly_core::CoreMailbox`]; the `BatchGuard`
/// drain-to-quiescence loop applies them **in-wave** via the sync
/// `Core::{emit,complete,error}` (immediate, cascade-ordering-preserving
/// — D232-AMEND).
///
/// Method names mirror the old `Core::{emit,complete,error}_or_defer`
/// so sink bodies are unchanged: only the captured handle's
/// construction differs (`em = ctx.emitter()` instead of
/// `core_s.clone()`).
/// The **`Send + Sync` cross-thread** producer emit handle (D249/S2c).
///
/// Holds only the id-only `Arc<CoreMailbox>` post side + the binding
/// (for the `Core`-gone handle-release branch). This is what an
/// autonomous timer task (`temporal.rs`, `tokio::spawn`-ed) captures —
/// it stays `Send` so the spawned future is `Send`. It deliberately
/// has **no `defer`** (that is the `!Send` owner-side path; see
/// [`ProducerEmitter`]).
/// The owner-side producer handle (D249/S2c). `MailboxEmitter` (the
/// `Send` cross-thread emit side) **plus** the owner-only `!Send`
/// `Rc<DeferQueue>` for [`Self::defer`]. Captured into owner-side
/// `!Send` producer sinks (control/higher-order dynamic-inner); the
/// `Rc` makes it `!Send`, consistent with the D248 single-owner `Sink`
/// relaxation. A timer task that needs only the cross-thread emit side
/// takes [`Self::emitter`] (a `Send` [`MailboxEmitter`]) instead.
/// Binding-layer RAII subscription handle (S2b / D225 / D234). The
/// core-level RAII `Subscription` was retired (a parameterless `Drop`
/// can't reach a relocating owned `Core`); this wrapper IS the
/// sanctioned binding-layer replacement for *substrate operators* that
/// manage an inner subscription's lifetime by ownership (higher-order
/// `switch/exhaust/merge/concat_map` inner subs). It holds a
/// `ProducerEmitter` (an `Arc<CoreMailbox>` — `Send + Sync`, `'static`,
/// NOT the `Core`), so its `Drop` legitimately posts a deferred
/// `unsubscribe` via `em.defer` (owner-side, in-wave, FIFO-ordered —
/// D234). FIFO ordering gives the correct cancel-then-resubscribe
/// semantics: a `SubGuard` dropped before a new subscribe is posted is
/// drained (unsub) before the new subscribe. A `Core`-gone post is
/// dropped unrun (subscription moot at teardown — no leak).
/// Context handed to a producer's build closure on activation.
///
/// Provides:
/// - [`Self::node_id`] / [`Self::core`] — identity + Core access for
/// sink callbacks that re-enter Core.
/// - [`Self::subscribe_to`] — subscribe to an upstream Core node;
/// the resulting `Subscription` is auto-tracked under
/// `node_id` in the binding's producer storage and dropped on
/// producer deactivation.
/// Default helper — explicitly unsubscribe the producer's recorded
/// upstream subs, then drop its storage entry, on deactivation.
///
/// S2b/D229: core-level RAII `Subscription` is retired, so the binding's
/// [`BindingBoundary::producer_deactivate`] impl receives a
/// `Core::unsubscribe`-capable `unsub` closure (the owner-driven chain
/// passes it the `&Core` it already holds). Looping it over the recorded
/// `(source, sub_id)` pairs is behaviour-identical to the old
/// `Vec<Subscription>`-drop cascade (same deregister + Phase-G chain,
/// lock-released so re-entrant producer cascades are safe).
///
/// Ordering (QA F3, 2026-05-18 — corrected from an earlier
/// remove-AFTER comment that contradicted the code): the entry is
/// **taken out under the `storage` lock FIRST**, then the `unsub`
/// cascade runs lock-released over the moved-out `subs`. This is
/// behaviour-identical to the retired path (old code did
/// `states.remove(&node_id)` and the dropped `Vec<Subscription>`'s
/// `Drop` ran the cascade — i.e. remove-then-cascade). Because the
/// entry is already gone before any re-entrant call, a re-entrant
/// `subscribe_to(node_id, …)` *during* the cascade `or_default()`s a
/// **fresh** entry that correctly survives this deactivation (a
/// genuine re-subscription) — there is never a half-cleared entry to
/// observe. Do NOT reorder to remove-after-unsub: that *would* expose
/// the live entry to the lock-released re-entrant cascade.
// =====================================================================
// Producer-shape operators (D-ops, Slice D Commit 2)
// =====================================================================
//
// All four producer ops follow the same shape:
//
// 1. Operator factory captures `Core::clone()` + sources + per-op state
// (Arc<Mutex<...>>) into a build closure.
// 2. `register_producer_build` returns a FnId.
// 3. `Core::register_producer(fn_id)` creates the producer node.
// 4. On first subscribe, Core fires invoke_fn → binding dispatches to
// the build closure → ProducerCtx is constructed.
// 5. Build closure subscribes to each upstream source, providing sink
// closures that capture per-op state and the producer's NodeId.
// 6. Sink closures process upstream emissions and emit on the producer
// node via `core.emit` / `core.complete` / `core.error`.
// 7. On last subscriber unsubscribe, Core fires producer_deactivate →
// binding drops storage entry → Subscription Vec drops → sinks
// unsub from upstream.
//
// The concrete operators (`zip` / `concat` / `race` / `take_until`)
// live in [`super::ops_impl`] (sibling module) and are re-exported
// from the crate root.