Skip to main content

hydro_lang/compile/ir/
mod.rs

1use core::panic;
2use std::cell::{Cell, RefCell};
3use std::collections::HashMap;
4#[cfg(feature = "build")]
5use std::collections::HashSet;
6use std::fmt::{Debug, Display};
7use std::hash::{Hash, Hasher};
8use std::ops::Deref;
9use std::rc::Rc;
10
11#[cfg(feature = "build")]
12use dfir_lang::graph::FlatGraphBuilder;
13#[cfg(feature = "build")]
14use proc_macro2::Span;
15use proc_macro2::TokenStream;
16use quote::ToTokens;
17#[cfg(feature = "build")]
18use quote::quote;
19#[cfg(feature = "build")]
20use slotmap::{SecondaryMap, SparseSecondaryMap};
21#[cfg(feature = "build")]
22use syn::parse_quote;
23
24#[cfg(feature = "build")]
25use crate::compile::builder::ClockId;
26#[cfg(feature = "build")]
27use crate::compile::builder::StmtId;
28use crate::compile::builder::{CycleId, ExternalPortId};
29#[cfg(feature = "build")]
30use crate::compile::deploy_provider::{Deploy, Node, RegisterPort};
31#[cfg(feature = "build")]
32use crate::handoff_ref::handoff_ref_ident;
33use crate::location::dynamic::{ClusterConsistency, LocationId};
34use crate::location::{LocationKey, NetworkHint};
35
36pub mod backtrace;
37use backtrace::Backtrace;
38
39/// A closure expression bundled with any singleton references it captures.
40///
41/// When a `q!()` closure captures a `SingletonRef`, the reference is recorded here
42/// alongside the closure's expression. This allows per-closure tracking of singleton
43/// captures, which is important for nodes with multiple closures (e.g. Fold has `init` and `acc`).
44pub struct ClosureExpr {
45    pub(crate) expr: DebugExpr,
46    /// Each entry is `(HydroNode::Reference, is_mut: bool)`.
47    /// The index in the Vec determines the ident name via [`handoff_ref_ident`].
48    /// The `access_counter` was assigned at staging time in code order.
49    pub(crate) singleton_refs: Vec<(HydroNode, bool)>,
50}
51
52impl Clone for ClosureExpr {
53    fn clone(&self) -> Self {
54        Self {
55            expr: self.expr.clone(),
56            singleton_refs: self
57                .singleton_refs
58                .iter()
59                .map(|(node, is_mut)| {
60                    let HydroNode::Reference {
61                        inner,
62                        kind,
63                        access_counter,
64                        metadata,
65                    } = node
66                    else {
67                        panic!("singleton_refs should only contain HydroNode::Reference");
68                    };
69                    (
70                        HydroNode::Reference {
71                            inner: SharedNode(Rc::clone(&inner.0)),
72                            kind: *kind,
73                            access_counter: access_counter.freeze(),
74                            metadata: metadata.clone(),
75                        },
76                        *is_mut,
77                    )
78                })
79                .collect(),
80        }
81    }
82}
83
84impl Hash for ClosureExpr {
85    fn hash<H: Hasher>(&self, state: &mut H) {
86        self.expr.hash(state);
87        // singleton_refs are structural children (like HydroIrMetadata), not
88        // identity-defining. Two closures with the same expr but different
89        // captured refs are the same closure text — the refs only affect codegen.
90    }
91}
92
93impl serde::Serialize for ClosureExpr {
94    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
95        use serde::ser::SerializeStruct;
96        let mut s = serializer.serialize_struct("ClosureExpr", 2)?;
97        s.serialize_field("expr", &self.expr)?;
98        s.serialize_field(
99            "singleton_refs",
100            &SerializableSingletonRefs(&self.singleton_refs),
101        )?;
102        s.end()
103    }
104}
105
106struct SerializableSingletonRefs<'a>(&'a [(HydroNode, bool)]);
107
108impl serde::Serialize for SerializableSingletonRefs<'_> {
109    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
110        use serde::ser::SerializeSeq;
111        let mut seq = serializer.serialize_seq(Some(self.0.len()))?;
112        for (node, is_mut) in self.0.iter() {
113            seq.serialize_element(&(node, is_mut))?;
114        }
115        seq.end()
116    }
117}
118
119impl Debug for ClosureExpr {
120    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121        Debug::fmt(&self.expr, f)
122    }
123}
124
125impl Display for ClosureExpr {
126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        Display::fmt(&self.expr, f)
128    }
129}
130
131impl From<syn::Expr> for ClosureExpr {
132    fn from(expr: syn::Expr) -> Self {
133        Self {
134            expr: DebugExpr(Box::new(expr)),
135            singleton_refs: Vec::new(),
136        }
137    }
138}
139
140impl From<DebugExpr> for ClosureExpr {
141    fn from(expr: DebugExpr) -> Self {
142        Self {
143            expr,
144            singleton_refs: Vec::new(),
145        }
146    }
147}
148
149impl ClosureExpr {
150    pub fn new(expr: DebugExpr, singleton_refs: Vec<(HydroNode, bool)>) -> Self {
151        Self {
152            expr,
153            singleton_refs,
154        }
155    }
156
157    pub fn has_mut_ref(&self) -> bool {
158        self.singleton_refs.iter().any(|(_, is_mut)| *is_mut)
159    }
160
161    pub fn deep_clone(&self, seen_tees: &mut SeenSharedNodes) -> Self {
162        Self {
163            expr: self.expr.clone(),
164            singleton_refs: self
165                .singleton_refs
166                .iter()
167                .map(|(node, is_mut)| (node.deep_clone(seen_tees), *is_mut))
168                .collect(),
169        }
170    }
171
172    pub fn transform_children(
173        &mut self,
174        transform: &mut impl FnMut(&mut HydroNode, &mut SeenSharedNodes),
175        seen_tees: &mut SeenSharedNodes,
176    ) {
177        for (ref_node, _is_mut) in self.singleton_refs.iter_mut() {
178            transform(ref_node, seen_tees);
179        }
180    }
181
182    /// Pop singleton ref idents from the stack and rewrite the closure's token stream,
183    /// replacing local singleton ref idents with `#{N} dfir_ident` or `#{N} mut dfir_ident` references.
184    #[cfg(feature = "build")]
185    pub fn emit_tokens(&self, ident_stack: &mut Vec<syn::Ident>) -> TokenStream {
186        if self.singleton_refs.is_empty() {
187            self.expr.0.to_token_stream()
188        } else {
189            assert!(
190                ident_stack.len() >= self.singleton_refs.len(),
191                "ident_stack has {} entries but expected at least {} for singleton_refs",
192                ident_stack.len(),
193                self.singleton_refs.len()
194            );
195            let ref_idents = ident_stack.drain(ident_stack.len() - self.singleton_refs.len()..);
196
197            let mut let_bindings = Vec::new();
198            for ((i, (ref_node, is_mut)), ref_ident) in
199                self.singleton_refs.iter().enumerate().zip(ref_idents)
200            {
201                let HydroNode::Reference { access_counter, .. } = ref_node else {
202                    panic!("ClosureExpression expected references to `HydroNode::Reference`");
203                };
204                let group = access_counter.frozen_group();
205                // TODO(mingwei): proper spanning?
206                let local_ident = handoff_ref_ident(i);
207                let hash = proc_macro2::Punct::new('#', proc_macro2::Spacing::Alone);
208                let group_lit = proc_macro2::Literal::u32_unsuffixed(group);
209                let mut_token = is_mut.then(|| quote!(mut));
210                let binding = quote! {
211                    let #local_ident = #hash {#group_lit} #mut_token #ref_ident;
212                };
213                let_bindings.push(binding);
214            }
215
216            let expr = &self.expr.0;
217            quote! {
218                {
219                    #( #let_bindings )*
220                    #expr
221                }
222            }
223        }
224    }
225}
226
227/// Wrapper that displays only the tokens of a parsed expr.
228///
229/// Boxes `syn::Type` which is ~240 bytes.
230#[derive(Clone, Hash)]
231pub struct DebugExpr(pub Box<syn::Expr>);
232
233impl serde::Serialize for DebugExpr {
234    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
235        serializer.serialize_str(&self.to_string())
236    }
237}
238
239impl From<syn::Expr> for DebugExpr {
240    fn from(expr: syn::Expr) -> Self {
241        Self(Box::new(expr))
242    }
243}
244
245impl Deref for DebugExpr {
246    type Target = syn::Expr;
247
248    fn deref(&self) -> &Self::Target {
249        &self.0
250    }
251}
252
253impl ToTokens for DebugExpr {
254    fn to_tokens(&self, tokens: &mut TokenStream) {
255        self.0.to_tokens(tokens);
256    }
257}
258
259impl Debug for DebugExpr {
260    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
261        write!(f, "{}", self.0.to_token_stream())
262    }
263}
264
265impl Display for DebugExpr {
266    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
267        let original = self.0.as_ref().clone();
268        let simplified = simplify_q_macro(original);
269
270        // For now, just use quote formatting without trying to parse as a statement
271        // This avoids the syn::parse_quote! issues entirely
272        write!(f, "q!({})", quote::quote!(#simplified))
273    }
274}
275
276/// Simplify expanded q! macro calls back to q!(...) syntax for better readability
277fn simplify_q_macro(expr: syn::Expr) -> syn::Expr {
278    if let syn::Expr::Call(ref call) = expr && let syn::Expr::Path(path_expr) = call.func.as_ref()
279        // Look for calls to stageleft::runtime_support::fn*
280        && is_stageleft_runtime_support_call(&path_expr.path)
281        && let syn::Expr::Block(b) = &call.args[0]
282        && b.block.stmts.len() == 3
283        && let Some(syn::Stmt::Expr(e, _)) = b.block.stmts.get(2)
284    // skip the first two, which are imports
285    {
286        let mut e = e.clone();
287        while let syn::Expr::Block(ref mut block) = e
288            && block.block.stmts.len() == 1
289            && let syn::Stmt::Expr(inner_e, _) = block.block.stmts.remove(0)
290        {
291            e = inner_e;
292        }
293
294        e
295    } else {
296        expr
297    }
298}
299
300fn is_stageleft_runtime_support_call(path: &syn::Path) -> bool {
301    // Check if this is a call to stageleft::runtime_support::fn*
302    if let Some(last_segment) = path.segments.last() {
303        let fn_name = last_segment.ident.to_string();
304        path.segments.len() > 2
305            && path.segments[0].ident == "stageleft"
306            && path.segments[1].ident == "runtime_support"
307            && fn_name.contains("_type_hint")
308    } else {
309        false
310    }
311}
312
313/// Debug displays the type's tokens.
314///
315/// Boxes `syn::Type` which is ~320 bytes.
316#[derive(Clone, PartialEq, Eq, Hash)]
317pub struct DebugType(pub Box<syn::Type>);
318
319impl From<syn::Type> for DebugType {
320    fn from(t: syn::Type) -> Self {
321        Self(Box::new(t))
322    }
323}
324
325impl Deref for DebugType {
326    type Target = syn::Type;
327
328    fn deref(&self) -> &Self::Target {
329        &self.0
330    }
331}
332
333impl ToTokens for DebugType {
334    fn to_tokens(&self, tokens: &mut TokenStream) {
335        self.0.to_tokens(tokens);
336    }
337}
338
339impl Debug for DebugType {
340    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
341        write!(f, "{}", self.0.to_token_stream())
342    }
343}
344
345impl serde::Serialize for DebugType {
346    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
347        serializer.serialize_str(&format!("{}", self.0.to_token_stream()))
348    }
349}
350
351fn serialize_backtrace_as_span<S: serde::Serializer>(
352    backtrace: &Backtrace,
353    serializer: S,
354) -> Result<S::Ok, S::Error> {
355    match backtrace.format_span() {
356        Some(span) => serializer.serialize_some(&span),
357        None => serializer.serialize_none(),
358    }
359}
360
361fn serialize_ident<S: serde::Serializer>(
362    ident: &syn::Ident,
363    serializer: S,
364) -> Result<S::Ok, S::Error> {
365    serializer.serialize_str(&ident.to_string())
366}
367
368pub enum DebugInstantiate {
369    Building,
370    Finalized(Box<DebugInstantiateFinalized>),
371}
372
373impl serde::Serialize for DebugInstantiate {
374    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
375        match self {
376            DebugInstantiate::Building => {
377                serializer.serialize_unit_variant("DebugInstantiate", 0, "Building")
378            }
379            DebugInstantiate::Finalized(_) => {
380                panic!(
381                    "cannot serialize DebugInstantiate::Finalized: contains non-serializable runtime state (closures)"
382                )
383            }
384        }
385    }
386}
387
388#[cfg_attr(
389    not(feature = "build"),
390    expect(
391        dead_code,
392        reason = "sink, source unused without `feature = \"build\"`."
393    )
394)]
395pub struct DebugInstantiateFinalized {
396    sink: syn::Expr,
397    source: syn::Expr,
398    connect_fn: Option<Box<dyn FnOnce()>>,
399}
400
401impl From<DebugInstantiateFinalized> for DebugInstantiate {
402    fn from(f: DebugInstantiateFinalized) -> Self {
403        Self::Finalized(Box::new(f))
404    }
405}
406
407impl Debug for DebugInstantiate {
408    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
409        write!(f, "<network instantiate>")
410    }
411}
412
413impl Hash for DebugInstantiate {
414    fn hash<H: Hasher>(&self, _state: &mut H) {
415        // Do nothing
416    }
417}
418
419impl Clone for DebugInstantiate {
420    fn clone(&self) -> Self {
421        match self {
422            DebugInstantiate::Building => DebugInstantiate::Building,
423            DebugInstantiate::Finalized(_) => {
424                panic!("DebugInstantiate::Finalized should not be cloned")
425            }
426        }
427    }
428}
429
430/// Tracks the instantiation state of a `ClusterMembers` source.
431///
432/// During `compile_network`, the first `ClusterMembers` node for a given
433/// `(at_location, target_cluster)` pair is promoted to [`Self::Stream`] and
434/// receives the expression returned by `Deploy::cluster_membership_stream`.
435/// All subsequent nodes for the same pair are set to [`Self::Tee`] so that
436/// during code-gen they simply reference the tee output of the first node
437/// instead of creating a redundant `source_stream`.
438#[derive(Debug, Hash, Clone, serde::Serialize)]
439pub enum ClusterMembersState {
440    /// Not yet instantiated.
441    Uninit,
442    /// The primary instance: holds the stream expression and will emit
443    /// `source_stream(expr) -> tee()` during code-gen.
444    Stream(DebugExpr),
445    /// A secondary instance that references the tee output of the primary.
446    /// Stores `(at_location_root, target_cluster_location)` so that `emit_core`
447    /// can derive the deterministic tee ident without extra state.
448    Tee(LocationId, LocationId),
449}
450
451/// A source in a Hydro graph, where data enters the graph.
452#[derive(Debug, Hash, Clone, serde::Serialize)]
453pub enum HydroSource {
454    Stream(DebugExpr),
455    ExternalNetwork(),
456    Iter(DebugExpr),
457    Spin(),
458    ClusterMembers(LocationId, ClusterMembersState),
459    Embedded(#[serde(serialize_with = "serialize_ident")] syn::Ident),
460    EmbeddedSingleton(#[serde(serialize_with = "serialize_ident")] syn::Ident),
461}
462
463#[cfg(feature = "build")]
464/// A trait that abstracts over elements of DFIR code-gen that differ between production deployment
465/// and simulations.
466///
467/// In particular, this lets the simulator fuse together all locations into one DFIR graph, spit
468/// out separate graphs for each tick, and emit hooks for controlling non-deterministic operators.
469pub trait DfirBuilder {
470    /// Whether the representation of singletons should include intermediate states.
471    fn singleton_intermediates(&self) -> bool;
472
473    /// Adds the DFIR statements to the graph for the given location.
474    ///
475    /// The location determines which DFIR graph the statements are placed in (for production,
476    /// the graph of the location's root; for simulation, either the fused async graph or the
477    /// tick's separate graph). In the future (#2902), production codegen will also use the
478    /// location to place tick-located statements inside the tick's `loop { ... }` context.
479    fn add_dfir_at(
480        &mut self,
481        location: &LocationId,
482        dfir: dfir_lang::parse::DfirCode,
483        operator_tag: Option<&str>,
484    );
485
486    /// Emits a source operator (e.g. `source_iter(...)`) that logically lives inside a tick.
487    ///
488    /// * `source_rhs` is the source pipeline (the right-hand side of the `=` assignment, e.g.
489    ///   `source_iter([123])`).
490    /// * `kind` is the collection kind of the source's output: production windows replayed
491    ///   stream-like sources in with `snapshot_prefix()` and singleton-like ones with
492    ///   `snapshot()`.
493    /// * `replay_each_tick` selects whether the value is re-emitted on every tick/firing
494    ///   (persisted) or delivered only on the first tick/firing.
495    ///
496    /// TODO(#2902): eventually this should not be an option here; instead the IR should model
497    /// the source as living outside the tick, windowed in through a `batch_persist()` loop
498    /// ingress operator when it should replay on every firing (the production impl already
499    /// lowers to exactly that shape: a root-level source + a persistent lazy windowing
500    /// operator).
501    ///
502    /// The default (simulation) emission places the source directly in the tick's own graph.
503    /// Production overrides this since DFIR sources must be at the root level, outside of the
504    /// tick's `loop { ... }` context: it emits the source at the root and windows it into the
505    /// loop.
506    fn add_tick_source(
507        &mut self,
508        location: &LocationId,
509        source_rhs: TokenStream,
510        out_ident: &syn::Ident,
511        kind: &CollectionKind,
512        replay_each_tick: bool,
513        operator_tag: Option<&str>,
514    );
515
516    /// The DFIR persistence lifetime for operator state scoped to a single tick, for an operator
517    /// at `op_location`.
518    ///
519    /// Returns `'tick`. In the future (#2902), production codegen will emit tick regions as DFIR
520    /// `loop { ... }` blocks, where this must instead be `'none` when `op_location` is a tick.
521    fn tick_state_lifetime(&self, _op_location: &LocationId) -> TokenStream {
522        quote!('tick)
523    }
524
525    /// The DFIR persistence lifetime for operator state that accumulates across ticks, for an
526    /// operator at `op_location`.
527    ///
528    /// Returns `'static`. In the future (#2902), production codegen will emit tick regions as
529    /// DFIR `loop { ... }` blocks, where this must instead be `'loop` when `op_location` is a
530    /// tick.
531    fn cross_tick_state_lifetime(&self, _op_location: &LocationId) -> TokenStream {
532        quote!('static)
533    }
534
535    /// Lowers a [`HydroNode::Batch`]: windows a stream-like collection (`in_kind` must be a
536    /// stream, a keyed stream, or a keyed singleton with bounded per-key values) into the tick
537    /// at `out_location`, so that each firing observes just the elements that arrived since
538    /// the previous batch.
539    ///
540    /// Implementations must reject singleton-like `in_kind`s, which are windowed with
541    /// [`DfirBuilder::snapshot`] instead.
542    #[expect(clippy::too_many_arguments, reason = "TODO")]
543    fn batch(
544        &mut self,
545        in_ident: syn::Ident,
546        in_location: &LocationId,
547        in_kind: &CollectionKind,
548        out_ident: &syn::Ident,
549        out_location: &LocationId,
550        op_meta: &HydroIrOpMetadata,
551        fold_hooked_idents: &HashSet<String>,
552    );
553
554    /// Lowers a [`HydroNode::Snapshot`]: windows a singleton-like collection (`in_kind` must be
555    /// a singleton, an optional, or a keyed singleton whose per-key values may change) into the
556    /// tick at `out_location`, so that each firing observes the collection's current value.
557    ///
558    /// Implementations must reject stream-like `in_kind`s, which are windowed with
559    /// [`DfirBuilder::batch`] instead.
560    #[expect(clippy::too_many_arguments, reason = "TODO")]
561    fn snapshot(
562        &mut self,
563        in_ident: syn::Ident,
564        in_location: &LocationId,
565        in_kind: &CollectionKind,
566        out_ident: &syn::Ident,
567        out_location: &LocationId,
568        op_meta: &HydroIrOpMetadata,
569        fold_hooked_idents: &HashSet<String>,
570    );
571
572    fn yield_from_tick(
573        &mut self,
574        in_ident: syn::Ident,
575        in_location: &LocationId,
576        in_kind: &CollectionKind,
577        out_ident: &syn::Ident,
578        out_location: &LocationId,
579        out_kind: &CollectionKind,
580    );
581
582    /// Un-windows an ident when it is produced inside a tick's `loop { ... }` context
583    /// (`in_location`) but is about to be consumed by an operator emitted at a location
584    /// (`out_location`) outside that loop. Returns the ident to use downstream.
585    ///
586    /// This differs from [`DfirBuilder::yield_from_tick`], which lowers an explicit IR-level
587    /// tick exit ([`HydroNode::YieldConcat`], i.e. `all_ticks()`/`latest()`) and therefore
588    /// always emits a boundary crossing. This method is internal codegen plumbing with no
589    /// corresponding IR node: it is used for operators (e.g.
590    /// [`HydroNode::ReduceKeyedWatermark`]) whose generated code must sit inside a logical tick
591    /// while the output is not in a tick, and it only inserts an un-windowing operator when the
592    /// producer's and consumer's loop contexts actually differ (so it is the identity in
593    /// simulation, which emits no loops).
594    fn unwindow_for_consume(
595        &mut self,
596        in_ident: syn::Ident,
597        in_location: &LocationId,
598        out_location: &LocationId,
599    ) -> syn::Ident;
600
601    fn begin_atomic(
602        &mut self,
603        in_ident: syn::Ident,
604        in_location: &LocationId,
605        in_kind: &CollectionKind,
606        out_ident: &syn::Ident,
607        out_location: &LocationId,
608        op_meta: &HydroIrOpMetadata,
609    );
610    fn end_atomic(
611        &mut self,
612        in_ident: syn::Ident,
613        in_location: &LocationId,
614        in_kind: &CollectionKind,
615        out_ident: &syn::Ident,
616        out_kind: &CollectionKind,
617    );
618
619    #[expect(clippy::too_many_arguments, reason = "TODO // internal")]
620    fn observe_nondet(
621        &mut self,
622        trusted: bool,
623        location: &LocationId,
624        in_ident: syn::Ident,
625        in_kind: &CollectionKind,
626        out_ident: &syn::Ident,
627        out_kind: &CollectionKind,
628        op_meta: &HydroIrOpMetadata,
629    );
630
631    #[expect(clippy::too_many_arguments, reason = "TODO")]
632    fn merge_ordered(
633        &mut self,
634        location: &LocationId,
635        first_ident: syn::Ident,
636        second_ident: syn::Ident,
637        out_ident: &syn::Ident,
638        in_kind: &CollectionKind,
639        op_meta: &HydroIrOpMetadata,
640        operator_tag: Option<&str>,
641    );
642
643    #[expect(clippy::too_many_arguments, reason = "TODO")]
644    fn create_network(
645        &mut self,
646        from: &LocationId,
647        to: &LocationId,
648        input_ident: syn::Ident,
649        out_ident: &syn::Ident,
650        serialize: Option<&DebugExpr>,
651        sink: syn::Expr,
652        source: syn::Expr,
653        deserialize: Option<&DebugExpr>,
654        external_element_type: Option<&syn::Type>,
655        tag_id: StmtId,
656        networking_info: &crate::networking::NetworkingInfo,
657    );
658
659    fn create_external_source(
660        &mut self,
661        on: &LocationId,
662        source_expr: syn::Expr,
663        out_ident: &syn::Ident,
664        deserialize: Option<&DebugExpr>,
665        tag_id: StmtId,
666    );
667
668    fn create_external_output(
669        &mut self,
670        on: &LocationId,
671        sink_expr: syn::Expr,
672        input_ident: &syn::Ident,
673        serialize: Option<&DebugExpr>,
674        tag_id: StmtId,
675    );
676
677    /// Optionally emit a fold hook that buffers and permutes inputs before the fold.
678    /// Returns the new input ident to use for the fold if a hook was emitted.
679    fn emit_fold_hook(
680        &mut self,
681        location: &LocationId,
682        in_ident: &syn::Ident,
683        in_kind: &CollectionKind,
684        op_meta: &HydroIrOpMetadata,
685    ) -> Option<syn::Ident>;
686
687    /// Inserts necessary code to validate a manual assertion that at this point the
688    /// input live collection is consistent. In production, this is a no-op, but in simulation
689    /// this will (not yet implemented) inject assertions that validate consistency.
690    fn assert_is_consistent(
691        &mut self,
692        trusted: bool,
693        location: &LocationId,
694        in_ident: syn::Ident,
695        out_ident: &syn::Ident,
696    );
697
698    /// Observes non-determinism introduced by a mut closure operating on a non-strict
699    /// (unordered / at-least-once) input. In production this is identity; in simulation
700    /// it delegates to `observe_nondet` with the strict output kind.
701    fn observe_for_mut(
702        &mut self,
703        location: &LocationId,
704        in_ident: syn::Ident,
705        in_kind: &CollectionKind,
706        out_ident: &syn::Ident,
707        op_meta: &HydroIrOpMetadata,
708    );
709
710    fn create_versioned_network_fork(
711        &mut self,
712        channel_id: u32,
713        dest: &LocationId,
714        senders: Vec<(LocationId, syn::Ident, Option<DebugExpr>)>,
715        external_element_type: Option<&syn::Type>,
716        tag_id: StmtId,
717    );
718
719    #[expect(clippy::too_many_arguments, reason = "networking codegen")]
720    fn create_versioned_network(
721        &mut self,
722        channel_id: u32,
723        source: &LocationId,
724        dest: &LocationId,
725        out_ident: &syn::Ident,
726        deserialize: Option<&DebugExpr>,
727        external_element_type: Option<&syn::Type>,
728        tag_id: StmtId,
729    );
730}
731
732/// The production (deployment) DFIR builder: emits one DFIR graph per root location
733/// (process/cluster).
734///
735/// Tick and atomic locations are collapsed onto their root location's graph. In the future
736/// (#2902), this builder will additionally emit each (unified) tick as a root-level
737/// `loop {{ ... }}` context within its root location's graph.
738#[cfg(feature = "build")]
739#[derive(Default)]
740pub struct ProdDfirBuilder {
741    /// The DFIR graph builder for each root location.
742    pub graphs: SecondaryMap<LocationKey, FlatGraphBuilder>,
743    /// The `loop { ... }` context emitted for each (unified) tick location. Keyed by the tick's
744    /// [`LocationId`] (which carries the `ClockId`), so multiple ticks on the same root location
745    /// each get their own sibling root-level loop within that root's graph.
746    tick_loops: HashMap<LocationId, dfir_lang::graph::GraphLoopId>,
747    /// Counter for generating unique intermediate idents at loop boundaries.
748    next_intermediate_id: usize,
749}
750
751#[cfg(feature = "build")]
752impl ProdDfirBuilder {
753    /// Gets the DFIR builder for the given location's root, creating it if necessary.
754    fn graph_mut(&mut self, location: &LocationId) -> &mut FlatGraphBuilder {
755        self.graphs
756            .entry(location.root().key())
757            .expect("location was removed")
758            .or_default()
759    }
760
761    /// Returns the `loop { ... }` context for the given location, creating it (as a root-level
762    /// loop in the location's root graph) if necessary. Returns `None` for top-level locations.
763    fn loop_context(&mut self, location: &LocationId) -> Option<dfir_lang::graph::GraphLoopId> {
764        let tick_location = tick_location_of(location)?.clone();
765        if let Some(&loop_id) = self.tick_loops.get(&tick_location) {
766            return Some(loop_id);
767        }
768        let loop_id = self.graph_mut(location).insert_loop(None);
769        self.tick_loops.insert(tick_location, loop_id);
770        Some(loop_id)
771    }
772
773    /// Adds the DFIR statements to the graph for the given location, inside the tick's loop
774    /// context if the location is a tick or atomic location (otherwise at the root level).
775    fn add_dfir_in(
776        &mut self,
777        location: &LocationId,
778        dfir: dfir_lang::parse::DfirCode,
779        operator_tag: Option<&str>,
780    ) {
781        let loop_context = self.loop_context(location);
782        self.graph_mut(location)
783            .add_dfir(dfir, loop_context, operator_tag);
784    }
785
786    /// Generates a unique intermediate identifier for loop-boundary plumbing.
787    fn intermediate_ident(&mut self) -> syn::Ident {
788        let id = self.next_intermediate_id;
789        self.next_intermediate_id += 1;
790        syn::Ident::new(&format!("__loop_boundary_{}", id), Span::call_site())
791    }
792}
793
794#[cfg(feature = "build")]
795impl DfirBuilder for ProdDfirBuilder {
796    fn singleton_intermediates(&self) -> bool {
797        false
798    }
799
800    fn add_dfir_at(
801        &mut self,
802        location: &LocationId,
803        dfir: dfir_lang::parse::DfirCode,
804        operator_tag: Option<&str>,
805    ) {
806        // Place tick/atomic-located statements inside the tick's loop context; everything else
807        // at the root level.
808        self.add_dfir_in(location, dfir, operator_tag);
809    }
810
811    /// In production, DFIR sources must be at the root level, outside of the tick's
812    /// `loop { ... }` context: it emits the source at the root and windows it into the loop.
813    fn add_tick_source(
814        &mut self,
815        location: &LocationId,
816        source_rhs: TokenStream,
817        out_ident: &syn::Ident,
818        kind: &CollectionKind,
819        replay_each_tick: bool,
820        operator_tag: Option<&str>,
821    ) {
822        // DFIR sources must be at the root level, not inside a `loop { ... }` context. Emit the
823        // source at the root, then window it into the tick's loop. Every windowing choice here
824        // is lazy: a tick-located source never causes its tick to fire on its own (only
825        // stream inputs batched in from outside the tick do).
826        let source_ident = self.intermediate_ident();
827        self.graph_mut(location).add_dfir(
828            parse_quote! {
829                #source_ident = #source_rhs;
830            },
831            None,
832            operator_tag,
833        );
834        let windowing: syn::Ident = if !replay_each_tick {
835            // Delivered only on the first tick: the root source emits only on the first DFIR
836            // tick, and the value is observed only if the tick fires during it.
837            parse_quote!(batch_lazy)
838        } else {
839            match kind {
840                // A replayed stream: `snapshot_prefix()` retains every element in a persistent
841                // buffer that each firing observes in full (so no `persist` is needed).
842                CollectionKind::Stream { .. } | CollectionKind::KeyedStream { .. } => {
843                    parse_quote!(snapshot_prefix)
844                }
845                // A replayed singleton-like value: `snapshot()` holds it in a persistent cell
846                // that each firing observes (so no `persist` is needed).
847                CollectionKind::Singleton { .. } | CollectionKind::Optional { .. } => {
848                    parse_quote!(snapshot)
849                }
850                CollectionKind::KeyedSingleton { .. } => {
851                    unimplemented!("tick-located keyed singleton sources are not supported")
852                }
853            }
854        };
855        self.add_dfir_in(
856            location,
857            parse_quote! {
858                #out_ident = #source_ident -> #windowing();
859            },
860            operator_tag,
861        );
862    }
863
864    fn batch(
865        &mut self,
866        in_ident: syn::Ident,
867        in_location: &LocationId,
868        in_kind: &CollectionKind,
869        out_ident: &syn::Ident,
870        out_location: &LocationId,
871        _op_meta: &HydroIrOpMetadata,
872        _fold_hooked_idents: &HashSet<String>,
873    ) {
874        match (
875            tick_location_of(in_location),
876            tick_location_of(out_location),
877        ) {
878            (Some(in_tick), Some(out_tick)) => {
879                // Within the same (unified) tick, e.g. entering the tick from its associated
880                // atomic region: both sides live in the same loop.
881                assert_eq!(
882                    in_tick, out_tick,
883                    "batch between distinct ticks should have been unified"
884                );
885                self.add_dfir_in(
886                    out_location,
887                    parse_quote! {
888                        #out_ident = #in_ident;
889                    },
890                    None,
891                );
892            }
893            (None, Some(_)) => {
894                // Entering the tick's loop from the top level: emit a windowing operator.
895                // `batch_eager()` preserves the pre-loop tick semantics: the loop fires on every
896                // tick even when the windowed input is empty.
897                match in_kind {
898                    // Streams and keyed streams are plain event feeds: a batch is simply the
899                    // new events. Keyed singletons with bounded per-key values keep the plain
900                    // `(K, V)` entry feed, where each entry's value arrives exactly once, and a
901                    // batch is defined to contain just the *new* finalized entries.
902                    CollectionKind::Stream { .. }
903                    | CollectionKind::KeyedStream { .. }
904                    | CollectionKind::KeyedSingleton {
905                        bound:
906                            KeyedSingletonBoundKind::BoundedValue | KeyedSingletonBoundKind::Bounded,
907                        ..
908                    } => {
909                        self.add_dfir_in(
910                            out_location,
911                            parse_quote! {
912                                #out_ident = #in_ident -> batch_eager();
913                            },
914                            None,
915                        );
916                    }
917
918                    CollectionKind::Singleton { .. }
919                    | CollectionKind::Optional { .. }
920                    | CollectionKind::KeyedSingleton {
921                        bound:
922                            KeyedSingletonBoundKind::Unbounded
923                            | KeyedSingletonBoundKind::MonotonicKeys
924                            | KeyedSingletonBoundKind::MonotonicValue,
925                        ..
926                    } => {
927                        panic!(
928                            "`Batch` is only defined for stream-like collections (streams, keyed \
929                             streams, and keyed singletons with bounded per-key values), but was \
930                             applied to a singleton-like collection {in_kind:?}; use `Snapshot` \
931                             instead"
932                        );
933                    }
934                }
935            }
936            (Some(_) | None, None) => {
937                unreachable!("batch must target a tick location");
938            }
939        }
940    }
941
942    fn snapshot(
943        &mut self,
944        in_ident: syn::Ident,
945        in_location: &LocationId,
946        in_kind: &CollectionKind,
947        out_ident: &syn::Ident,
948        out_location: &LocationId,
949        _op_meta: &HydroIrOpMetadata,
950        _fold_hooked_idents: &HashSet<String>,
951    ) {
952        match (
953            tick_location_of(in_location),
954            tick_location_of(out_location),
955        ) {
956            (Some(in_tick), Some(out_tick)) => {
957                // Within the same (unified) tick, e.g. entering the tick from its associated
958                // atomic region: both sides live in the same loop.
959                assert_eq!(
960                    in_tick, out_tick,
961                    "snapshot between distinct ticks should have been unified"
962                );
963                // NOTE(#2902): a bounded singleton-like value produced once inside the
964                // loop (e.g. by `fold_no_replay` in an atomic region) needs to be held across
965                // firings. Operators in atomic regions have `'static` lifetimes so they should
966                // be persisted and replayed properly.
967                self.add_dfir_in(
968                    out_location,
969                    parse_quote! {
970                        #out_ident = #in_ident;
971                    },
972                    None,
973                );
974            }
975            (None, Some(_)) => {
976                // Entering the tick's loop from the top level: emit a windowing operator.
977                // NOTE: this is the single point deciding how singleton-like values are windowed
978                // into a tick. Snapshot ingress never causes the tick to fire on its own — the
979                // tick runs only when gated by a stream batch, a `defer_tick` back-edge, or a
980                // source. All arms window in with DFIR `snapshot()`: a persistent last-write-wins
981                // cell that is *not* consumed when the loop fires, so every firing observes the
982                // latest value, no matter how many ticks passed without the loop firing, and no
983                // update is ever missed (even for emit-on-change producers such as
984                // `Optional::latest()` yields or watermark deltas). Memory is bounded by the
985                // single held value.
986                //
987                // `snapshot()` holds exactly one item, so it fits singleton-like feeds (each item
988                // is the whole current value). Keyed feeds carry one entry per item, so they use
989                // `snapshot_keyed()`, which holds the latest value per key.
990                match in_kind {
991                    // Singletons and optionals whose root representation is a feed of plain `T`
992                    // updates (or a single value, if bounded). The cell holds the latest one.
993                    // Until the first update arrives the snapshot is empty: for a singleton the
994                    // first update arrives before any consumer could observe it (the upstream
995                    // aggregation emits its initial value immediately), and for an optional
996                    // "no value yet" genuinely means null.
997                    CollectionKind::Singleton { .. }
998                    | CollectionKind::Optional {
999                        bound: OptionalBoundKind::Bounded | OptionalBoundKind::InitNone,
1000                        ..
1001                    } => {
1002                        self.add_dfir_in(
1003                            out_location,
1004                            parse_quote! {
1005                                #out_ident = #in_ident -> snapshot();
1006                            },
1007                            None,
1008                        );
1009                    }
1010
1011                    // A root unbounded optional is a tombstoned update feed of `Option<T>`
1012                    // (see [`CollectionKind::root_repr_is_tombstoned_update_feed`]). The cell
1013                    // holds the latest `Option<T>`: a tombstone (or no update yet) means the
1014                    // optional is currently null.
1015                    CollectionKind::Optional {
1016                        bound: OptionalBoundKind::Unbounded,
1017                        ..
1018                    } => {
1019                        self.add_dfir_in(
1020                            out_location,
1021                            parse_quote! {
1022                                #out_ident = #in_ident -> snapshot() -> flatten();
1023                            },
1024                            None,
1025                        );
1026                    }
1027
1028                    // A root unbounded keyed singleton is a tombstoned update feed of
1029                    // `(K, Option<V>)` (see
1030                    // [`CollectionKind::root_repr_is_tombstoned_update_feed`]), which is exactly
1031                    // the update feed `snapshot_keyed()` applies (upserts and removals).
1032                    CollectionKind::KeyedSingleton {
1033                        bound: KeyedSingletonBoundKind::Unbounded,
1034                        ..
1035                    } => {
1036                        self.add_dfir_in(
1037                            out_location,
1038                            parse_quote! {
1039                                #out_ident = #in_ident -> snapshot_keyed();
1040                            },
1041                            None,
1042                        );
1043                    }
1044
1045                    // The keyed-singleton kinds that never remove keys (`Bounded`,
1046                    // `MonotonicKeys`, `MonotonicValue`) are a plain `(K, V)` entry feed, where a
1047                    // later entry for a key supersedes earlier ones (whether the producer replays
1048                    // all entries every tick or emits only changed ones). Each entry is an upsert.
1049                    CollectionKind::KeyedSingleton {
1050                        bound:
1051                            KeyedSingletonBoundKind::Bounded
1052                            | KeyedSingletonBoundKind::MonotonicKeys
1053                            | KeyedSingletonBoundKind::MonotonicValue,
1054                        ..
1055                    } => {
1056                        // The upsert `map` runs at the root: the windowing operator must be the
1057                        // first operator inside the loop.
1058                        let upserts_ident = self.intermediate_ident();
1059                        self.add_dfir_in(
1060                            in_location,
1061                            parse_quote! {
1062                                #upserts_ident = #in_ident
1063                                    -> map(|(key, value)| (key, ::std::option::Option::Some(value)));
1064                            },
1065                            None,
1066                        );
1067                        self.add_dfir_in(
1068                            out_location,
1069                            parse_quote! {
1070                                #out_ident = #upserts_ident -> snapshot_keyed();
1071                            },
1072                            None,
1073                        );
1074                    }
1075
1076                    CollectionKind::Stream { .. }
1077                    | CollectionKind::KeyedStream { .. }
1078                    | CollectionKind::KeyedSingleton {
1079                        bound: KeyedSingletonBoundKind::BoundedValue,
1080                        ..
1081                    } => {
1082                        panic!(
1083                            "`Snapshot` is only defined for singleton-like collections \
1084                             (singletons, optionals, and keyed singletons whose per-key values \
1085                             may change), but was applied to a stream-like collection \
1086                             {in_kind:?}; use `Batch` instead"
1087                        );
1088                    }
1089                }
1090            }
1091            (Some(_) | None, None) => {
1092                unreachable!("snapshot must target a tick location");
1093            }
1094        }
1095    }
1096
1097    fn yield_from_tick(
1098        &mut self,
1099        in_ident: syn::Ident,
1100        in_location: &LocationId,
1101        _in_kind: &CollectionKind,
1102        out_ident: &syn::Ident,
1103        out_location: &LocationId,
1104        out_kind: &CollectionKind,
1105    ) {
1106        // A `YieldConcat` may target either the top level (`latest`/`all_ticks`) or an atomic
1107        // region wrapping the *same* tick (`latest_atomic`/`all_ticks_atomic`). The atomic region
1108        // is fused with (runs synchronously inside) its tick's loop, so a yield into it stays in
1109        // the loop and is emitted as identity — emitting `all_iterations()` there would illegally
1110        // exit the loop even though the consumer lives inside it. This mirrors the simulation
1111        // builder, which also emits identity for a same-tick atomic yield.
1112        match (
1113            tick_location_of(in_location),
1114            tick_location_of(out_location),
1115        ) {
1116            (Some(in_tick), Some(out_tick)) => {
1117                assert_eq!(
1118                    in_tick, out_tick,
1119                    "atomic yield to a different tick should have been unified"
1120                );
1121                self.add_dfir_in(
1122                    out_location,
1123                    parse_quote! {
1124                        #out_ident = #in_ident;
1125                    },
1126                    None,
1127                );
1128            }
1129            _ => {
1130                // Exit the tick's loop back to the top level.
1131                match out_kind {
1132                    CollectionKind::Optional {
1133                        bound: OptionalBoundKind::Unbounded,
1134                        ..
1135                    } => {
1136                        // `Optional::latest()`: the root unbounded optional is a tombstoned
1137                        // update feed of `Option<T>`. Emit exactly one update per firing —
1138                        // `Some(v)` when the tick optional has a value, `None` (a tombstone)
1139                        // when it is null — so that downstream observers can distinguish
1140                        // "became null" from "no update". The `fold` runs inside the loop (a
1141                        // `'tick` accumulator, reset each firing, that captures the 0-or-1
1142                        // element of the tick optional) and emits once per firing even when
1143                        // its input is empty.
1144                        let folded_ident = self.intermediate_ident();
1145                        let lifetime: TokenStream = self.tick_state_lifetime(in_location);
1146                        let lifetime: syn::Lifetime = syn::parse2(lifetime).unwrap();
1147                        self.add_dfir_in(
1148                            in_location,
1149                            parse_quote! {
1150                                #folded_ident = #in_ident
1151                                    -> fold::<#lifetime>(|| None, |update, value| { *update = Some(value); });
1152                            },
1153                            None,
1154                        );
1155                        self.graph_mut(in_location).add_dfir(
1156                            parse_quote! {
1157                                #out_ident = #folded_ident -> all_iterations();
1158                            },
1159                            None,
1160                            None,
1161                        );
1162                    }
1163                    CollectionKind::KeyedSingleton {
1164                        bound: KeyedSingletonBoundKind::Unbounded,
1165                        ..
1166                    } => {
1167                        // The root representation is a tombstoned `(K, Option<V>)` update feed
1168                        // (see [`CollectionKind::root_repr_is_tombstoned_update_feed`]), but
1169                        // no API currently yields an unbounded keyed singleton out of a tick
1170                        // (there is no `KeyedSingleton::latest()`). Emitting this yield would
1171                        // require diffing the per-firing entry set against the previous
1172                        // firing's to synthesize tombstones for disappeared keys.
1173                        todo!(
1174                            "yielding an unbounded KeyedSingleton out of a tick is not yet supported"
1175                        );
1176                    }
1177                    _ => {
1178                        // `in_ident` is produced inside the loop; `all_iterations()` is the
1179                        // un-windowing operator, emitted at the root level.
1180                        self.graph_mut(in_location).add_dfir(
1181                            parse_quote! {
1182                                #out_ident = #in_ident -> all_iterations();
1183                            },
1184                            None,
1185                            None,
1186                        );
1187                    }
1188                }
1189            }
1190        }
1191    }
1192
1193    fn unwindow_for_consume(
1194        &mut self,
1195        in_ident: syn::Ident,
1196        in_location: &LocationId,
1197        out_location: &LocationId,
1198    ) -> syn::Ident {
1199        // If the input lives inside a tick's loop context but the consumer is emitted outside
1200        // that loop, the raw edge would illegally exit the loop. Insert an `all_iterations()`
1201        // un-windowing operator (emitted at the root level of the input's graph, just like
1202        // `yield_from_tick`) so the boundary crossing is explicit and legal.
1203        let in_loop = self.loop_context(in_location);
1204        let out_loop = self.loop_context(out_location);
1205        if in_loop.is_some() && in_loop != out_loop {
1206            let out_ident = self.intermediate_ident();
1207            self.graph_mut(in_location).add_dfir(
1208                parse_quote! {
1209                    #out_ident = #in_ident -> all_iterations();
1210                },
1211                None,
1212                None,
1213            );
1214            out_ident
1215        } else {
1216            in_ident
1217        }
1218    }
1219
1220    fn begin_atomic(
1221        &mut self,
1222        in_ident: syn::Ident,
1223        in_location: &LocationId,
1224        in_kind: &CollectionKind,
1225        out_ident: &syn::Ident,
1226        out_location: &LocationId,
1227        op_meta: &HydroIrOpMetadata,
1228    ) {
1229        // An atomic region is fused with (runs synchronously inside) its tick's loop. Entering it
1230        // from the top level windows data in; entering from within the same tick is identity.
1231        match (
1232            tick_location_of(in_location),
1233            tick_location_of(out_location),
1234        ) {
1235            (None, Some(_)) => {
1236                // Entering the loop from the root is the same representational boundary as a
1237                // snapshot: singleton-like values need held-state (and, for tombstoned update
1238                // feeds, un-tombstoning) so that inside the loop they are plain per-firing
1239                // values. Delegate to the `batch` logic, which handles every collection kind.
1240                self.batch(
1241                    in_ident,
1242                    in_location,
1243                    in_kind,
1244                    out_ident,
1245                    out_location,
1246                    op_meta,
1247                    &HashSet::new(),
1248                );
1249            }
1250            _ => {
1251                self.add_dfir_in(
1252                    out_location,
1253                    parse_quote! {
1254                        #out_ident = #in_ident;
1255                    },
1256                    None,
1257                );
1258            }
1259        }
1260    }
1261
1262    fn end_atomic(
1263        &mut self,
1264        in_ident: syn::Ident,
1265        in_location: &LocationId,
1266        in_kind: &CollectionKind,
1267        out_ident: &syn::Ident,
1268        out_kind: &CollectionKind,
1269    ) {
1270        // Exit the atomic region (and thus the tick's loop) back to the top level. This is the
1271        // same representational boundary as `yield_from_tick`: root unbounded optionals become
1272        // tombstoned `Option<T>` update feeds.
1273        let out_location = in_location.root().clone();
1274        self.yield_from_tick(
1275            in_ident,
1276            in_location,
1277            in_kind,
1278            out_ident,
1279            &out_location,
1280            out_kind,
1281        );
1282    }
1283
1284    fn observe_nondet(
1285        &mut self,
1286        _trusted: bool,
1287        location: &LocationId,
1288        in_ident: syn::Ident,
1289        _in_kind: &CollectionKind,
1290        out_ident: &syn::Ident,
1291        _out_kind: &CollectionKind,
1292        _op_meta: &HydroIrOpMetadata,
1293    ) {
1294        let builder = self.graph_mut(location);
1295        builder.add_dfir(
1296            parse_quote! {
1297                #out_ident = #in_ident;
1298            },
1299            None,
1300            None,
1301        );
1302    }
1303
1304    fn merge_ordered(
1305        &mut self,
1306        location: &LocationId,
1307        first_ident: syn::Ident,
1308        second_ident: syn::Ident,
1309        out_ident: &syn::Ident,
1310        _in_kind: &CollectionKind,
1311        _op_meta: &HydroIrOpMetadata,
1312        operator_tag: Option<&str>,
1313    ) {
1314        let builder = self.graph_mut(location);
1315        builder.add_dfir(
1316            parse_quote! {
1317                #out_ident = union();
1318                #first_ident -> [0]#out_ident;
1319                #second_ident -> [1]#out_ident;
1320            },
1321            None,
1322            operator_tag,
1323        );
1324    }
1325
1326    fn create_network(
1327        &mut self,
1328        from: &LocationId,
1329        to: &LocationId,
1330        input_ident: syn::Ident,
1331        out_ident: &syn::Ident,
1332        serialize: Option<&DebugExpr>,
1333        sink: syn::Expr,
1334        source: syn::Expr,
1335        deserialize: Option<&DebugExpr>,
1336        _external_element_type: Option<&syn::Type>,
1337        tag_id: StmtId,
1338        _networking_info: &crate::networking::NetworkingInfo,
1339    ) {
1340        let sender_builder = self.graph_mut(from);
1341        if let Some(serialize_pipeline) = serialize {
1342            sender_builder.add_dfir(
1343                parse_quote! {
1344                    #input_ident -> map(#serialize_pipeline) -> dest_sink(#sink);
1345                },
1346                None,
1347                // operator tag separates send and receive, which otherwise have the same next_stmt_id
1348                Some(&format!("send{}", tag_id)),
1349            );
1350        } else {
1351            sender_builder.add_dfir(
1352                parse_quote! {
1353                    #input_ident -> dest_sink(#sink);
1354                },
1355                None,
1356                Some(&format!("send{}", tag_id)),
1357            );
1358        }
1359
1360        let receiver_builder = self.graph_mut(to);
1361        if let Some(deserialize_pipeline) = deserialize {
1362            receiver_builder.add_dfir(
1363                parse_quote! {
1364                    #out_ident = source_stream(#source) -> map(#deserialize_pipeline);
1365                },
1366                None,
1367                Some(&format!("recv{}", tag_id)),
1368            );
1369        } else {
1370            receiver_builder.add_dfir(
1371                parse_quote! {
1372                    #out_ident = source_stream(#source);
1373                },
1374                None,
1375                Some(&format!("recv{}", tag_id)),
1376            );
1377        }
1378    }
1379
1380    fn create_external_source(
1381        &mut self,
1382        on: &LocationId,
1383        source_expr: syn::Expr,
1384        out_ident: &syn::Ident,
1385        deserialize: Option<&DebugExpr>,
1386        tag_id: StmtId,
1387    ) {
1388        let receiver_builder = self.graph_mut(on);
1389        if let Some(deserialize_pipeline) = deserialize {
1390            receiver_builder.add_dfir(
1391                parse_quote! {
1392                    #out_ident = source_stream(#source_expr) -> map(#deserialize_pipeline);
1393                },
1394                None,
1395                Some(&format!("recv{}", tag_id)),
1396            );
1397        } else {
1398            receiver_builder.add_dfir(
1399                parse_quote! {
1400                    #out_ident = source_stream(#source_expr);
1401                },
1402                None,
1403                Some(&format!("recv{}", tag_id)),
1404            );
1405        }
1406    }
1407
1408    fn create_external_output(
1409        &mut self,
1410        on: &LocationId,
1411        sink_expr: syn::Expr,
1412        input_ident: &syn::Ident,
1413        serialize: Option<&DebugExpr>,
1414        tag_id: StmtId,
1415    ) {
1416        let sender_builder = self.graph_mut(on);
1417        if let Some(serialize_fn) = serialize {
1418            sender_builder.add_dfir(
1419                parse_quote! {
1420                    #input_ident -> map(#serialize_fn) -> dest_sink(#sink_expr);
1421                },
1422                None,
1423                // operator tag separates send and receive, which otherwise have the same next_stmt_id
1424                Some(&format!("send{}", tag_id)),
1425            );
1426        } else {
1427            sender_builder.add_dfir(
1428                parse_quote! {
1429                    #input_ident -> dest_sink(#sink_expr);
1430                },
1431                None,
1432                Some(&format!("send{}", tag_id)),
1433            );
1434        }
1435    }
1436
1437    fn emit_fold_hook(
1438        &mut self,
1439        _location: &LocationId,
1440        _in_ident: &syn::Ident,
1441        _in_kind: &CollectionKind,
1442        _op_meta: &HydroIrOpMetadata,
1443    ) -> Option<syn::Ident> {
1444        None
1445    }
1446
1447    fn assert_is_consistent(
1448        &mut self,
1449        _trusted: bool,
1450        location: &LocationId,
1451        in_ident: syn::Ident,
1452        out_ident: &syn::Ident,
1453    ) {
1454        let builder = self.graph_mut(location);
1455        builder.add_dfir(
1456            parse_quote! {
1457                #out_ident = #in_ident;
1458            },
1459            None,
1460            None,
1461        );
1462    }
1463
1464    fn observe_for_mut(
1465        &mut self,
1466        location: &LocationId,
1467        in_ident: syn::Ident,
1468        _in_kind: &CollectionKind,
1469        out_ident: &syn::Ident,
1470        _op_meta: &HydroIrOpMetadata,
1471    ) {
1472        let builder = self.graph_mut(location);
1473        builder.add_dfir(
1474            parse_quote! {
1475                #out_ident = #in_ident;
1476            },
1477            None,
1478            None,
1479        );
1480    }
1481
1482    fn create_versioned_network_fork(
1483        &mut self,
1484        _channel_id: u32,
1485        _dest: &LocationId,
1486        _senders: Vec<(LocationId, syn::Ident, Option<DebugExpr>)>,
1487        _external_element_type: Option<&syn::Type>,
1488        _tag_id: StmtId,
1489    ) {
1490        unreachable!(
1491            "HydroNode::VersionedNetworkFork is only produced by the multi-version simulator merge \
1492             pass and cannot be emitted by the non-simulation builder"
1493        );
1494    }
1495
1496    fn create_versioned_network(
1497        &mut self,
1498        _channel_id: u32,
1499        _source: &LocationId,
1500        _dest: &LocationId,
1501        _out_ident: &syn::Ident,
1502        _deserialize: Option<&DebugExpr>,
1503        _external_element_type: Option<&syn::Type>,
1504        _tag_id: StmtId,
1505    ) {
1506        unreachable!(
1507            "HydroNode::VersionedNetwork is only produced by the multi-version simulator merge \
1508             pass and cannot be emitted by the non-simulation builder"
1509        );
1510    }
1511}
1512
1513#[cfg(feature = "build")]
1514pub enum BuildersOrCallback<'a, L, N>
1515where
1516    L: FnMut(&mut HydroRoot, &mut crate::Counter<StmtId>),
1517    N: FnMut(&mut HydroNode, &mut crate::Counter<StmtId>),
1518{
1519    Builders(&'a mut dyn DfirBuilder),
1520    Callback(L, N),
1521}
1522
1523/// An root in a Hydro graph, which is an pipeline that doesn't emit
1524/// any downstream values. Traversals over the dataflow graph and
1525/// generating DFIR IR start from roots.
1526#[derive(Debug, Hash, serde::Serialize)]
1527pub enum HydroRoot {
1528    ForEach {
1529        f: ClosureExpr,
1530        input: Box<HydroNode>,
1531        op_metadata: HydroIrOpMetadata,
1532    },
1533    SendExternal {
1534        to_external_key: LocationKey,
1535        to_port_id: ExternalPortId,
1536        to_many: bool,
1537        unpaired: bool,
1538        serialize_fn: Option<DebugExpr>,
1539        instantiate_fn: DebugInstantiate,
1540        input: Box<HydroNode>,
1541        op_metadata: HydroIrOpMetadata,
1542    },
1543    DestSink {
1544        sink: DebugExpr,
1545        input: Box<HydroNode>,
1546        op_metadata: HydroIrOpMetadata,
1547    },
1548    CycleSink {
1549        cycle_id: CycleId,
1550        input: Box<HydroNode>,
1551        op_metadata: HydroIrOpMetadata,
1552    },
1553    EmbeddedOutput {
1554        #[serde(serialize_with = "serialize_ident")]
1555        ident: syn::Ident,
1556        input: Box<HydroNode>,
1557        op_metadata: HydroIrOpMetadata,
1558    },
1559    Null {
1560        input: Box<HydroNode>,
1561        op_metadata: HydroIrOpMetadata,
1562    },
1563}
1564
1565impl HydroRoot {
1566    #[cfg(feature = "build")]
1567    #[expect(clippy::too_many_arguments, reason = "TODO(internal)")]
1568    pub fn compile_network<'a, D>(
1569        &mut self,
1570        extra_stmts: &mut SparseSecondaryMap<LocationKey, Vec<syn::Stmt>>,
1571        seen_tees: &mut SeenSharedNodes,
1572        seen_cluster_members: &mut HashSet<(LocationId, LocationKey)>,
1573        processes: &SparseSecondaryMap<LocationKey, D::Process>,
1574        clusters: &SparseSecondaryMap<LocationKey, D::Cluster>,
1575        externals: &SparseSecondaryMap<LocationKey, D::External>,
1576        env: &mut D::InstantiateEnv,
1577    ) where
1578        D: Deploy<'a>,
1579    {
1580        let refcell_extra_stmts = RefCell::new(extra_stmts);
1581        let refcell_env = RefCell::new(env);
1582        let refcell_seen_cluster_members = RefCell::new(seen_cluster_members);
1583        self.transform_bottom_up(
1584            &mut |l| {
1585                if let HydroRoot::SendExternal {
1586                    #[cfg(feature = "tokio")]
1587                    input,
1588                    #[cfg(feature = "tokio")]
1589                    to_external_key,
1590                    #[cfg(feature = "tokio")]
1591                    to_port_id,
1592                    #[cfg(feature = "tokio")]
1593                    to_many,
1594                    #[cfg(feature = "tokio")]
1595                    unpaired,
1596                    #[cfg(feature = "tokio")]
1597                    instantiate_fn,
1598                    ..
1599                } = l
1600                {
1601                    #[cfg(feature = "tokio")]
1602                    let ((sink_expr, source_expr), connect_fn) = match instantiate_fn {
1603                        DebugInstantiate::Building => {
1604                            let to_node = externals
1605                                .get(*to_external_key)
1606                                .unwrap_or_else(|| {
1607                                    panic!("A external used in the graph was not instantiated: {}", to_external_key)
1608                                })
1609                                .clone();
1610
1611                            match input.metadata().location_id.root() {
1612                                &LocationId::Process(process_key) => {
1613                                    if *to_many {
1614                                        (
1615                                            (
1616                                                D::e2o_many_sink(format!("{}_{}", *to_external_key, *to_port_id)),
1617                                                parse_quote!(DUMMY),
1618                                            ),
1619                                            Box::new(|| {}) as Box<dyn FnOnce()>,
1620                                        )
1621                                    } else {
1622                                        let from_node = processes
1623                                            .get(process_key)
1624                                            .unwrap_or_else(|| {
1625                                                panic!("A process used in the graph was not instantiated: {}", process_key)
1626                                            })
1627                                            .clone();
1628
1629                                        let sink_port = from_node.next_port();
1630                                        let source_port = to_node.next_port();
1631
1632                                        if *unpaired {
1633                                            use stageleft::quote_type;
1634                                            use tokio_util::codec::LengthDelimitedCodec;
1635
1636                                            to_node.register(*to_port_id, source_port.clone());
1637
1638                                            let _ = D::e2o_source(
1639                                                refcell_extra_stmts.borrow_mut().entry(process_key).expect("location was removed").or_default(),
1640                                                &to_node, &source_port,
1641                                                &from_node, &sink_port,
1642                                                &quote_type::<LengthDelimitedCodec>(),
1643                                                &quote_type::<bytes::Bytes>(),
1644                                                format!("{}_{}", *to_external_key, *to_port_id)
1645                                            );
1646                                        }
1647
1648                                        (
1649                                            (
1650                                                D::o2e_sink(
1651                                                    &from_node,
1652                                                    &sink_port,
1653                                                    &to_node,
1654                                                    &source_port,
1655                                                    format!("{}_{}", *to_external_key, *to_port_id)
1656                                                ),
1657                                                parse_quote!(DUMMY),
1658                                            ),
1659                                            if *unpaired {
1660                                                D::e2o_connect(
1661                                                    &to_node,
1662                                                    &source_port,
1663                                                    &from_node,
1664                                                    &sink_port,
1665                                                    *to_many,
1666                                                    NetworkHint::Auto,
1667                                                )
1668                                            } else {
1669                                                Box::new(|| {}) as Box<dyn FnOnce()>
1670                                            },
1671                                        )
1672                                    }
1673                                }
1674                                LocationId::Cluster(cluster_key) => {
1675                                    let from_node = clusters
1676                                        .get(*cluster_key)
1677                                        .unwrap_or_else(|| {
1678                                            panic!("A cluster used in the graph was not instantiated: {}", cluster_key)
1679                                        })
1680                                        .clone();
1681
1682                                    let sink_port = from_node.next_port();
1683                                    let source_port = to_node.next_port();
1684
1685                                    if *unpaired {
1686                                        to_node.register(*to_port_id, source_port.clone());
1687                                    }
1688
1689                                    (
1690                                        (
1691                                            D::m2e_sink(
1692                                                &from_node,
1693                                                &sink_port,
1694                                                &to_node,
1695                                                &source_port,
1696                                                format!("{}_{}", *to_external_key, *to_port_id)
1697                                            ),
1698                                            parse_quote!(DUMMY),
1699                                        ),
1700                                        Box::new(|| {}) as Box<dyn FnOnce()>,
1701                                    )
1702                                }
1703                                _ => panic!()
1704                            }
1705                        },
1706
1707                        DebugInstantiate::Finalized(_) => panic!("network already finalized"),
1708                    };
1709
1710                    #[cfg(not(feature = "tokio"))]
1711                    {
1712                        panic!("Cannot instantiate external inputs without tokio");
1713                    };
1714
1715                    #[cfg(feature = "tokio")]
1716                    {
1717                        *instantiate_fn = DebugInstantiateFinalized {
1718                            sink: sink_expr,
1719                            source: source_expr,
1720                            connect_fn: Some(connect_fn),
1721                        }
1722                        .into();
1723                    };
1724                } else if let HydroRoot::EmbeddedOutput { ident, input, .. } = l {
1725                    let element_type = match &input.metadata().collection_kind {
1726                        CollectionKind::Stream { element_type, .. } => element_type.0.as_ref().clone(),
1727                        _ => panic!("Embedded output must have Stream collection kind"),
1728                    };
1729                    let location_key = match input.metadata().location_id.root() {
1730                        LocationId::Process(key) | LocationId::Cluster(key) => *key,
1731                        _ => panic!("Embedded output must be on a process or cluster"),
1732                    };
1733                    D::register_embedded_output(
1734                        &mut refcell_env.borrow_mut(),
1735                        location_key,
1736                        ident,
1737                        &element_type,
1738                    );
1739                }
1740            },
1741            &mut |n| {
1742                if let HydroNode::Network {
1743                    name,
1744                    networking_info,
1745                    input,
1746                    instantiate_fn,
1747                    serialize,
1748                    deserialize,
1749                    metadata,
1750                    ..
1751                } = n
1752                {
1753                    let external_types = match (
1754                        serialize.external_element_type(),
1755                        deserialize.external_element_type(),
1756                    ) {
1757                        (Some(input_type), Some(output_type)) => Some((input_type, output_type)),
1758                        _ => None,
1759                    };
1760                    let (sink_expr, source_expr, connect_fn) = match instantiate_fn {
1761                        DebugInstantiate::Building => instantiate_network::<D>(
1762                            &mut refcell_env.borrow_mut(),
1763                            input.metadata().location_id.root(),
1764                            metadata.location_id.root(),
1765                            processes,
1766                            clusters,
1767                            name.as_deref(),
1768                            networking_info,
1769                            external_types,
1770                        ),
1771
1772                        DebugInstantiate::Finalized(_) => panic!("network already finalized"),
1773                    };
1774
1775                    *instantiate_fn = DebugInstantiateFinalized {
1776                        sink: sink_expr,
1777                        source: source_expr,
1778                        connect_fn: Some(connect_fn),
1779                    }
1780                    .into();
1781                } else if let HydroNode::ExternalInput {
1782                    from_external_key,
1783                    from_port_id,
1784                    from_many,
1785                    codec_type,
1786                    encode_type,
1787                    port_hint,
1788                    instantiate_fn,
1789                    metadata,
1790                    ..
1791                } = n
1792                {
1793                    let ((sink_expr, source_expr), connect_fn) = match instantiate_fn {
1794                        DebugInstantiate::Building => {
1795                            let from_node = externals
1796                                .get(*from_external_key)
1797                                .unwrap_or_else(|| {
1798                                    panic!(
1799                                        "A external used in the graph was not instantiated: {}",
1800                                        from_external_key,
1801                                    )
1802                                })
1803                                .clone();
1804
1805                            match metadata.location_id.root() {
1806                                &LocationId::Process(process_key) => {
1807                                    let to_node = processes
1808                                        .get(process_key)
1809                                        .unwrap_or_else(|| {
1810                                            panic!("A process used in the graph was not instantiated: {}", process_key)
1811                                        })
1812                                        .clone();
1813
1814                                    let sink_port = from_node.next_port();
1815                                    let source_port = to_node.next_port();
1816
1817                                    from_node.register(*from_port_id, sink_port.clone());
1818
1819                                    (
1820                                        (
1821                                            parse_quote!(DUMMY),
1822                                            if *from_many {
1823                                                D::e2o_many_source(
1824                                                    refcell_extra_stmts.borrow_mut().entry(process_key).expect("location was removed").or_default(),
1825                                                    &to_node, &source_port,
1826                                                    codec_type.0.as_ref(),
1827                                                    encode_type.0.as_ref(),
1828                                                    format!("{}_{}", *from_external_key, *from_port_id)
1829                                                )
1830                                            } else {
1831                                                D::e2o_source(
1832                                                    refcell_extra_stmts.borrow_mut().entry(process_key).expect("location was removed").or_default(),
1833                                                    &from_node, &sink_port,
1834                                                    &to_node, &source_port,
1835                                                    codec_type.0.as_ref(),
1836                                                    encode_type.0.as_ref(),
1837                                                    format!("{}_{}", *from_external_key, *from_port_id)
1838                                                )
1839                                            },
1840                                        ),
1841                                        D::e2o_connect(&from_node, &sink_port, &to_node, &source_port, *from_many, *port_hint),
1842                                    )
1843                                }
1844                                LocationId::Cluster(cluster_key) => {
1845                                    let to_node = clusters
1846                                        .get(*cluster_key)
1847                                        .unwrap_or_else(|| {
1848                                            panic!("A cluster used in the graph was not instantiated: {}", cluster_key)
1849                                        })
1850                                        .clone();
1851
1852                                    let sink_port = from_node.next_port();
1853                                    let source_port = to_node.next_port();
1854
1855                                    from_node.register(*from_port_id, sink_port.clone());
1856
1857                                    (
1858                                        (
1859                                            parse_quote!(DUMMY),
1860                                            D::e2m_source(
1861                                                refcell_extra_stmts.borrow_mut().entry(*cluster_key).expect("location was removed").or_default(),
1862                                                &from_node, &sink_port,
1863                                                &to_node, &source_port,
1864                                                codec_type.0.as_ref(),
1865                                                encode_type.0.as_ref(),
1866                                                format!("{}_{}", *from_external_key, *from_port_id)
1867                                            ),
1868                                        ),
1869                                        D::e2m_connect(&from_node, &sink_port, &to_node, &source_port, *port_hint),
1870                                    )
1871                                }
1872                                _ => panic!()
1873                            }
1874                        },
1875
1876                        DebugInstantiate::Finalized(_) => panic!("network already finalized"),
1877                    };
1878
1879                    *instantiate_fn = DebugInstantiateFinalized {
1880                        sink: sink_expr,
1881                        source: source_expr,
1882                        connect_fn: Some(connect_fn),
1883                    }
1884                    .into();
1885                } else if let HydroNode::Source { source: HydroSource::Embedded(ident), metadata } = n {
1886                    let element_type = match &metadata.collection_kind {
1887                        CollectionKind::Stream { element_type, .. } => element_type.0.as_ref().clone(),
1888                        _ => panic!("Embedded source must have Stream collection kind"),
1889                    };
1890                    let location_key = match metadata.location_id.root() {
1891                        LocationId::Process(key) | LocationId::Cluster(key) => *key,
1892                        _ => panic!("Embedded source must be on a process or cluster"),
1893                    };
1894                    D::register_embedded_stream_input(
1895                        &mut refcell_env.borrow_mut(),
1896                        location_key,
1897                        ident,
1898                        &element_type,
1899                    );
1900                } else if let HydroNode::Source { source: HydroSource::EmbeddedSingleton(ident), metadata } = n {
1901                    let element_type = match &metadata.collection_kind {
1902                        CollectionKind::Singleton { element_type, .. } => element_type.0.as_ref().clone(),
1903                        _ => panic!("EmbeddedSingleton source must have Singleton collection kind"),
1904                    };
1905                    let location_key = match metadata.location_id.root() {
1906                        LocationId::Process(key) | LocationId::Cluster(key) => *key,
1907                        _ => panic!("EmbeddedSingleton source must be on a process or cluster"),
1908                    };
1909                    D::register_embedded_singleton_input(
1910                        &mut refcell_env.borrow_mut(),
1911                        location_key,
1912                        ident,
1913                        &element_type,
1914                    );
1915                } else if let HydroNode::Source { source: HydroSource::ClusterMembers(location_id, state), metadata } = n {
1916                    match state {
1917                        ClusterMembersState::Uninit => {
1918                            let at_location = metadata.location_id.root().clone();
1919                            let key = (at_location.clone(), location_id.key());
1920                            if refcell_seen_cluster_members.borrow_mut().insert(key) {
1921                                // First occurrence: call cluster_membership_stream and mark as Stream.
1922                                let expr = D::cluster_membership_stream(&mut refcell_env.borrow_mut(), &at_location, location_id);
1923                                *state = ClusterMembersState::Stream(expr.into());
1924                            } else {
1925                                // Already instantiated for this (at, target) pair: just tee.
1926                                *state = ClusterMembersState::Tee(at_location, location_id.clone());
1927                            }
1928                        }
1929                        ClusterMembersState::Stream(_) | ClusterMembersState::Tee(..) => {
1930                            panic!("cluster members already finalized");
1931                        }
1932                    }
1933                }
1934            },
1935            seen_tees,
1936            false,
1937        );
1938    }
1939
1940    pub fn connect_network(&mut self, seen_tees: &mut SeenSharedNodes) {
1941        self.transform_bottom_up(
1942            &mut |l| {
1943                if let HydroRoot::SendExternal { instantiate_fn, .. } = l {
1944                    match instantiate_fn {
1945                        DebugInstantiate::Building => panic!("network not built"),
1946
1947                        DebugInstantiate::Finalized(finalized) => {
1948                            (finalized.connect_fn.take().unwrap())();
1949                        }
1950                    }
1951                }
1952            },
1953            &mut |n| {
1954                if let HydroNode::Network { instantiate_fn, .. }
1955                | HydroNode::ExternalInput { instantiate_fn, .. } = n
1956                {
1957                    match instantiate_fn {
1958                        DebugInstantiate::Building => panic!("network not built"),
1959
1960                        DebugInstantiate::Finalized(finalized) => {
1961                            (finalized.connect_fn.take().unwrap())();
1962                        }
1963                    }
1964                }
1965            },
1966            seen_tees,
1967            false,
1968        );
1969    }
1970
1971    pub fn transform_bottom_up(
1972        &mut self,
1973        transform_root: &mut impl FnMut(&mut HydroRoot),
1974        transform_node: &mut impl FnMut(&mut HydroNode),
1975        seen_tees: &mut SeenSharedNodes,
1976        check_well_formed: bool,
1977    ) {
1978        self.transform_children(
1979            |n, s| n.transform_bottom_up(transform_node, s, check_well_formed),
1980            seen_tees,
1981        );
1982
1983        transform_root(self);
1984    }
1985
1986    pub fn transform_children(
1987        &mut self,
1988        mut transform: impl FnMut(&mut HydroNode, &mut SeenSharedNodes),
1989        seen_tees: &mut SeenSharedNodes,
1990    ) {
1991        match self {
1992            HydroRoot::ForEach { f, input, .. } => {
1993                f.transform_children(&mut transform, seen_tees);
1994                transform(input, seen_tees);
1995            }
1996            HydroRoot::SendExternal { input, .. }
1997            | HydroRoot::DestSink { input, .. }
1998            | HydroRoot::CycleSink { input, .. }
1999            | HydroRoot::EmbeddedOutput { input, .. }
2000            | HydroRoot::Null { input, .. } => {
2001                transform(input, seen_tees);
2002            }
2003        }
2004    }
2005
2006    pub fn deep_clone(&self, seen_tees: &mut SeenSharedNodes) -> HydroRoot {
2007        match self {
2008            HydroRoot::ForEach {
2009                f,
2010                input,
2011                op_metadata,
2012            } => HydroRoot::ForEach {
2013                f: f.deep_clone(seen_tees),
2014                input: Box::new(input.deep_clone(seen_tees)),
2015                op_metadata: op_metadata.clone(),
2016            },
2017            HydroRoot::SendExternal {
2018                to_external_key,
2019                to_port_id,
2020                to_many,
2021                unpaired,
2022                serialize_fn,
2023                instantiate_fn,
2024                input,
2025                op_metadata,
2026            } => HydroRoot::SendExternal {
2027                to_external_key: *to_external_key,
2028                to_port_id: *to_port_id,
2029                to_many: *to_many,
2030                unpaired: *unpaired,
2031                serialize_fn: serialize_fn.clone(),
2032                instantiate_fn: instantiate_fn.clone(),
2033                input: Box::new(input.deep_clone(seen_tees)),
2034                op_metadata: op_metadata.clone(),
2035            },
2036            HydroRoot::DestSink {
2037                sink,
2038                input,
2039                op_metadata,
2040            } => HydroRoot::DestSink {
2041                sink: sink.clone(),
2042                input: Box::new(input.deep_clone(seen_tees)),
2043                op_metadata: op_metadata.clone(),
2044            },
2045            HydroRoot::CycleSink {
2046                cycle_id,
2047                input,
2048                op_metadata,
2049            } => HydroRoot::CycleSink {
2050                cycle_id: *cycle_id,
2051                input: Box::new(input.deep_clone(seen_tees)),
2052                op_metadata: op_metadata.clone(),
2053            },
2054            HydroRoot::EmbeddedOutput {
2055                ident,
2056                input,
2057                op_metadata,
2058            } => HydroRoot::EmbeddedOutput {
2059                ident: ident.clone(),
2060                input: Box::new(input.deep_clone(seen_tees)),
2061                op_metadata: op_metadata.clone(),
2062            },
2063            HydroRoot::Null { input, op_metadata } => HydroRoot::Null {
2064                input: Box::new(input.deep_clone(seen_tees)),
2065                op_metadata: op_metadata.clone(),
2066            },
2067        }
2068    }
2069
2070    #[cfg(feature = "build")]
2071    pub fn emit(
2072        &mut self,
2073        graph_builders: &mut dyn DfirBuilder,
2074        seen_tees: &mut SeenSharedNodes,
2075        built_tees: &mut HashMap<*const RefCell<HydroNode>, Vec<syn::Ident>>,
2076        next_stmt_id: &mut crate::Counter<StmtId>,
2077        fold_hooked_idents: &mut HashSet<String>,
2078    ) {
2079        self.emit_core(
2080            &mut BuildersOrCallback::<
2081                fn(&mut HydroRoot, &mut crate::Counter<StmtId>),
2082                fn(&mut HydroNode, &mut crate::Counter<StmtId>),
2083            >::Builders(graph_builders),
2084            seen_tees,
2085            built_tees,
2086            next_stmt_id,
2087            fold_hooked_idents,
2088        );
2089    }
2090
2091    #[cfg(feature = "build")]
2092    pub fn emit_core(
2093        &mut self,
2094        builders_or_callback: &mut BuildersOrCallback<
2095            '_,
2096            impl FnMut(&mut HydroRoot, &mut crate::Counter<StmtId>),
2097            impl FnMut(&mut HydroNode, &mut crate::Counter<StmtId>),
2098        >,
2099        seen_tees: &mut SeenSharedNodes,
2100        built_tees: &mut HashMap<*const RefCell<HydroNode>, Vec<syn::Ident>>,
2101        next_stmt_id: &mut crate::Counter<StmtId>,
2102        fold_hooked_idents: &mut HashSet<String>,
2103    ) {
2104        match self {
2105            HydroRoot::ForEach { f, input, .. } => {
2106                let input_ident = input.emit_core(
2107                    builders_or_callback,
2108                    seen_tees,
2109                    built_tees,
2110                    next_stmt_id,
2111                    fold_hooked_idents,
2112                );
2113
2114                // for_each is always side-effecting, so we observe non-determinism
2115                // even when the closure does not capture a mut ref (unlike map/filter
2116                // which only observe when they have a mut ref).
2117                let input_ident = if !input.metadata().collection_kind.is_strict() {
2118                    let observe_stmt_id = next_stmt_id.get_and_increment();
2119                    let observe_ident =
2120                        syn::Ident::new(&format!("stream_{}", observe_stmt_id), Span::call_site());
2121                    if let BuildersOrCallback::Builders(graph_builders) = builders_or_callback {
2122                        graph_builders.observe_for_mut(
2123                            &input.metadata().location_id,
2124                            input_ident,
2125                            &input.metadata().collection_kind,
2126                            &observe_ident,
2127                            &input.metadata().op,
2128                        );
2129                    }
2130                    observe_ident
2131                } else {
2132                    input_ident
2133                };
2134
2135                // Emit each captured handoff reference (deduplicated via `built_tees` in the
2136                // `HydroNode::Reference` arm), so that references captured *only* by this
2137                // `for_each` closure are still materialized. This mirrors how node-level
2138                // operators (e.g. `map`) emit their closures' captured references as part of
2139                // their bottom-up traversal. This is done in both the Builders and Callback
2140                // paths so that statement IDs stay consistent between them.
2141                let mut ref_idents = Vec::new();
2142                for (ref_node, _is_mut) in f.singleton_refs.iter_mut() {
2143                    assert!(
2144                        matches!(ref_node, HydroNode::Reference { .. }),
2145                        "singleton_refs should only contain HydroNode::Reference"
2146                    );
2147                    ref_idents.push(ref_node.emit_core(
2148                        builders_or_callback,
2149                        seen_tees,
2150                        built_tees,
2151                        next_stmt_id,
2152                        fold_hooked_idents,
2153                    ));
2154                }
2155
2156                // Mint the root's statement ID only after emitting the captured refs, so that
2157                // statement IDs follow emission order and (in the Callback path) the callback
2158                // observes this root's ID as the most recently allocated one, consistent with
2159                // the other `HydroRoot` variants.
2160                let stmt_id = next_stmt_id.get_and_increment();
2161
2162                match builders_or_callback {
2163                    BuildersOrCallback::Builders(graph_builders) => {
2164                        // The refs' idents are in `singleton_refs` order, matching what
2165                        // `emit_tokens` expects on the ident stack.
2166                        let mut ident_stack: Vec<syn::Ident> = ref_idents;
2167
2168                        let f_tokens = f.emit_tokens(&mut ident_stack);
2169
2170                        graph_builders.add_dfir_at(
2171                            &input.metadata().location_id,
2172                            parse_quote! {
2173                                #input_ident -> for_each(#f_tokens);
2174                            },
2175                            Some(&stmt_id.to_string()),
2176                        );
2177                    }
2178                    BuildersOrCallback::Callback(leaf_callback, _) => {
2179                        leaf_callback(self, next_stmt_id);
2180                    }
2181                }
2182            }
2183
2184            HydroRoot::SendExternal {
2185                serialize_fn,
2186                instantiate_fn,
2187                input,
2188                ..
2189            } => {
2190                let input_ident = input.emit_core(
2191                    builders_or_callback,
2192                    seen_tees,
2193                    built_tees,
2194                    next_stmt_id,
2195                    fold_hooked_idents,
2196                );
2197
2198                let stmt_id = next_stmt_id.get_and_increment();
2199
2200                match builders_or_callback {
2201                    BuildersOrCallback::Builders(graph_builders) => {
2202                        let (sink_expr, _) = match instantiate_fn {
2203                            DebugInstantiate::Building => (
2204                                syn::parse_quote!(DUMMY_SINK),
2205                                syn::parse_quote!(DUMMY_SOURCE),
2206                            ),
2207
2208                            DebugInstantiate::Finalized(finalized) => {
2209                                (finalized.sink.clone(), finalized.source.clone())
2210                            }
2211                        };
2212
2213                        graph_builders.create_external_output(
2214                            &input.metadata().location_id,
2215                            sink_expr,
2216                            &input_ident,
2217                            serialize_fn.as_ref(),
2218                            stmt_id,
2219                        );
2220                    }
2221                    BuildersOrCallback::Callback(leaf_callback, _) => {
2222                        leaf_callback(self, next_stmt_id);
2223                    }
2224                }
2225            }
2226
2227            HydroRoot::DestSink { sink, input, .. } => {
2228                let input_ident = input.emit_core(
2229                    builders_or_callback,
2230                    seen_tees,
2231                    built_tees,
2232                    next_stmt_id,
2233                    fold_hooked_idents,
2234                );
2235
2236                let stmt_id = next_stmt_id.get_and_increment();
2237
2238                match builders_or_callback {
2239                    BuildersOrCallback::Builders(graph_builders) => {
2240                        graph_builders.add_dfir_at(
2241                            &input.metadata().location_id,
2242                            parse_quote! {
2243                                #input_ident -> dest_sink(#sink);
2244                            },
2245                            Some(&stmt_id.to_string()),
2246                        );
2247                    }
2248                    BuildersOrCallback::Callback(leaf_callback, _) => {
2249                        leaf_callback(self, next_stmt_id);
2250                    }
2251                }
2252            }
2253
2254            HydroRoot::CycleSink {
2255                cycle_id, input, ..
2256            } => {
2257                let input_ident = input.emit_core(
2258                    builders_or_callback,
2259                    seen_tees,
2260                    built_tees,
2261                    next_stmt_id,
2262                    fold_hooked_idents,
2263                );
2264
2265                match builders_or_callback {
2266                    BuildersOrCallback::Builders(graph_builders) => {
2267                        // NOTE: this must be the *pipe* element type: tombstoned update feeds
2268                        // (see [`CollectionKind::root_repr_is_tombstoned_update_feed`]) carry
2269                        // `Option<T>` update records, not plain values.
2270                        let tombstoned =
2271                            update_feed_repr(input.metadata()) == UpdateFeedRepr::Tombstoned;
2272                        let elem_type: syn::Type = match &input.metadata().collection_kind {
2273                            CollectionKind::KeyedSingleton {
2274                                key_type,
2275                                value_type,
2276                                ..
2277                            } if tombstoned => {
2278                                parse_quote!((#key_type, ::std::option::Option<#value_type>))
2279                            }
2280                            CollectionKind::KeyedSingleton {
2281                                key_type,
2282                                value_type,
2283                                ..
2284                            }
2285                            | CollectionKind::KeyedStream {
2286                                key_type,
2287                                value_type,
2288                                ..
2289                            } => {
2290                                parse_quote!((#key_type, #value_type))
2291                            }
2292                            CollectionKind::Optional { element_type, .. } if tombstoned => {
2293                                parse_quote!(::std::option::Option<#element_type>)
2294                            }
2295                            CollectionKind::Stream { element_type, .. }
2296                            | CollectionKind::Singleton { element_type, .. }
2297                            | CollectionKind::Optional { element_type, .. } => {
2298                                parse_quote!(#element_type)
2299                            }
2300                        };
2301
2302                        let cycle_id_ident = cycle_id.as_ident();
2303                        graph_builders.add_dfir_at(
2304                            &input.metadata().location_id,
2305                            parse_quote! {
2306                                #cycle_id_ident = #input_ident -> identity::<#elem_type>();
2307                            },
2308                            None,
2309                        );
2310                    }
2311                    // No ID, no callback
2312                    BuildersOrCallback::Callback(_, _) => {}
2313                }
2314            }
2315
2316            HydroRoot::EmbeddedOutput { ident, input, .. } => {
2317                let input_ident = input.emit_core(
2318                    builders_or_callback,
2319                    seen_tees,
2320                    built_tees,
2321                    next_stmt_id,
2322                    fold_hooked_idents,
2323                );
2324
2325                let stmt_id = next_stmt_id.get_and_increment();
2326
2327                match builders_or_callback {
2328                    BuildersOrCallback::Builders(graph_builders) => {
2329                        graph_builders.add_dfir_at(
2330                            &input.metadata().location_id,
2331                            parse_quote! {
2332                                #input_ident -> for_each(&mut #ident);
2333                            },
2334                            Some(&stmt_id.to_string()),
2335                        );
2336                    }
2337                    BuildersOrCallback::Callback(leaf_callback, _) => {
2338                        leaf_callback(self, next_stmt_id);
2339                    }
2340                }
2341            }
2342
2343            HydroRoot::Null { input, .. } => {
2344                let input_ident = input.emit_core(
2345                    builders_or_callback,
2346                    seen_tees,
2347                    built_tees,
2348                    next_stmt_id,
2349                    fold_hooked_idents,
2350                );
2351
2352                let stmt_id = next_stmt_id.get_and_increment();
2353
2354                match builders_or_callback {
2355                    BuildersOrCallback::Builders(graph_builders) => {
2356                        graph_builders.add_dfir_at(
2357                            &input.metadata().location_id,
2358                            parse_quote! {
2359                                #input_ident -> for_each(|_| {});
2360                            },
2361                            Some(&stmt_id.to_string()),
2362                        );
2363                    }
2364                    BuildersOrCallback::Callback(leaf_callback, _) => {
2365                        leaf_callback(self, next_stmt_id);
2366                    }
2367                }
2368            }
2369        }
2370    }
2371
2372    pub fn op_metadata(&self) -> &HydroIrOpMetadata {
2373        match self {
2374            HydroRoot::ForEach { op_metadata, .. }
2375            | HydroRoot::SendExternal { op_metadata, .. }
2376            | HydroRoot::DestSink { op_metadata, .. }
2377            | HydroRoot::CycleSink { op_metadata, .. }
2378            | HydroRoot::EmbeddedOutput { op_metadata, .. }
2379            | HydroRoot::Null { op_metadata, .. } => op_metadata,
2380        }
2381    }
2382
2383    pub fn op_metadata_mut(&mut self) -> &mut HydroIrOpMetadata {
2384        match self {
2385            HydroRoot::ForEach { op_metadata, .. }
2386            | HydroRoot::SendExternal { op_metadata, .. }
2387            | HydroRoot::DestSink { op_metadata, .. }
2388            | HydroRoot::CycleSink { op_metadata, .. }
2389            | HydroRoot::EmbeddedOutput { op_metadata, .. }
2390            | HydroRoot::Null { op_metadata, .. } => op_metadata,
2391        }
2392    }
2393
2394    pub fn input(&self) -> &HydroNode {
2395        match self {
2396            HydroRoot::ForEach { input, .. }
2397            | HydroRoot::SendExternal { input, .. }
2398            | HydroRoot::DestSink { input, .. }
2399            | HydroRoot::CycleSink { input, .. }
2400            | HydroRoot::EmbeddedOutput { input, .. }
2401            | HydroRoot::Null { input, .. } => input,
2402        }
2403    }
2404
2405    pub fn input_metadata(&self) -> &HydroIrMetadata {
2406        self.input().metadata()
2407    }
2408
2409    pub fn print_root(&self) -> String {
2410        match self {
2411            HydroRoot::ForEach { f, .. } => format!("ForEach({:?})", f),
2412            HydroRoot::SendExternal { .. } => "SendExternal".to_owned(),
2413            HydroRoot::DestSink { sink, .. } => format!("DestSink({:?})", sink),
2414            HydroRoot::CycleSink { cycle_id, .. } => format!("CycleSink({})", cycle_id),
2415            HydroRoot::EmbeddedOutput { ident, .. } => {
2416                format!("EmbeddedOutput({})", ident)
2417            }
2418            HydroRoot::Null { .. } => "Null".to_owned(),
2419        }
2420    }
2421
2422    pub fn visit_debug_expr(&mut self, mut transform: impl FnMut(&mut DebugExpr)) {
2423        match self {
2424            HydroRoot::ForEach { f, .. } => {
2425                transform(&mut f.expr);
2426            }
2427            HydroRoot::DestSink { sink, .. } => {
2428                transform(sink);
2429            }
2430            HydroRoot::SendExternal { .. }
2431            | HydroRoot::CycleSink { .. }
2432            | HydroRoot::EmbeddedOutput { .. }
2433            | HydroRoot::Null { .. } => {}
2434        }
2435    }
2436}
2437
2438/// Returns the (unified) tick location that `loc` belongs to: the location itself for tick
2439/// locations, the wrapped tick for atomic locations, and `None` for root (top-level) locations.
2440///
2441/// The returned [`LocationId`] carries the tick's [`ClockId`] (use [`tick_of`] to extract just
2442/// the clock).
2443#[cfg(feature = "build")]
2444fn tick_location_of(loc: &LocationId) -> Option<&LocationId> {
2445    match loc {
2446        // Regular tick.
2447        LocationId::Tick {
2448            tick: Some(_),
2449            parent_location: _,
2450        } => Some(loc),
2451        // Tick around atomic: the clock lives in the parent location.
2452        LocationId::Tick {
2453            tick: None,
2454            parent_location,
2455        } => Some(
2456            tick_location_of(parent_location)
2457                .expect("Tick should have either own clock ID or clock ID within parent_location."),
2458        ),
2459        LocationId::Atomic(inner) => tick_location_of(inner),
2460        LocationId::Process(_) | LocationId::Cluster(_) => None,
2461    }
2462}
2463
2464/// Returns the [`ClockId`] of the (unified) tick that `loc` belongs to (via
2465/// [`tick_location_of`]), or `None` for root (top-level) locations.
2466#[cfg(feature = "build")]
2467fn tick_of(loc: &LocationId) -> Option<ClockId> {
2468    tick_location_of(loc).map(|tick_location| match tick_location {
2469        LocationId::Tick {
2470            tick: Some(tick), ..
2471        } => *tick,
2472        _ => unreachable!("`tick_location_of` only returns ticks with a clock ID"),
2473    })
2474}
2475
2476#[cfg(feature = "build")]
2477fn remap_location(loc: &mut LocationId, uf: &mut HashMap<ClockId, ClockId>) {
2478    match loc {
2479        LocationId::Tick {
2480            tick,
2481            parent_location,
2482        } => {
2483            if let Some(tick) = tick {
2484                *tick = uf_find(uf, *tick);
2485            }
2486            remap_location(parent_location, uf);
2487        }
2488        LocationId::Atomic(inner) => {
2489            remap_location(inner, uf);
2490        }
2491        LocationId::Process(_) | LocationId::Cluster(_) => {}
2492    }
2493}
2494
2495#[cfg(feature = "build")]
2496fn uf_find(parent: &mut HashMap<ClockId, ClockId>, x: ClockId) -> ClockId {
2497    let p = *parent.get(&x).unwrap_or(&x);
2498    if p == x {
2499        return x;
2500    }
2501    let root = uf_find(parent, p);
2502    parent.insert(x, root);
2503    root
2504}
2505
2506#[cfg(feature = "build")]
2507fn uf_union(parent: &mut HashMap<ClockId, ClockId>, a: ClockId, b: ClockId) {
2508    let ra = uf_find(parent, a);
2509    let rb = uf_find(parent, b);
2510    if ra != rb {
2511        parent.insert(ra, rb);
2512    }
2513}
2514
2515/// Traverse the IR to build a union-find that unifies tick IDs connected
2516/// through `Batch`, `Snapshot`, and `YieldConcat` nodes at atomic boundaries, then
2517/// rewrite all `LocationId`s to use the representative tick ID.
2518#[cfg(feature = "build")]
2519pub fn unify_atomic_ticks(ir: &mut [HydroRoot]) {
2520    let mut uf: HashMap<ClockId, ClockId> = HashMap::new();
2521
2522    // Pass 1: collect unifications.
2523    transform_bottom_up(
2524        ir,
2525        &mut |_| {},
2526        &mut |node: &mut HydroNode| match node {
2527            HydroNode::Batch { inner, metadata }
2528            | HydroNode::Snapshot { inner, metadata }
2529            | HydroNode::YieldConcat { inner, metadata } => {
2530                if let (Some(a), Some(b)) = (
2531                    tick_of(&inner.metadata().location_id),
2532                    tick_of(&metadata.location_id),
2533                ) {
2534                    uf_union(&mut uf, a, b);
2535                }
2536            }
2537            HydroNode::Chain {
2538                first,
2539                second,
2540                metadata,
2541            }
2542            | HydroNode::ChainFirst {
2543                first,
2544                second,
2545                metadata,
2546            }
2547            | HydroNode::MergeOrdered {
2548                first,
2549                second,
2550                metadata,
2551            } => {
2552                if let (Some(a), Some(b)) = (
2553                    tick_of(&first.metadata().location_id),
2554                    tick_of(&metadata.location_id),
2555                ) {
2556                    uf_union(&mut uf, a, b);
2557                }
2558                if let (Some(a), Some(b)) = (
2559                    tick_of(&second.metadata().location_id),
2560                    tick_of(&metadata.location_id),
2561                ) {
2562                    uf_union(&mut uf, a, b);
2563                }
2564            }
2565            _ => {}
2566        },
2567        false,
2568    );
2569
2570    // Pass 2: rewrite all LocationIds.
2571    transform_bottom_up(
2572        ir,
2573        &mut |_| {},
2574        &mut |node: &mut HydroNode| {
2575            remap_location(&mut node.metadata_mut().location_id, &mut uf);
2576        },
2577        false,
2578    );
2579}
2580
2581#[cfg(feature = "build")]
2582pub fn emit(ir: &mut Vec<HydroRoot>) -> SecondaryMap<LocationKey, FlatGraphBuilder> {
2583    let mut builders = ProdDfirBuilder::default();
2584    let mut seen_tees = HashMap::new();
2585    let mut built_tees = HashMap::new();
2586    let mut next_stmt_id = crate::Counter::<StmtId>::default();
2587    let mut fold_hooked_idents = HashSet::new();
2588    for leaf in ir {
2589        leaf.emit(
2590            &mut builders,
2591            &mut seen_tees,
2592            &mut built_tees,
2593            &mut next_stmt_id,
2594            &mut fold_hooked_idents,
2595        );
2596    }
2597    builders.graphs
2598}
2599
2600#[cfg(feature = "build")]
2601pub fn traverse_dfir(
2602    ir: &mut [HydroRoot],
2603    transform_root: impl FnMut(&mut HydroRoot, &mut crate::Counter<StmtId>),
2604    transform_node: impl FnMut(&mut HydroNode, &mut crate::Counter<StmtId>),
2605) {
2606    let mut seen_tees = HashMap::new();
2607    let mut built_tees = HashMap::new();
2608    let mut next_stmt_id = crate::Counter::<StmtId>::default();
2609    let mut fold_hooked_idents = HashSet::new();
2610    let mut callback = BuildersOrCallback::Callback(transform_root, transform_node);
2611    ir.iter_mut().for_each(|leaf| {
2612        leaf.emit_core(
2613            &mut callback,
2614            &mut seen_tees,
2615            &mut built_tees,
2616            &mut next_stmt_id,
2617            &mut fold_hooked_idents,
2618        );
2619    });
2620}
2621
2622pub fn transform_bottom_up(
2623    ir: &mut [HydroRoot],
2624    transform_root: &mut impl FnMut(&mut HydroRoot),
2625    transform_node: &mut impl FnMut(&mut HydroNode),
2626    check_well_formed: bool,
2627) {
2628    let mut seen_tees = HashMap::new();
2629    ir.iter_mut().for_each(|leaf| {
2630        leaf.transform_bottom_up(
2631            transform_root,
2632            transform_node,
2633            &mut seen_tees,
2634            check_well_formed,
2635        );
2636    });
2637}
2638
2639pub fn deep_clone(ir: &[HydroRoot]) -> Vec<HydroRoot> {
2640    let mut seen_tees = HashMap::new();
2641    ir.iter()
2642        .map(|leaf| leaf.deep_clone(&mut seen_tees))
2643        .collect()
2644}
2645
2646type PrintedTees = RefCell<Option<(usize, HashMap<*const RefCell<HydroNode>, usize>)>>;
2647thread_local! {
2648    static PRINTED_TEES: PrintedTees = const { RefCell::new(None) };
2649    /// Tracks shared nodes already serialized so that `SharedNode::serialize`
2650    /// emits the full subtree only once and uses a `"<shared N>"` back-reference
2651    /// on subsequent encounters, preventing infinite loops.
2652    static SERIALIZED_SHARED: PrintedTees
2653        = const { RefCell::new(None) };
2654}
2655
2656pub fn dbg_dedup_tee<T>(f: impl FnOnce() -> T) -> T {
2657    PRINTED_TEES.with(|printed_tees| {
2658        let mut printed_tees_mut = printed_tees.borrow_mut();
2659        *printed_tees_mut = Some((0, HashMap::new()));
2660        drop(printed_tees_mut);
2661
2662        let ret = f();
2663
2664        let mut printed_tees_mut = printed_tees.borrow_mut();
2665        *printed_tees_mut = None;
2666
2667        ret
2668    })
2669}
2670
2671/// Runs `f` with a fresh shared-node deduplication scope for serialization.
2672/// Any `SharedNode` serialized inside `f` will be tracked; the first occurrence
2673/// emits the full subtree while later occurrences emit a `{"$shared_ref": id}`
2674/// back-reference.  The tracking state is restored when `f` returns or panics.
2675pub fn serialize_dedup_shared<T>(f: impl FnOnce() -> T) -> T {
2676    let _guard = SerializedSharedGuard::enter();
2677    f()
2678}
2679
2680/// RAII guard that saves/restores the `SERIALIZED_SHARED` thread-local,
2681/// making `serialize_dedup_shared` re-entrant and panic-safe.
2682struct SerializedSharedGuard {
2683    previous: Option<(usize, HashMap<*const RefCell<HydroNode>, usize>)>,
2684}
2685
2686impl SerializedSharedGuard {
2687    fn enter() -> Self {
2688        let previous = SERIALIZED_SHARED.with(|cell| {
2689            let mut guard = cell.borrow_mut();
2690            guard.replace((0, HashMap::new()))
2691        });
2692        Self { previous }
2693    }
2694}
2695
2696impl Drop for SerializedSharedGuard {
2697    fn drop(&mut self) {
2698        SERIALIZED_SHARED.with(|cell| {
2699            *cell.borrow_mut() = self.previous.take();
2700        });
2701    }
2702}
2703
2704pub struct SharedNode(pub Rc<RefCell<HydroNode>>);
2705
2706impl serde::Serialize for SharedNode {
2707    /// Multiple `SharedNode`s can point to the same underlying `HydroNode` (via
2708    /// `Tee` / `Partition`).  A naïve recursive serialization would revisit the
2709    /// same subtree every time and, if the graph ever contains a cycle, loop
2710    /// forever.
2711    ///
2712    /// We keep a thread-local map (`SERIALIZED_SHARED`) from raw `Rc` pointer →
2713    /// integer id.  The first time we see a pointer we assign it the next id and
2714    /// emit the full subtree as `{"$shared": <id>, "node": …}`.  Every later
2715    /// encounter of the same pointer emits `{"$shared_ref": <id>}`, cutting the
2716    /// recursion.  Requires an active `serialize_dedup_shared` scope.
2717    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2718        SERIALIZED_SHARED.with(|cell| {
2719            let mut guard = cell.borrow_mut();
2720            // (next_id, pointer → assigned_id)
2721            let state = guard.as_mut().ok_or_else(|| {
2722                serde::ser::Error::custom(
2723                    "SharedNode serialization requires an active serialize_dedup_shared scope",
2724                )
2725            })?;
2726            let ptr = self.0.as_ptr() as *const RefCell<HydroNode>;
2727
2728            if let Some(&id) = state.1.get(&ptr) {
2729                drop(guard);
2730                use serde::ser::SerializeMap;
2731                let mut map = serializer.serialize_map(Some(1))?;
2732                map.serialize_entry("$shared_ref", &id)?;
2733                map.end()
2734            } else {
2735                let id = state.0;
2736                state.0 += 1;
2737                state.1.insert(ptr, id);
2738                drop(guard);
2739
2740                use serde::ser::SerializeMap;
2741                let mut map = serializer.serialize_map(Some(2))?;
2742                map.serialize_entry("$shared", &id)?;
2743                map.serialize_entry("node", &*self.0.borrow())?;
2744                map.end()
2745            }
2746        })
2747    }
2748}
2749
2750impl SharedNode {
2751    pub fn as_ptr(&self) -> *const RefCell<HydroNode> {
2752        Rc::as_ptr(&self.0)
2753    }
2754}
2755
2756impl Debug for SharedNode {
2757    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2758        PRINTED_TEES.with(|printed_tees| {
2759            let mut printed_tees_mut_borrow = printed_tees.borrow_mut();
2760            let printed_tees_mut = printed_tees_mut_borrow.as_mut();
2761
2762            if let Some(printed_tees_mut) = printed_tees_mut {
2763                if let Some(existing) = printed_tees_mut
2764                    .1
2765                    .get(&(std::ptr::from_ref(self.0.as_ref())))
2766                {
2767                    write!(f, "<shared {}>", existing)
2768                } else {
2769                    let next_id = printed_tees_mut.0;
2770                    printed_tees_mut.0 += 1;
2771                    printed_tees_mut
2772                        .1
2773                        .insert(std::ptr::from_ref(self.0.as_ref()), next_id);
2774                    drop(printed_tees_mut_borrow);
2775                    write!(f, "<shared {}>: ", next_id)?;
2776                    Debug::fmt(&self.0.borrow(), f)
2777                }
2778            } else {
2779                drop(printed_tees_mut_borrow);
2780                write!(f, "<shared>: ")?;
2781                Debug::fmt(&self.0.borrow(), f)
2782            }
2783        })
2784    }
2785}
2786
2787impl Hash for SharedNode {
2788    fn hash<H: Hasher>(&self, state: &mut H) {
2789        self.0.borrow_mut().hash(state);
2790    }
2791}
2792
2793/// A counter for tracking singleton access groups on a `HydroNode::Reference`.
2794///
2795/// Each mutable access increments the counter (before and after) to isolate itself in its own group;
2796/// immutable accesses share the current group.
2797#[derive(Debug)]
2798pub enum AccessCounter {
2799    Counting(Cell<u32>),
2800    Frozen(u32),
2801}
2802
2803impl AccessCounter {
2804    pub fn new() -> Self {
2805        Self::Counting(Cell::new(0))
2806    }
2807
2808    /// Assign the next access group for this reference.
2809    /// Mutable accesses get an isolated group (counter increments before and after).
2810    /// Immutable accesses share the current group.
2811    pub fn next_group(&self, is_mut: bool) -> Self {
2812        let AccessCounter::Counting(count) = self else {
2813            panic!("Cannot count on `AccessCounter::Frozen`");
2814        };
2815        let c = if is_mut {
2816            let c = count.get() + 1;
2817            count.set(c + 1);
2818            c
2819        } else {
2820            count.get()
2821        };
2822        Self::Frozen(c)
2823    }
2824
2825    /// Creates a frozen counter to prevent further counting.
2826    pub fn freeze(&self) -> Self {
2827        Self::Frozen(match self {
2828            Self::Counting(count) => count.get(),
2829            Self::Frozen(count) => *count,
2830        })
2831    }
2832
2833    pub fn frozen_group(&self) -> u32 {
2834        let Self::Frozen(count) = self else {
2835            panic!("`AccessCounter` not frozen");
2836        };
2837        *count
2838    }
2839}
2840
2841impl Default for AccessCounter {
2842    fn default() -> Self {
2843        Self::new()
2844    }
2845}
2846
2847impl Hash for AccessCounter {
2848    fn hash<H: Hasher>(&self, _state: &mut H) {
2849        // Access counter does not participate in hashing — it is runtime bookkeeping.
2850    }
2851}
2852
2853impl serde::Serialize for AccessCounter {
2854    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2855        let count = match self {
2856            AccessCounter::Counting(count) => count.get(),
2857            AccessCounter::Frozen(count) => *count,
2858        };
2859        count.serialize(serializer)
2860    }
2861}
2862
2863#[derive(serde::Serialize, Clone, PartialEq, Eq, Debug)]
2864pub enum BoundKind {
2865    Unbounded,
2866    Bounded,
2867}
2868
2869#[derive(serde::Serialize, Clone, PartialEq, Eq, Debug)]
2870pub enum OptionalBoundKind {
2871    Unbounded,
2872    /// The optional starts out null, but once it becomes non-null it will remain non-null
2873    /// forever (though the non-null value may change arbitrarily). Erases to [`BoundKind::Unbounded`].
2874    InitNone,
2875    Bounded,
2876}
2877
2878#[derive(serde::Serialize, Clone, PartialEq, Eq, Hash, Debug)]
2879pub enum StreamOrder {
2880    NoOrder,
2881    TotalOrder,
2882}
2883
2884#[derive(serde::Serialize, Clone, PartialEq, Eq, Hash, Debug)]
2885pub enum StreamRetry {
2886    AtLeastOnce,
2887    ExactlyOnce,
2888}
2889
2890#[cfg(feature = "build")]
2891impl StreamOrder {
2892    /// The `Ordering` type for this order.
2893    pub fn type_tokens(&self) -> TokenStream {
2894        let root = crate::staging_util::get_this_crate();
2895        match self {
2896            StreamOrder::TotalOrder => quote! { #root::live_collections::stream::TotalOrder },
2897            StreamOrder::NoOrder => quote! { #root::live_collections::stream::NoOrder },
2898        }
2899    }
2900}
2901
2902#[cfg(feature = "build")]
2903impl StreamRetry {
2904    /// The `Retries` type for this retry guarantee.
2905    pub fn type_tokens(&self) -> TokenStream {
2906        let root = crate::staging_util::get_this_crate();
2907        match self {
2908            StreamRetry::ExactlyOnce => quote! { #root::live_collections::stream::ExactlyOnce },
2909            StreamRetry::AtLeastOnce => quote! { #root::live_collections::stream::AtLeastOnce },
2910        }
2911    }
2912}
2913
2914#[derive(serde::Serialize, Clone, PartialEq, Eq, Debug)]
2915pub enum KeyedSingletonBoundKind {
2916    Unbounded,
2917    MonotonicKeys,
2918    MonotonicValue,
2919    BoundedValue,
2920    Bounded,
2921}
2922
2923#[derive(serde::Serialize, Clone, PartialEq, Eq, Debug)]
2924pub enum SingletonBoundKind {
2925    Unbounded,
2926    Monotonic,
2927    Bounded,
2928}
2929
2930#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize)]
2931pub enum CollectionKind {
2932    Stream {
2933        bound: BoundKind,
2934        order: StreamOrder,
2935        retry: StreamRetry,
2936        element_type: DebugType,
2937    },
2938    Singleton {
2939        bound: SingletonBoundKind,
2940        element_type: DebugType,
2941    },
2942    Optional {
2943        bound: OptionalBoundKind,
2944        element_type: DebugType,
2945    },
2946    KeyedStream {
2947        bound: BoundKind,
2948        value_order: StreamOrder,
2949        value_retry: StreamRetry,
2950        key_type: DebugType,
2951        value_type: DebugType,
2952    },
2953    KeyedSingleton {
2954        bound: KeyedSingletonBoundKind,
2955        key_type: DebugType,
2956        value_type: DebugType,
2957    },
2958}
2959
2960impl CollectionKind {
2961    pub fn is_bounded(&self) -> bool {
2962        matches!(
2963            self,
2964            CollectionKind::Stream {
2965                bound: BoundKind::Bounded,
2966                ..
2967            } | CollectionKind::Singleton {
2968                bound: SingletonBoundKind::Bounded,
2969                ..
2970            } | CollectionKind::Optional {
2971                bound: OptionalBoundKind::Bounded,
2972                ..
2973            } | CollectionKind::KeyedStream {
2974                bound: BoundKind::Bounded,
2975                ..
2976            } | CollectionKind::KeyedSingleton {
2977                bound: KeyedSingletonBoundKind::Bounded,
2978                ..
2979            }
2980        )
2981    }
2982
2983    /// Returns whether this collection kind is already "strict" (`TotalOrder` + `ExactlyOnce`),
2984    /// meaning no non-determinism needs to be observed for mut closures.
2985    pub fn is_strict(&self) -> bool {
2986        match self {
2987            CollectionKind::Stream { order, retry, .. } => {
2988                *order == StreamOrder::TotalOrder && *retry == StreamRetry::ExactlyOnce
2989            }
2990            CollectionKind::KeyedStream {
2991                value_order,
2992                value_retry,
2993                ..
2994            } => {
2995                *value_order == StreamOrder::TotalOrder && *value_retry == StreamRetry::ExactlyOnce
2996            }
2997            // Singletons/Optionals/KeyedSingletons do not have observable
2998            // non-determinism other than snapshots / batching
2999            CollectionKind::Singleton { .. }
3000            | CollectionKind::Optional { .. }
3001            | CollectionKind::KeyedSingleton { .. } => true,
3002        }
3003    }
3004
3005    /// Returns whether this collection kind, when materialized at a **root** (non-tick,
3006    /// non-atomic) location, is represented as a "tombstoned update feed": a DFIR pipe whose
3007    /// elements are explicit update records that can express *removal*, rather than plain
3008    /// values.
3009    ///
3010    /// - [`CollectionKind::Optional`] with [`OptionalBoundKind::Unbounded`]: the pipe carries
3011    ///   `Option<T>` updates, where `None` is a tombstone recording that the optional became
3012    ///   null. (Bounded and `InitNone` optionals never become null after having a value, so
3013    ///   they are represented as plain `T` updates.)
3014    /// - [`CollectionKind::KeyedSingleton`] with [`KeyedSingletonBoundKind::Unbounded`]: the
3015    ///   pipe carries `(K, Option<V>)` updates, where `(k, Some(v))` upserts an entry and
3016    ///   `(k, None)` is a tombstone recording that key `k` was removed (e.g. garbage-collected
3017    ///   by `KeyedStream::reduce_watermark` when the watermark advances). The other keyed
3018    ///   bound kinds never remove keys (or are bounded), so they keep plain `(K, V)` entries.
3019    ///
3020    /// This representation exists because a plain update feed cannot distinguish "no update"
3021    /// from "became absent" (#3181). It applies **only** at root locations: inside a tick (or
3022    /// atomic region fused into a tick's loop), presence is re-derived every firing, so
3023    /// absence in a firing is already meaningful and plain values are used.
3024    ///
3025    /// Producers of tombstoned feeds must emit an explicit tombstone for every removal (see
3026    /// the delta-emitting `scan` in the [`HydroNode::ReduceKeyedWatermark`] codegen);
3027    /// consumers hold the latest state across firings by applying updates (see
3028    /// [`DfirBuilder::batch`]). Generated code for keyed feeds requires `K: Clone` (and
3029    /// `V: Clone`), which the pre-existing whole-map re-emission already required.
3030    pub fn root_repr_is_tombstoned_update_feed(&self) -> bool {
3031        matches!(
3032            self,
3033            CollectionKind::Optional {
3034                bound: OptionalBoundKind::Unbounded,
3035                ..
3036            } | CollectionKind::KeyedSingleton {
3037                bound: KeyedSingletonBoundKind::Unbounded,
3038                ..
3039            }
3040        )
3041    }
3042
3043    /// Creates a "strict" version of this kind with `TotalOrder` and `ExactlyOnce`.
3044    pub fn strict_kind(&self) -> CollectionKind {
3045        match self {
3046            CollectionKind::Stream {
3047                bound,
3048                element_type,
3049                ..
3050            } => CollectionKind::Stream {
3051                bound: bound.clone(),
3052                order: StreamOrder::TotalOrder,
3053                retry: StreamRetry::ExactlyOnce,
3054                element_type: element_type.clone(),
3055            },
3056            CollectionKind::KeyedStream {
3057                bound,
3058                key_type,
3059                value_type,
3060                ..
3061            } => CollectionKind::KeyedStream {
3062                bound: bound.clone(),
3063                value_order: StreamOrder::TotalOrder,
3064                value_retry: StreamRetry::ExactlyOnce,
3065                key_type: key_type.clone(),
3066                value_type: value_type.clone(),
3067            },
3068            other => other.clone(),
3069        }
3070    }
3071}
3072
3073#[derive(Clone, serde::Serialize)]
3074pub struct HydroIrMetadata {
3075    pub location_id: LocationId,
3076    pub collection_kind: CollectionKind,
3077    pub consistency: Option<ClusterConsistency>,
3078    pub cardinality: Option<usize>,
3079    pub tag: Option<String>,
3080    pub op: HydroIrOpMetadata,
3081}
3082
3083// HydroIrMetadata shouldn't be used to hash or compare
3084impl Hash for HydroIrMetadata {
3085    fn hash<H: Hasher>(&self, _: &mut H) {}
3086}
3087
3088impl PartialEq for HydroIrMetadata {
3089    fn eq(&self, _: &Self) -> bool {
3090        true
3091    }
3092}
3093
3094impl Eq for HydroIrMetadata {}
3095
3096impl Debug for HydroIrMetadata {
3097    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3098        f.debug_struct("HydroIrMetadata")
3099            .field("location_id", &self.location_id)
3100            .field("collection_kind", &self.collection_kind)
3101            .finish()
3102    }
3103}
3104
3105/// Metadata that is specific to the operator itself, rather than its outputs.
3106/// This is available on _both_ inner nodes and roots.
3107#[derive(Clone, serde::Serialize)]
3108pub struct HydroIrOpMetadata {
3109    #[serde(rename = "span", serialize_with = "serialize_backtrace_as_span")]
3110    pub backtrace: Backtrace,
3111    pub cpu_usage: Option<f64>,
3112    pub network_recv_cpu_usage: Option<f64>,
3113    pub id: Option<usize>,
3114    /// When set, this unsafe operator (e.g. `batch` / `snapshot`) is bound to a simulator
3115    /// hook handle with this ID, letting simulation tests script its decisions. Ignored by
3116    /// non-simulator backends.
3117    #[serde(skip)]
3118    pub sim_hook_id: Option<usize>,
3119}
3120
3121impl HydroIrOpMetadata {
3122    #[expect(
3123        clippy::new_without_default,
3124        reason = "explicit calls to new ensure correct backtrace bounds"
3125    )]
3126    pub fn new() -> HydroIrOpMetadata {
3127        Self::new_with_skip(1)
3128    }
3129
3130    fn new_with_skip(skip_count: usize) -> HydroIrOpMetadata {
3131        HydroIrOpMetadata {
3132            backtrace: Backtrace::get_backtrace(2 + skip_count),
3133            cpu_usage: None,
3134            network_recv_cpu_usage: None,
3135            id: None,
3136            sim_hook_id: None,
3137        }
3138    }
3139}
3140
3141impl Debug for HydroIrOpMetadata {
3142    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3143        f.debug_struct("HydroIrOpMetadata").finish()
3144    }
3145}
3146
3147impl Hash for HydroIrOpMetadata {
3148    fn hash<H: Hasher>(&self, _: &mut H) {}
3149}
3150
3151/// How a network channel's *sender* prepares each message before it is handed to the transport.
3152///
3153/// A channel's serialization is split into a send half ([`NetworkSend`]) and a receive half
3154/// ([`NetworkRecv`]) so that the multi-version simulation merge can reason about each side
3155/// independently (the sender fork and the receiver are separate IR nodes).
3156#[derive(Debug, Clone, Hash, serde::Serialize)]
3157pub enum NetworkSend {
3158    /// Serialization is performed within the Hydro dataflow using the provided serialize
3159    /// expression. This is how channels using [`crate::networking::Bincode`] are lowered.
3160    Custom { serialize_fn: Option<DebugExpr> },
3161    /// Serialization is left to code outside of Hydro (see [`crate::networking::Embedded`]). The
3162    /// raw `element_type` is passed through unserialized. When demuxing, the destination
3163    /// [`crate::location::MemberId`] is unwrapped to its `Id`, because the host's transport routes
3164    /// by plain IDs. Only supported by the embedded backend.
3165    ///
3166    /// Stored as structured info (rather than a pre-baked expression) so that the code can be
3167    /// synthesized in a post-IR codegen pass.
3168    Embedded {
3169        tag: Option<DebugType>,
3170        element_type: DebugType,
3171    },
3172}
3173
3174/// How a network channel's *receiver* recovers each message from the transport. See
3175/// [`NetworkSend`] for the sender half.
3176#[derive(Debug, Clone, Hash, serde::Serialize)]
3177pub enum NetworkRecv {
3178    /// Deserialization is performed within the Hydro dataflow using the provided deserialize
3179    /// expression. This is how channels using [`crate::networking::Bincode`] are lowered.
3180    Custom { deserialize_fn: Option<DebugExpr> },
3181    /// Deserialization is left to code outside of Hydro (see [`crate::networking::Embedded`]). The
3182    /// raw `element_type` is delivered to the receiver directly, with no transport `Result` to
3183    /// unwrap (the external code that produces the stream decides how to handle faults). When the
3184    /// receiver is keyed by sender, the host's plain sender ID is wrapped in a
3185    /// [`crate::location::MemberId`] again. The wrapper records the sender's cluster, so the
3186    /// dataflow cannot mistake it for a member of another cluster. Only supported by the embedded
3187    /// backend.
3188    Embedded {
3189        tag: Option<DebugType>,
3190        element_type: DebugType,
3191    },
3192}
3193
3194#[cfg(feature = "build")]
3195impl NetworkSend {
3196    /// The raw payload type flowing across the channel when serialization is left to external code,
3197    /// or [`None`] when the channel serializes internally.
3198    pub(crate) fn external_element_type(&self) -> Option<&syn::Type> {
3199        match self {
3200            NetworkSend::Custom { .. } => None,
3201            NetworkSend::Embedded { element_type, .. } => Some(&element_type.0),
3202        }
3203    }
3204}
3205
3206#[cfg(feature = "build")]
3207impl NetworkRecv {
3208    /// See [`NetworkSend::external_element_type`].
3209    pub(crate) fn external_element_type(&self) -> Option<&syn::Type> {
3210        match self {
3211            NetworkRecv::Custom { .. } => None,
3212            NetworkRecv::Embedded { element_type, .. } => Some(&element_type.0),
3213        }
3214    }
3215}
3216
3217#[cfg(feature = "build")]
3218impl NetworkSend {
3219    /// The expression applied on the sender to prepare each message for the transport, if any.
3220    pub(crate) fn pipeline(&self) -> Option<DebugExpr> {
3221        match self {
3222            NetworkSend::Custom { serialize_fn } => serialize_fn.clone(),
3223            NetworkSend::Embedded { tag, element_type } => {
3224                let root = crate::staging_util::get_this_crate();
3225                let element_type = &element_type.0;
3226                let expr: syn::Expr = if let Some(tag) = tag {
3227                    let tag = &tag.0;
3228                    parse_quote! {
3229                        #root::runtime_support::stageleft::runtime_support::fn1_type_hint::<(#root::__staged::location::MemberId<#tag, _>, #element_type), _>(
3230                            |(id, data)| (id.into_tagless(), data)
3231                        )
3232                    }
3233                } else {
3234                    parse_quote! {
3235                        #root::runtime_support::stageleft::runtime_support::fn1_type_hint::<#element_type, _>(
3236                            |data| data
3237                        )
3238                    }
3239                };
3240                Some(expr.into())
3241            }
3242        }
3243    }
3244}
3245
3246#[cfg(feature = "build")]
3247impl NetworkRecv {
3248    /// The expression applied on the receiver to recover each message from the transport, if any.
3249    pub(crate) fn pipeline(&self) -> Option<DebugExpr> {
3250        match self {
3251            NetworkRecv::Custom { deserialize_fn } => deserialize_fn.clone(),
3252            // Embedded channels hand the raw payload to the receiver directly (no transport
3253            // `Result`), so the developer's external code decides how to handle serialization
3254            // faults. The only transformation is restoring the typed `MemberId` when the receiver
3255            // is keyed by the sender.
3256            NetworkRecv::Embedded { tag, .. } => {
3257                let tag = tag.as_ref()?;
3258                let root = crate::staging_util::get_this_crate();
3259                let tag = &tag.0;
3260                let expr: syn::Expr = parse_quote! {
3261                    |(id, b)| (#root::__staged::location::MemberId::<#tag, _>::from_tagless(id), b)
3262                };
3263                Some(expr.into())
3264            }
3265        }
3266    }
3267}
3268
3269/// An intermediate node in a Hydro graph, which consumes data
3270/// from upstream nodes and emits data to downstream nodes.
3271#[derive(Debug, Hash, serde::Serialize)]
3272pub enum HydroNode {
3273    Placeholder,
3274
3275    /// Manually "casts" between two different collection kinds.
3276    ///
3277    /// Using this IR node requires special care, since it bypasses many of Hydro's core
3278    /// correctness checks. In particular, the user must ensure that every possible
3279    /// "interpretation" of the input corresponds to a distinct "interpretation" of the output,
3280    /// where an "interpretation" is a possible output of `ObserveNonDet` applied to the
3281    /// collection. This ensures that the simulator does not miss any possible outputs.
3282    Cast {
3283        inner: Box<HydroNode>,
3284        metadata: HydroIrMetadata,
3285    },
3286
3287    /// Exposes the top-level update feed of a singleton-like collection (a [`Singleton`],
3288    /// [`Optional`], or [`KeyedSingleton`](crate::live_collections::KeyedSingleton) at a root
3289    /// location) as a stream-like collection whose elements are exactly the feed's updates.
3290    ///
3291    /// The updates use the input's top-level representation (see
3292    /// [`CollectionKind::root_repr_is_tombstoned_update_feed`]): plain values, or `Option`
3293    /// updates where `None` is a tombstone. In both production and simulation this is an
3294    /// identity on the generated dataflow.
3295    ///
3296    /// Unlike [`HydroNode::Cast`], this is *not* deterministic: which versions of the
3297    /// collection appear in its update feed depends on timing. Relative to "every version,
3298    /// exactly once", the feed may *stutter* (repeat the current version, consecutively per
3299    /// key) and *skip* (omit non-final versions). Consumers must therefore be invariant to
3300    /// stuttering and skipping, which each use justifies with a `nondet!`.
3301    ///
3302    /// # Soundness with the simulator
3303    ///
3304    /// The simulator does **not** explore the space of possible update streams: it always
3305    /// emits every version exactly once. A real execution may skip intermediate versions that a
3306    /// simulated one never skips. The simulator still covers every production behavior only
3307    /// because of how this node is consumed. Every use (all of them internal to Hydro; this must
3308    /// never be exposed to user code) must uphold the following.
3309    ///
3310    /// - **Never expose the updates themselves.** The update stream, or anything derived from it
3311    ///   update-by-update, must not reach user code or an output. Otherwise a simulated run
3312    ///   would show every intermediate version, while production may skip some of them, so a
3313    ///   test passing in simulation would say nothing about the executions that skip.
3314    /// - **Preserve the whole trajectory up to a nondeterministic choice.** Before anything
3315    ///   observable happens, the updates must flow into logic that keeps the full trajectory of
3316    ///   versions available, and then through a simulator hook that nondeterministically picks
3317    ///   among them. The hook is what explores the skips and stutters, so the logic in between
3318    ///   must not deterministically drop versions that production could observe. Sound patterns:
3319    ///   - fold the updates back into a singleton-like "latest" state (the root `fold` / `scan`
3320    ///     lowerings, `into_singleton`, `key_count`). Its consumers snapshot it, and the
3321    ///     snapshot hook picks any version from the trajectory;
3322    ///   - batch the updates into a tick (`or` / `zip`, thresholds, `sample_eager`). The batch
3323    ///     hook explores every way the versions can be grouped into firings, i.e. which
3324    ///     versions are combined with which and which are skipped.
3325    /// - **Explore interleavings, not just versions.** When several feeds are combined (e.g.
3326    ///   `or` / `zip`), production can pair any version of one side with any version of the
3327    ///   other, depending on timing. Combining the feeds with a deterministic interleaving
3328    ///   (`chain`, a merge, or a stateful operator applied to the merged updates) would simulate
3329    ///   only one of those pairings. Sound uses batch *each* feed into the same tick, so the batch
3330    ///   hooks explore every relative grouping of the sides' versions, and then combine the
3331    ///   per-firing latest values.
3332    /// - **A derived feed must stay within the simulated trajectory.** When the updates are
3333    ///   folded into a new singleton-like collection (which is itself an update feed), every
3334    ///   version production can produce must also appear in the simulated trajectory, so that
3335    ///   the downstream hooks can still reach it.
3336    ///
3337    /// Within those rules, each use must still justify in its `nondet!` that it is invariant
3338    /// to stuttering and skipping, since the simulator does not check that either.
3339    ///
3340    /// [`Singleton`]: crate::live_collections::Singleton
3341    /// [`Optional`]: crate::live_collections::Optional
3342    CastUpdateStream {
3343        inner: Box<HydroNode>,
3344        metadata: HydroIrMetadata,
3345    },
3346
3347    /// Strengthens the guarantees of a stream by non-deterministically selecting a possible
3348    /// interpretation of the input stream.
3349    ///
3350    /// In production, this simply passes through the input, but in simulation, this operator
3351    /// explicitly selects a randomized interpretation.
3352    ObserveNonDet {
3353        inner: Box<HydroNode>,
3354        trusted: bool, // if true, we do not need to simulate non-determinism
3355        metadata: HydroIrMetadata,
3356    },
3357
3358    Source {
3359        source: HydroSource,
3360        metadata: HydroIrMetadata,
3361    },
3362
3363    SingletonSource {
3364        value: DebugExpr,
3365        first_tick_only: bool,
3366        metadata: HydroIrMetadata,
3367    },
3368
3369    CycleSource {
3370        cycle_id: CycleId,
3371        metadata: HydroIrMetadata,
3372    },
3373
3374    Tee {
3375        inner: SharedNode,
3376        metadata: HydroIrMetadata,
3377    },
3378
3379    /// A reference materialization point. Wraps a `SharedNode` so that:
3380    /// - The pipe output delivers data to one consumer
3381    /// - `#var` references can borrow the value from the slot
3382    ///
3383    /// In DFIR codegen, emits `ident = inner_ident -> singleton()` or `-> optional()` or
3384    /// `-> handoff()` depending on `kind`.
3385    ///
3386    /// Uses the same `built_tees` dedup pattern as `Tee`.
3387    Reference {
3388        inner: SharedNode,
3389        kind: crate::handoff_ref::HandoffRefKind,
3390        access_counter: AccessCounter,
3391        metadata: HydroIrMetadata,
3392    },
3393
3394    /// An output side of the partition operator.
3395    PartitionSide {
3396        inner: SharedNode,
3397        is_true: bool,
3398        metadata: HydroIrMetadata,
3399    },
3400
3401    /// The inner input of partitioning, shared between two `PartitionSide`.
3402    PartitionShared {
3403        input: Box<HydroNode>,
3404        f: ClosureExpr,
3405        metadata: HydroIrMetadata,
3406    },
3407
3408    BeginAtomic {
3409        inner: Box<HydroNode>,
3410        metadata: HydroIrMetadata,
3411    },
3412
3413    EndAtomic {
3414        inner: Box<HydroNode>,
3415        metadata: HydroIrMetadata,
3416    },
3417
3418    /// Windows a stream-like collection (a stream, a keyed stream, or a keyed singleton whose
3419    /// per-key values are bounded) into a tick. Each firing of the tick observes a *batch* of
3420    /// the elements (or finalized entries) that have arrived since the previous batch, and
3421    /// never sees an element twice.
3422    ///
3423    /// The simulator fuzzes how the arriving elements are split into batches.
3424    Batch {
3425        inner: Box<HydroNode>,
3426        metadata: HydroIrMetadata,
3427    },
3428
3429    /// Windows a singleton-like collection (a singleton, an optional, or a keyed singleton
3430    /// whose per-key values may change, as well as a fully bounded keyed singleton) into a
3431    /// tick. Each firing of the tick observes a *snapshot* of the collection's current value,
3432    /// so a value that has not changed since the previous firing is observed again.
3433    ///
3434    /// The simulator fuzzes which of the collection's intermediate states each snapshot
3435    /// observes.
3436    Snapshot {
3437        inner: Box<HydroNode>,
3438        metadata: HydroIrMetadata,
3439    },
3440
3441    YieldConcat {
3442        inner: Box<HydroNode>,
3443        metadata: HydroIrMetadata,
3444    },
3445
3446    Chain {
3447        first: Box<HydroNode>,
3448        second: Box<HydroNode>,
3449        metadata: HydroIrMetadata,
3450    },
3451
3452    MergeOrdered {
3453        first: Box<HydroNode>,
3454        second: Box<HydroNode>,
3455        metadata: HydroIrMetadata,
3456    },
3457
3458    ChainFirst {
3459        first: Box<HydroNode>,
3460        second: Box<HydroNode>,
3461        metadata: HydroIrMetadata,
3462    },
3463
3464    CrossProduct {
3465        left: Box<HydroNode>,
3466        right: Box<HydroNode>,
3467        metadata: HydroIrMetadata,
3468    },
3469
3470    CrossSingleton {
3471        left: Box<HydroNode>,
3472        right: Box<HydroNode>,
3473        metadata: HydroIrMetadata,
3474    },
3475
3476    Join {
3477        left: Box<HydroNode>,
3478        right: Box<HydroNode>,
3479        metadata: HydroIrMetadata,
3480    },
3481
3482    /// Asymmetric join where the right (build) side is bounded.
3483    /// The build side is accumulated (stratum-delayed) into a hash table,
3484    /// then the left (probe) side streams through preserving its ordering.
3485    JoinHalf {
3486        left: Box<HydroNode>,
3487        right: Box<HydroNode>,
3488        metadata: HydroIrMetadata,
3489    },
3490
3491    Difference {
3492        pos: Box<HydroNode>,
3493        neg: Box<HydroNode>,
3494        metadata: HydroIrMetadata,
3495    },
3496
3497    AntiJoin {
3498        pos: Box<HydroNode>,
3499        neg: Box<HydroNode>,
3500        metadata: HydroIrMetadata,
3501    },
3502
3503    ResolveFutures {
3504        input: Box<HydroNode>,
3505        metadata: HydroIrMetadata,
3506    },
3507    ResolveFuturesBlocking {
3508        input: Box<HydroNode>,
3509        metadata: HydroIrMetadata,
3510    },
3511    ResolveFuturesOrdered {
3512        input: Box<HydroNode>,
3513        metadata: HydroIrMetadata,
3514    },
3515
3516    Map {
3517        f: ClosureExpr,
3518        input: Box<HydroNode>,
3519        metadata: HydroIrMetadata,
3520    },
3521    FlatMap {
3522        f: ClosureExpr,
3523        input: Box<HydroNode>,
3524        metadata: HydroIrMetadata,
3525    },
3526    FlatMapStreamBlocking {
3527        f: ClosureExpr,
3528        input: Box<HydroNode>,
3529        metadata: HydroIrMetadata,
3530    },
3531    Filter {
3532        f: ClosureExpr,
3533        input: Box<HydroNode>,
3534        metadata: HydroIrMetadata,
3535    },
3536    FilterMap {
3537        f: ClosureExpr,
3538        input: Box<HydroNode>,
3539        metadata: HydroIrMetadata,
3540    },
3541
3542    DeferTick {
3543        input: Box<HydroNode>,
3544        metadata: HydroIrMetadata,
3545    },
3546    Enumerate {
3547        input: Box<HydroNode>,
3548        metadata: HydroIrMetadata,
3549    },
3550    Inspect {
3551        f: ClosureExpr,
3552        input: Box<HydroNode>,
3553        metadata: HydroIrMetadata,
3554    },
3555
3556    Unique {
3557        input: Box<HydroNode>,
3558        metadata: HydroIrMetadata,
3559    },
3560
3561    Sort {
3562        input: Box<HydroNode>,
3563        metadata: HydroIrMetadata,
3564    },
3565    Fold {
3566        init: ClosureExpr,
3567        acc: ClosureExpr,
3568        input: Box<HydroNode>,
3569        metadata: HydroIrMetadata,
3570    },
3571
3572    Scan {
3573        init: ClosureExpr,
3574        acc: ClosureExpr,
3575        input: Box<HydroNode>,
3576        metadata: HydroIrMetadata,
3577    },
3578    ScanAsyncBlocking {
3579        init: ClosureExpr,
3580        acc: ClosureExpr,
3581        input: Box<HydroNode>,
3582        metadata: HydroIrMetadata,
3583    },
3584    FoldKeyed {
3585        init: ClosureExpr,
3586        acc: ClosureExpr,
3587        input: Box<HydroNode>,
3588        metadata: HydroIrMetadata,
3589    },
3590
3591    Reduce {
3592        f: ClosureExpr,
3593        input: Box<HydroNode>,
3594        metadata: HydroIrMetadata,
3595    },
3596    ReduceKeyed {
3597        f: ClosureExpr,
3598        input: Box<HydroNode>,
3599        metadata: HydroIrMetadata,
3600    },
3601    ReduceKeyedWatermark {
3602        f: ClosureExpr,
3603        input: Box<HydroNode>,
3604        watermark: Box<HydroNode>,
3605        metadata: HydroIrMetadata,
3606    },
3607
3608    Network {
3609        name: Option<String>,
3610        networking_info: crate::networking::NetworkingInfo,
3611        serialize: NetworkSend,
3612        deserialize: NetworkRecv,
3613        instantiate_fn: DebugInstantiate,
3614        input: Box<HydroNode>,
3615        metadata: HydroIrMetadata,
3616    },
3617
3618    VersionedNetworkFork {
3619        channel_id: u32,
3620        channel_name: String,
3621        senders: Vec<(u32, Box<HydroNode>, NetworkSend)>,
3622        metadata: HydroIrMetadata,
3623    },
3624
3625    VersionedNetwork {
3626        fork: SharedNode,
3627        version: u32,
3628        deserialize: NetworkRecv,
3629        metadata: HydroIrMetadata,
3630    },
3631
3632    ExternalInput {
3633        from_external_key: LocationKey,
3634        from_port_id: ExternalPortId,
3635        from_many: bool,
3636        codec_type: DebugType,
3637        /// Item type that `codec_type` encodes for messages sent back to the external client.
3638        /// A codec can implement `Encoder` for several item types (`LengthDelimitedCodec` encodes
3639        /// both `Bytes` and `&[u8]`), so generated code names this type instead of inferring it.
3640        encode_type: DebugType,
3641        #[serde(skip)]
3642        port_hint: NetworkHint,
3643        instantiate_fn: DebugInstantiate,
3644        deserialize_fn: Option<DebugExpr>,
3645        metadata: HydroIrMetadata,
3646    },
3647
3648    Counter {
3649        tag: String,
3650        duration: DebugExpr,
3651        prefix: String,
3652        input: Box<HydroNode>,
3653        metadata: HydroIrMetadata,
3654    },
3655
3656    AssertIsConsistent {
3657        inner: Box<HydroNode>,
3658        trusted: bool,
3659        metadata: HydroIrMetadata,
3660    },
3661
3662    UnboundSingleton {
3663        inner: Box<HydroNode>,
3664        metadata: HydroIrMetadata,
3665    },
3666}
3667
3668pub type SeenSharedNodes = HashMap<*const RefCell<HydroNode>, Rc<RefCell<HydroNode>>>;
3669pub type SeenSharedNodeLocations = HashMap<*const RefCell<HydroNode>, LocationId>;
3670
3671/// The runtime representation of a collection's DFIR pipe at a given node.
3672///
3673/// See [`CollectionKind::root_repr_is_tombstoned_update_feed`]: root-located unbounded
3674/// [`Optional`](CollectionKind::Optional)s and
3675/// [`KeyedSingleton`](CollectionKind::KeyedSingleton)s are represented as feeds of explicit
3676/// update records (`Option<T>` / `(K, Option<V>)`) so that *removal* is representable;
3677/// everything else is a plain feed of values.
3678#[cfg(feature = "build")]
3679#[derive(PartialEq, Eq, Clone, Copy, Debug)]
3680enum UpdateFeedRepr {
3681    /// Plain values (`T` elements / `(K, V)` entries).
3682    Plain,
3683    /// Tombstoned updates (`Option<T>` / `(K, Option<V>)`).
3684    Tombstoned,
3685}
3686
3687#[cfg(feature = "build")]
3688fn update_feed_repr(metadata: &HydroIrMetadata) -> UpdateFeedRepr {
3689    if metadata.location_id.is_root()
3690        && metadata
3691            .collection_kind
3692            .root_repr_is_tombstoned_update_feed()
3693    {
3694        UpdateFeedRepr::Tombstoned
3695    } else {
3696        UpdateFeedRepr::Plain
3697    }
3698}
3699
3700/// If `f` has a mut singleton ref and `in_kind` is non-strict, emits an
3701/// `observe_for_mut` node and returns the new ident. Otherwise returns
3702/// `in_ident` unchanged. Always consumes a `stmt_id` when applicable.
3703#[cfg(feature = "build")]
3704fn maybe_observe_for_mut(
3705    f: &ClosureExpr,
3706    in_ident: syn::Ident,
3707    in_location: &LocationId,
3708    in_kind: &CollectionKind,
3709    op_meta: &HydroIrOpMetadata,
3710    builders_or_callback: &mut BuildersOrCallback<
3711        '_,
3712        impl FnMut(&mut HydroRoot, &mut crate::Counter<StmtId>),
3713        impl FnMut(&mut HydroNode, &mut crate::Counter<StmtId>),
3714    >,
3715    next_stmt_id: &mut crate::Counter<StmtId>,
3716) -> syn::Ident {
3717    if f.has_mut_ref() && !in_kind.is_strict() {
3718        let observe_stmt_id = next_stmt_id.get_and_increment();
3719        let observe_ident =
3720            syn::Ident::new(&format!("stream_{}", observe_stmt_id), Span::call_site());
3721        if let BuildersOrCallback::Builders(graph_builders) = builders_or_callback {
3722            graph_builders.observe_for_mut(in_location, in_ident, in_kind, &observe_ident, op_meta);
3723        }
3724        observe_ident
3725    } else {
3726        in_ident
3727    }
3728}
3729
3730impl HydroNode {
3731    pub fn transform_bottom_up(
3732        &mut self,
3733        transform: &mut impl FnMut(&mut HydroNode),
3734        seen_tees: &mut SeenSharedNodes,
3735        check_well_formed: bool,
3736    ) {
3737        self.transform_children(
3738            |n, s| n.transform_bottom_up(transform, s, check_well_formed),
3739            seen_tees,
3740        );
3741
3742        transform(self);
3743
3744        let self_location = self.metadata().location_id.root();
3745
3746        if check_well_formed {
3747            match &*self {
3748                HydroNode::Network { .. } => {}
3749                _ => {
3750                    self.input_metadata().iter().for_each(|i| {
3751                        assert!(
3752                            i.location_id.root() == self_location,
3753                            "Mismatching IR locations, child: {:?} ({:?}) of: {:?} ({:?})",
3754                            i,
3755                            i.location_id.root(),
3756                            self,
3757                            self_location
3758                        );
3759                    });
3760                }
3761            }
3762        }
3763    }
3764
3765    #[inline(always)]
3766    pub fn transform_children(
3767        &mut self,
3768        mut transform: impl FnMut(&mut HydroNode, &mut SeenSharedNodes),
3769        seen_tees: &mut SeenSharedNodes,
3770    ) {
3771        match self {
3772            HydroNode::Placeholder => {
3773                panic!();
3774            }
3775
3776            HydroNode::Source { .. }
3777            | HydroNode::SingletonSource { .. }
3778            | HydroNode::CycleSource { .. }
3779            | HydroNode::ExternalInput { .. } => {}
3780
3781            HydroNode::Tee { inner, .. } | HydroNode::Reference { inner, .. } => {
3782                if let Some(transformed) = seen_tees.get(&inner.as_ptr()) {
3783                    *inner = SharedNode(transformed.clone());
3784                } else {
3785                    let transformed_cell = Rc::new(RefCell::new(HydroNode::Placeholder));
3786                    seen_tees.insert(inner.as_ptr(), transformed_cell.clone());
3787                    let mut orig = inner.0.replace(HydroNode::Placeholder);
3788                    transform(&mut orig, seen_tees);
3789                    *transformed_cell.borrow_mut() = orig;
3790                    *inner = SharedNode(transformed_cell);
3791                }
3792            }
3793
3794            HydroNode::PartitionSide { inner, .. } => {
3795                if let Some(transformed) = seen_tees.get(&inner.as_ptr()) {
3796                    *inner = SharedNode(transformed.clone());
3797                } else {
3798                    let transformed_cell = Rc::new(RefCell::new(HydroNode::Placeholder));
3799                    seen_tees.insert(inner.as_ptr(), transformed_cell.clone());
3800                    let mut orig: HydroNode = inner.0.replace(HydroNode::Placeholder);
3801                    transform(&mut orig, seen_tees);
3802                    *transformed_cell.borrow_mut() = orig;
3803                    *inner = SharedNode(transformed_cell);
3804                }
3805            }
3806            HydroNode::PartitionShared { input, f, .. } => {
3807                f.transform_children(&mut transform, seen_tees);
3808                transform(input.as_mut(), seen_tees);
3809            }
3810
3811            HydroNode::Cast { inner, .. }
3812            | HydroNode::CastUpdateStream { inner, .. }
3813            | HydroNode::ObserveNonDet { inner, .. }
3814            | HydroNode::BeginAtomic { inner, .. }
3815            | HydroNode::EndAtomic { inner, .. }
3816            | HydroNode::Batch { inner, .. }
3817            | HydroNode::Snapshot { inner, .. }
3818            | HydroNode::YieldConcat { inner, .. }
3819            | HydroNode::UnboundSingleton { inner, .. }
3820            | HydroNode::AssertIsConsistent { inner, .. } => {
3821                transform(inner.as_mut(), seen_tees);
3822            }
3823
3824            HydroNode::Chain { first, second, .. } => {
3825                transform(first.as_mut(), seen_tees);
3826                transform(second.as_mut(), seen_tees);
3827            }
3828
3829            HydroNode::MergeOrdered { first, second, .. } => {
3830                transform(first.as_mut(), seen_tees);
3831                transform(second.as_mut(), seen_tees);
3832            }
3833
3834            HydroNode::ChainFirst { first, second, .. } => {
3835                transform(first.as_mut(), seen_tees);
3836                transform(second.as_mut(), seen_tees);
3837            }
3838
3839            HydroNode::CrossSingleton { left, right, .. }
3840            | HydroNode::CrossProduct { left, right, .. }
3841            | HydroNode::Join { left, right, .. }
3842            | HydroNode::JoinHalf { left, right, .. } => {
3843                transform(left.as_mut(), seen_tees);
3844                transform(right.as_mut(), seen_tees);
3845            }
3846
3847            HydroNode::Difference { pos, neg, .. } | HydroNode::AntiJoin { pos, neg, .. } => {
3848                transform(pos.as_mut(), seen_tees);
3849                transform(neg.as_mut(), seen_tees);
3850            }
3851
3852            HydroNode::Map { f, input, .. } => {
3853                f.transform_children(&mut transform, seen_tees);
3854                transform(input.as_mut(), seen_tees);
3855            }
3856            HydroNode::FlatMap { f, input, .. }
3857            | HydroNode::FlatMapStreamBlocking { f, input, .. }
3858            | HydroNode::Filter { f, input, .. }
3859            | HydroNode::FilterMap { f, input, .. }
3860            | HydroNode::Inspect { f, input, .. }
3861            | HydroNode::Reduce { f, input, .. }
3862            | HydroNode::ReduceKeyed { f, input, .. } => {
3863                f.transform_children(&mut transform, seen_tees);
3864                transform(input.as_mut(), seen_tees);
3865            }
3866            HydroNode::ReduceKeyedWatermark {
3867                f,
3868                input,
3869                watermark,
3870                ..
3871            } => {
3872                f.transform_children(&mut transform, seen_tees);
3873                transform(input.as_mut(), seen_tees);
3874                transform(watermark.as_mut(), seen_tees);
3875            }
3876            HydroNode::Fold {
3877                init, acc, input, ..
3878            }
3879            | HydroNode::Scan {
3880                init, acc, input, ..
3881            }
3882            | HydroNode::ScanAsyncBlocking {
3883                init, acc, input, ..
3884            }
3885            | HydroNode::FoldKeyed {
3886                init, acc, input, ..
3887            } => {
3888                init.transform_children(&mut transform, seen_tees);
3889                acc.transform_children(&mut transform, seen_tees);
3890                transform(input.as_mut(), seen_tees);
3891            }
3892            HydroNode::ResolveFutures { input, .. }
3893            | HydroNode::ResolveFuturesBlocking { input, .. }
3894            | HydroNode::ResolveFuturesOrdered { input, .. }
3895            | HydroNode::Sort { input, .. }
3896            | HydroNode::DeferTick { input, .. }
3897            | HydroNode::Enumerate { input, .. }
3898            | HydroNode::Unique { input, .. }
3899            | HydroNode::Network { input, .. }
3900            | HydroNode::Counter { input, .. } => {
3901                transform(input.as_mut(), seen_tees);
3902            }
3903
3904            HydroNode::VersionedNetworkFork { senders, .. } => {
3905                for (_version, sender, _serialize) in senders.iter_mut() {
3906                    transform(sender.as_mut(), seen_tees);
3907                }
3908            }
3909
3910            HydroNode::VersionedNetwork { fork, .. } => {
3911                if let Some(transformed) = seen_tees.get(&fork.as_ptr()) {
3912                    *fork = SharedNode(transformed.clone());
3913                } else {
3914                    let transformed_cell = Rc::new(RefCell::new(HydroNode::Placeholder));
3915                    seen_tees.insert(fork.as_ptr(), transformed_cell.clone());
3916                    let mut orig = fork.0.replace(HydroNode::Placeholder);
3917                    transform(&mut orig, seen_tees);
3918                    *transformed_cell.borrow_mut() = orig;
3919                    *fork = SharedNode(transformed_cell);
3920                }
3921            }
3922        }
3923    }
3924
3925    pub fn deep_clone(&self, seen_tees: &mut SeenSharedNodes) -> HydroNode {
3926        match self {
3927            HydroNode::Placeholder => HydroNode::Placeholder,
3928            HydroNode::Cast { inner, metadata } => HydroNode::Cast {
3929                inner: Box::new(inner.deep_clone(seen_tees)),
3930                metadata: metadata.clone(),
3931            },
3932            HydroNode::CastUpdateStream { inner, metadata } => HydroNode::CastUpdateStream {
3933                inner: Box::new(inner.deep_clone(seen_tees)),
3934                metadata: metadata.clone(),
3935            },
3936            HydroNode::UnboundSingleton { inner, metadata } => HydroNode::UnboundSingleton {
3937                inner: Box::new(inner.deep_clone(seen_tees)),
3938                metadata: metadata.clone(),
3939            },
3940            HydroNode::ObserveNonDet {
3941                inner,
3942                trusted,
3943                metadata,
3944            } => HydroNode::ObserveNonDet {
3945                inner: Box::new(inner.deep_clone(seen_tees)),
3946                trusted: *trusted,
3947                metadata: metadata.clone(),
3948            },
3949            HydroNode::AssertIsConsistent {
3950                inner,
3951                trusted,
3952                metadata,
3953            } => HydroNode::AssertIsConsistent {
3954                inner: Box::new(inner.deep_clone(seen_tees)),
3955                trusted: *trusted,
3956                metadata: metadata.clone(),
3957            },
3958            HydroNode::Source { source, metadata } => HydroNode::Source {
3959                source: source.clone(),
3960                metadata: metadata.clone(),
3961            },
3962            HydroNode::SingletonSource {
3963                value,
3964                first_tick_only,
3965                metadata,
3966            } => HydroNode::SingletonSource {
3967                value: value.clone(),
3968                first_tick_only: *first_tick_only,
3969                metadata: metadata.clone(),
3970            },
3971            HydroNode::CycleSource { cycle_id, metadata } => HydroNode::CycleSource {
3972                cycle_id: *cycle_id,
3973                metadata: metadata.clone(),
3974            },
3975            HydroNode::Tee { inner, metadata }
3976            | HydroNode::Reference {
3977                inner, metadata, ..
3978            } => {
3979                let cloned_inner = if let Some(transformed) = seen_tees.get(&inner.as_ptr()) {
3980                    SharedNode(transformed.clone())
3981                } else {
3982                    let new_rc = Rc::new(RefCell::new(HydroNode::Placeholder));
3983                    seen_tees.insert(inner.as_ptr(), new_rc.clone());
3984                    let cloned = inner.0.borrow().deep_clone(seen_tees);
3985                    *new_rc.borrow_mut() = cloned;
3986                    SharedNode(new_rc)
3987                };
3988                if let HydroNode::Reference {
3989                    kind,
3990                    access_counter,
3991                    ..
3992                } = self
3993                {
3994                    HydroNode::Reference {
3995                        inner: cloned_inner,
3996                        kind: *kind,
3997                        access_counter: access_counter.freeze(),
3998                        metadata: metadata.clone(),
3999                    }
4000                } else {
4001                    HydroNode::Tee {
4002                        inner: cloned_inner,
4003                        metadata: metadata.clone(),
4004                    }
4005                }
4006            }
4007            HydroNode::PartitionSide {
4008                inner,
4009                is_true,
4010                metadata,
4011            } => {
4012                if let Some(transformed) = seen_tees.get(&inner.as_ptr()) {
4013                    HydroNode::PartitionSide {
4014                        inner: SharedNode(transformed.clone()),
4015                        is_true: *is_true,
4016                        metadata: metadata.clone(),
4017                    }
4018                } else {
4019                    let new_rc = Rc::new(RefCell::new(HydroNode::Placeholder));
4020                    seen_tees.insert(inner.as_ptr(), new_rc.clone());
4021                    let cloned = inner.0.borrow().deep_clone(seen_tees);
4022                    *new_rc.borrow_mut() = cloned;
4023                    HydroNode::PartitionSide {
4024                        inner: SharedNode(new_rc),
4025                        is_true: *is_true,
4026                        metadata: metadata.clone(),
4027                    }
4028                }
4029            }
4030            HydroNode::PartitionShared { input, f, metadata } => HydroNode::PartitionShared {
4031                input: Box::new(input.deep_clone(seen_tees)),
4032                f: f.deep_clone(seen_tees),
4033                metadata: metadata.clone(),
4034            },
4035            HydroNode::YieldConcat { inner, metadata } => HydroNode::YieldConcat {
4036                inner: Box::new(inner.deep_clone(seen_tees)),
4037                metadata: metadata.clone(),
4038            },
4039            HydroNode::BeginAtomic { inner, metadata } => HydroNode::BeginAtomic {
4040                inner: Box::new(inner.deep_clone(seen_tees)),
4041                metadata: metadata.clone(),
4042            },
4043            HydroNode::EndAtomic { inner, metadata } => HydroNode::EndAtomic {
4044                inner: Box::new(inner.deep_clone(seen_tees)),
4045                metadata: metadata.clone(),
4046            },
4047            HydroNode::Batch { inner, metadata } => HydroNode::Batch {
4048                inner: Box::new(inner.deep_clone(seen_tees)),
4049                metadata: metadata.clone(),
4050            },
4051            HydroNode::Snapshot { inner, metadata } => HydroNode::Snapshot {
4052                inner: Box::new(inner.deep_clone(seen_tees)),
4053                metadata: metadata.clone(),
4054            },
4055            HydroNode::Chain {
4056                first,
4057                second,
4058                metadata,
4059            } => HydroNode::Chain {
4060                first: Box::new(first.deep_clone(seen_tees)),
4061                second: Box::new(second.deep_clone(seen_tees)),
4062                metadata: metadata.clone(),
4063            },
4064            HydroNode::MergeOrdered {
4065                first,
4066                second,
4067                metadata,
4068            } => HydroNode::MergeOrdered {
4069                first: Box::new(first.deep_clone(seen_tees)),
4070                second: Box::new(second.deep_clone(seen_tees)),
4071                metadata: metadata.clone(),
4072            },
4073            HydroNode::ChainFirst {
4074                first,
4075                second,
4076                metadata,
4077            } => HydroNode::ChainFirst {
4078                first: Box::new(first.deep_clone(seen_tees)),
4079                second: Box::new(second.deep_clone(seen_tees)),
4080                metadata: metadata.clone(),
4081            },
4082            HydroNode::CrossProduct {
4083                left,
4084                right,
4085                metadata,
4086            } => HydroNode::CrossProduct {
4087                left: Box::new(left.deep_clone(seen_tees)),
4088                right: Box::new(right.deep_clone(seen_tees)),
4089                metadata: metadata.clone(),
4090            },
4091            HydroNode::CrossSingleton {
4092                left,
4093                right,
4094                metadata,
4095            } => HydroNode::CrossSingleton {
4096                left: Box::new(left.deep_clone(seen_tees)),
4097                right: Box::new(right.deep_clone(seen_tees)),
4098                metadata: metadata.clone(),
4099            },
4100            HydroNode::Join {
4101                left,
4102                right,
4103                metadata,
4104            } => HydroNode::Join {
4105                left: Box::new(left.deep_clone(seen_tees)),
4106                right: Box::new(right.deep_clone(seen_tees)),
4107                metadata: metadata.clone(),
4108            },
4109            HydroNode::JoinHalf {
4110                left,
4111                right,
4112                metadata,
4113            } => HydroNode::JoinHalf {
4114                left: Box::new(left.deep_clone(seen_tees)),
4115                right: Box::new(right.deep_clone(seen_tees)),
4116                metadata: metadata.clone(),
4117            },
4118            HydroNode::Difference { pos, neg, metadata } => HydroNode::Difference {
4119                pos: Box::new(pos.deep_clone(seen_tees)),
4120                neg: Box::new(neg.deep_clone(seen_tees)),
4121                metadata: metadata.clone(),
4122            },
4123            HydroNode::AntiJoin { pos, neg, metadata } => HydroNode::AntiJoin {
4124                pos: Box::new(pos.deep_clone(seen_tees)),
4125                neg: Box::new(neg.deep_clone(seen_tees)),
4126                metadata: metadata.clone(),
4127            },
4128            HydroNode::ResolveFutures { input, metadata } => HydroNode::ResolveFutures {
4129                input: Box::new(input.deep_clone(seen_tees)),
4130                metadata: metadata.clone(),
4131            },
4132            HydroNode::ResolveFuturesBlocking { input, metadata } => {
4133                HydroNode::ResolveFuturesBlocking {
4134                    input: Box::new(input.deep_clone(seen_tees)),
4135                    metadata: metadata.clone(),
4136                }
4137            }
4138            HydroNode::ResolveFuturesOrdered { input, metadata } => {
4139                HydroNode::ResolveFuturesOrdered {
4140                    input: Box::new(input.deep_clone(seen_tees)),
4141                    metadata: metadata.clone(),
4142                }
4143            }
4144            HydroNode::Map { f, input, metadata } => HydroNode::Map {
4145                f: f.deep_clone(seen_tees),
4146                input: Box::new(input.deep_clone(seen_tees)),
4147                metadata: metadata.clone(),
4148            },
4149            HydroNode::FlatMap { f, input, metadata } => HydroNode::FlatMap {
4150                f: f.deep_clone(seen_tees),
4151                input: Box::new(input.deep_clone(seen_tees)),
4152                metadata: metadata.clone(),
4153            },
4154            HydroNode::FlatMapStreamBlocking { f, input, metadata } => {
4155                HydroNode::FlatMapStreamBlocking {
4156                    f: f.deep_clone(seen_tees),
4157                    input: Box::new(input.deep_clone(seen_tees)),
4158                    metadata: metadata.clone(),
4159                }
4160            }
4161            HydroNode::Filter { f, input, metadata } => HydroNode::Filter {
4162                f: f.deep_clone(seen_tees),
4163                input: Box::new(input.deep_clone(seen_tees)),
4164                metadata: metadata.clone(),
4165            },
4166            HydroNode::FilterMap { f, input, metadata } => HydroNode::FilterMap {
4167                f: f.deep_clone(seen_tees),
4168                input: Box::new(input.deep_clone(seen_tees)),
4169                metadata: metadata.clone(),
4170            },
4171            HydroNode::DeferTick { input, metadata } => HydroNode::DeferTick {
4172                input: Box::new(input.deep_clone(seen_tees)),
4173                metadata: metadata.clone(),
4174            },
4175            HydroNode::Enumerate { input, metadata } => HydroNode::Enumerate {
4176                input: Box::new(input.deep_clone(seen_tees)),
4177                metadata: metadata.clone(),
4178            },
4179            HydroNode::Inspect { f, input, metadata } => HydroNode::Inspect {
4180                f: f.deep_clone(seen_tees),
4181                input: Box::new(input.deep_clone(seen_tees)),
4182                metadata: metadata.clone(),
4183            },
4184            HydroNode::Unique { input, metadata } => HydroNode::Unique {
4185                input: Box::new(input.deep_clone(seen_tees)),
4186                metadata: metadata.clone(),
4187            },
4188            HydroNode::Sort { input, metadata } => HydroNode::Sort {
4189                input: Box::new(input.deep_clone(seen_tees)),
4190                metadata: metadata.clone(),
4191            },
4192            HydroNode::Fold {
4193                init,
4194                acc,
4195                input,
4196                metadata,
4197            } => HydroNode::Fold {
4198                init: init.deep_clone(seen_tees),
4199                acc: acc.deep_clone(seen_tees),
4200                input: Box::new(input.deep_clone(seen_tees)),
4201                metadata: metadata.clone(),
4202            },
4203            HydroNode::Scan {
4204                init,
4205                acc,
4206                input,
4207                metadata,
4208            } => HydroNode::Scan {
4209                init: init.deep_clone(seen_tees),
4210                acc: acc.deep_clone(seen_tees),
4211                input: Box::new(input.deep_clone(seen_tees)),
4212                metadata: metadata.clone(),
4213            },
4214            HydroNode::ScanAsyncBlocking {
4215                init,
4216                acc,
4217                input,
4218                metadata,
4219            } => HydroNode::ScanAsyncBlocking {
4220                init: init.deep_clone(seen_tees),
4221                acc: acc.deep_clone(seen_tees),
4222                input: Box::new(input.deep_clone(seen_tees)),
4223                metadata: metadata.clone(),
4224            },
4225            HydroNode::FoldKeyed {
4226                init,
4227                acc,
4228                input,
4229                metadata,
4230            } => HydroNode::FoldKeyed {
4231                init: init.deep_clone(seen_tees),
4232                acc: acc.deep_clone(seen_tees),
4233                input: Box::new(input.deep_clone(seen_tees)),
4234                metadata: metadata.clone(),
4235            },
4236            HydroNode::ReduceKeyedWatermark {
4237                f,
4238                input,
4239                watermark,
4240                metadata,
4241            } => HydroNode::ReduceKeyedWatermark {
4242                f: f.deep_clone(seen_tees),
4243                input: Box::new(input.deep_clone(seen_tees)),
4244                watermark: Box::new(watermark.deep_clone(seen_tees)),
4245                metadata: metadata.clone(),
4246            },
4247            HydroNode::Reduce { f, input, metadata } => HydroNode::Reduce {
4248                f: f.deep_clone(seen_tees),
4249                input: Box::new(input.deep_clone(seen_tees)),
4250                metadata: metadata.clone(),
4251            },
4252            HydroNode::ReduceKeyed { f, input, metadata } => HydroNode::ReduceKeyed {
4253                f: f.deep_clone(seen_tees),
4254                input: Box::new(input.deep_clone(seen_tees)),
4255                metadata: metadata.clone(),
4256            },
4257            HydroNode::Network {
4258                name,
4259                networking_info,
4260                serialize,
4261                deserialize,
4262                instantiate_fn,
4263                input,
4264                metadata,
4265            } => HydroNode::Network {
4266                name: name.clone(),
4267                networking_info: networking_info.clone(),
4268                serialize: serialize.clone(),
4269                deserialize: deserialize.clone(),
4270                instantiate_fn: instantiate_fn.clone(),
4271                input: Box::new(input.deep_clone(seen_tees)),
4272                metadata: metadata.clone(),
4273            },
4274            HydroNode::ExternalInput {
4275                from_external_key,
4276                from_port_id,
4277                from_many,
4278                codec_type,
4279                encode_type,
4280                port_hint,
4281                instantiate_fn,
4282                deserialize_fn,
4283                metadata,
4284            } => HydroNode::ExternalInput {
4285                from_external_key: *from_external_key,
4286                from_port_id: *from_port_id,
4287                from_many: *from_many,
4288                codec_type: codec_type.clone(),
4289                encode_type: encode_type.clone(),
4290                port_hint: *port_hint,
4291                instantiate_fn: instantiate_fn.clone(),
4292                deserialize_fn: deserialize_fn.clone(),
4293                metadata: metadata.clone(),
4294            },
4295            HydroNode::Counter {
4296                tag,
4297                duration,
4298                prefix,
4299                input,
4300                metadata,
4301            } => HydroNode::Counter {
4302                tag: tag.clone(),
4303                duration: duration.clone(),
4304                prefix: prefix.clone(),
4305                input: Box::new(input.deep_clone(seen_tees)),
4306                metadata: metadata.clone(),
4307            },
4308            HydroNode::VersionedNetworkFork {
4309                channel_id,
4310                channel_name,
4311                senders,
4312                metadata,
4313            } => HydroNode::VersionedNetworkFork {
4314                channel_id: *channel_id,
4315                channel_name: channel_name.clone(),
4316                senders: senders
4317                    .iter()
4318                    .map(|(version, sender, serialize)| {
4319                        (
4320                            *version,
4321                            Box::new(sender.deep_clone(seen_tees)),
4322                            serialize.clone(),
4323                        )
4324                    })
4325                    .collect(),
4326                metadata: metadata.clone(),
4327            },
4328            HydroNode::VersionedNetwork {
4329                fork,
4330                version,
4331                deserialize,
4332                metadata,
4333            } => {
4334                let cloned_fork = if let Some(transformed) = seen_tees.get(&fork.as_ptr()) {
4335                    SharedNode(transformed.clone())
4336                } else {
4337                    let new_rc = Rc::new(RefCell::new(HydroNode::Placeholder));
4338                    seen_tees.insert(fork.as_ptr(), new_rc.clone());
4339                    let cloned = fork.0.borrow().deep_clone(seen_tees);
4340                    *new_rc.borrow_mut() = cloned;
4341                    SharedNode(new_rc)
4342                };
4343                HydroNode::VersionedNetwork {
4344                    fork: cloned_fork,
4345                    version: *version,
4346                    deserialize: deserialize.clone(),
4347                    metadata: metadata.clone(),
4348                }
4349            }
4350        }
4351    }
4352
4353    #[cfg(feature = "build")]
4354    pub fn emit_core(
4355        &mut self,
4356        builders_or_callback: &mut BuildersOrCallback<
4357            '_,
4358            impl FnMut(&mut HydroRoot, &mut crate::Counter<StmtId>),
4359            impl FnMut(&mut HydroNode, &mut crate::Counter<StmtId>),
4360        >,
4361        seen_tees: &mut SeenSharedNodes,
4362        built_tees: &mut HashMap<*const RefCell<HydroNode>, Vec<syn::Ident>>,
4363        next_stmt_id: &mut crate::Counter<StmtId>,
4364        fold_hooked_idents: &mut HashSet<String>,
4365    ) -> syn::Ident {
4366        let mut ident_stack: Vec<syn::Ident> = Vec::new();
4367
4368        self.transform_bottom_up(
4369            &mut |node: &mut HydroNode| {
4370                let out_location = node.metadata().location_id.clone();
4371                match node {
4372                    HydroNode::Placeholder => {
4373                        panic!()
4374                    }
4375
4376                    HydroNode::CastUpdateStream { inner, metadata } => {
4377                        // The input's top-level update feed *is* the output stream: identity.
4378                        // The input ident is already on the stack from processing the child.
4379                        debug_assert!(
4380                            inner.metadata().location_id.is_root(),
4381                            "CastUpdateStream requires a root-located input, got {:?}",
4382                            inner.metadata().location_id
4383                        );
4384                        // The cast only changes the collection type, so the shapes must align:
4385                        // a singleton / optional's feed is a stream, and a keyed singleton's feed
4386                        // is a keyed stream.
4387                        assert!(
4388                            matches!(
4389                                (&inner.metadata().collection_kind, &metadata.collection_kind),
4390                                (
4391                                    CollectionKind::Singleton { .. }
4392                                        | CollectionKind::Optional { .. },
4393                                    CollectionKind::Stream { .. }
4394                                ) | (
4395                                    CollectionKind::KeyedSingleton { .. },
4396                                    CollectionKind::KeyedStream { .. }
4397                                )
4398                            ),
4399                            "CastUpdateStream kinds do not align: {:?} -> {:?}",
4400                            inner.metadata().collection_kind,
4401                            metadata.collection_kind
4402                        );
4403                        let _ = next_stmt_id.get_and_increment();
4404                        match builders_or_callback {
4405                            BuildersOrCallback::Builders(_) => {}
4406                            BuildersOrCallback::Callback(_, node_callback) => {
4407                                node_callback(node, next_stmt_id);
4408                            }
4409                        }
4410                    }
4411
4412                    HydroNode::Cast { inner, metadata } => {
4413                        // Casts are metadata-only *except* when they cross the update-feed
4414                        // representation boundary (see
4415                        // [`CollectionKind::root_repr_is_tombstoned_update_feed`]):
4416                        // - Plain -> tombstoned (e.g. `ignore_init_none`, `into_optional` at
4417                        //   the root): every plain value becomes a `Some(v)` update (for keyed
4418                        //   feeds, every `(k, v)` entry becomes a `(k, Some(v))` upsert). This
4419                        //   is lossless: collections with a plain representation never become
4420                        //   absent, so no tombstone is ever needed.
4421                        // - Tombstoned -> plain (e.g. the cast of an always-present `or`
4422                        //   result back to a `Singleton` in `unwrap_or`/`zip`): keep the
4423                        //   values of `Some` updates. Tombstones are dropped, which is only
4424                        //   sound because such casts are constructed exclusively for feeds
4425                        //   whose consumers treat absence-of-value as absence anyway (the
4426                        //   plain-repr kinds have no notion of removal to lose).
4427                        // - Tombstoned -> tombstoned with *different* update-record encodings
4428                        //   (`Optional::into_keyed_singleton` at the root: `Option<(K, V)>`
4429                        //   updates -> `(K, Option<V>)` updates): a stateful scan remembers
4430                        //   the previously-emitted key so that when the optional becomes null
4431                        //   (or moves to a different key), the old key is explicitly
4432                        //   tombstoned.
4433                        let in_repr = update_feed_repr(inner.metadata());
4434                        let out_repr = update_feed_repr(metadata);
4435                        let cross_kind_tombstoned = in_repr == UpdateFeedRepr::Tombstoned
4436                            && out_repr == UpdateFeedRepr::Tombstoned
4437                            && std::mem::discriminant(&inner.metadata().collection_kind)
4438                                != std::mem::discriminant(&metadata.collection_kind);
4439
4440                        if in_repr == out_repr && !cross_kind_tombstoned {
4441                            // Identity: passes through the input ident unchanged. The input
4442                            // ident is already on the stack from processing the child.
4443                            let _ = next_stmt_id.get_and_increment();
4444                            match builders_or_callback {
4445                                BuildersOrCallback::Builders(_) => {}
4446                                BuildersOrCallback::Callback(_, node_callback) => {
4447                                    node_callback(node, next_stmt_id);
4448                                }
4449                            }
4450                            // input_ident stays on stack as output
4451                        } else {
4452                            let input_ident = ident_stack.pop().unwrap();
4453
4454                            let stmt_id = next_stmt_id.get_and_increment();
4455                            let cast_ident =
4456                                syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
4457
4458                            match builders_or_callback {
4459                                BuildersOrCallback::Builders(graph_builders) => {
4460                                    let cast_op: TokenStream = if cross_kind_tombstoned {
4461                                        match (
4462                                            &inner.metadata().collection_kind,
4463                                            &metadata.collection_kind,
4464                                        ) {
4465                                            (
4466                                                CollectionKind::Optional { .. },
4467                                                CollectionKind::KeyedSingleton { .. },
4468                                            ) => {
4469                                                // `Optional::into_keyed_singleton` at the root.
4470                                                // Generated code requires `K: Clone + PartialEq`
4471                                                // (to compare against and tombstone the previous
4472                                                // key); these bounds are expressed on the
4473                                                // `into_keyed_singleton` API itself.
4474                                                let lifetime: TokenStream = graph_builders
4475                                                    .cross_tick_state_lifetime(&out_location);
4476                                                let lifetime: syn::Lifetime =
4477                                                    syn::parse2(lifetime).unwrap();
4478                                                quote! {
4479                                                    scan::<#lifetime>(
4480                                                        || ::std::option::Option::None,
4481                                                        |previous_key, update: ::std::option::Option<(_, _)>| {
4482                                                            let mut deltas = ::std::vec::Vec::new();
4483                                                            match update {
4484                                                                ::std::option::Option::Some((key, value)) => {
4485                                                                    match previous_key.take() {
4486                                                                        ::std::option::Option::Some(previous) if previous != key => {
4487                                                                            deltas.push((previous, ::std::option::Option::None));
4488                                                                        }
4489                                                                        _ => {}
4490                                                                    }
4491                                                                    *previous_key = ::std::option::Option::Some(::std::clone::Clone::clone(&key));
4492                                                                    deltas.push((key, ::std::option::Option::Some(value)));
4493                                                                }
4494                                                                ::std::option::Option::None => {
4495                                                                    if let ::std::option::Option::Some(previous) = previous_key.take() {
4496                                                                        deltas.push((previous, ::std::option::Option::None));
4497                                                                    }
4498                                                                }
4499                                                            }
4500                                                            ::std::option::Option::Some(deltas)
4501                                                        },
4502                                                    ) -> flatten()
4503                                                }
4504                                            }
4505                                            (in_kind, out_kind) => todo!(
4506                                                "casting between tombstoned update feeds \
4507                                                 {:?} -> {:?} is not yet supported",
4508                                                in_kind,
4509                                                out_kind
4510                                            ),
4511                                        }
4512                                    } else {
4513                                        match (in_repr, out_repr) {
4514                                            (UpdateFeedRepr::Plain, UpdateFeedRepr::Tombstoned) => {
4515                                                match &metadata.collection_kind {
4516                                                    CollectionKind::Optional { .. } => {
4517                                                        quote! { map(::std::option::Option::Some) }
4518                                                    }
4519                                                    CollectionKind::KeyedSingleton { .. } => {
4520                                                        quote! { map(|(__hydro_key, __hydro_value)| (__hydro_key, ::std::option::Option::Some(__hydro_value))) }
4521                                                    }
4522                                                    other => panic!(
4523                                                        "unexpected tombstoned update feed kind for cast: {:?}",
4524                                                        other
4525                                                    ),
4526                                                }
4527                                            }
4528                                            (UpdateFeedRepr::Tombstoned, UpdateFeedRepr::Plain) => {
4529                                                // Reached when a root unbounded optional is cast
4530                                                // back to a plain-repr kind: `Optional::unwrap_or`
4531                                                // (and its derivatives `into_singleton`,
4532                                                // `unwrap_or_default`, `is_some`, `is_none`) casts
4533                                                // the always-present `or` result to a `Singleton`,
4534                                                // and top-level `zip` casts the `latest()` result
4535                                                // back to a `Bounded` optional. Dropping
4536                                                // tombstones is sound only because these feeds
4537                                                // never become null after having a value, so no
4538                                                // tombstone is ever emitted at runtime.
4539                                                match &inner.metadata().collection_kind {
4540                                                    CollectionKind::Optional { .. } => {
4541                                                        quote! { filter_map(|__hydro_update| __hydro_update) }
4542                                                    }
4543                                                    CollectionKind::KeyedSingleton { .. } => {
4544                                                        quote! { filter_map(|(__hydro_key, __hydro_update)| __hydro_update.map(|__hydro_value| (__hydro_key, __hydro_value))) }
4545                                                    }
4546                                                    other => panic!(
4547                                                        "unexpected tombstoned update feed kind for cast: {:?}",
4548                                                        other
4549                                                    ),
4550                                                }
4551                                            }
4552                                            _ => unreachable!(),
4553                                        }
4554                                    };
4555
4556                                    graph_builders.add_dfir_at(
4557                                        &out_location,
4558                                        parse_quote! {
4559                                            #cast_ident = #input_ident -> #cast_op;
4560                                        },
4561                                        Some(&stmt_id.to_string()),
4562                                    );
4563                                }
4564                                BuildersOrCallback::Callback(_, node_callback) => {
4565                                    node_callback(node, next_stmt_id);
4566                                }
4567                            }
4568
4569                            ident_stack.push(cast_ident);
4570                        }
4571                    }
4572
4573                    HydroNode::UnboundSingleton { .. } => {
4574                        let inner_ident = ident_stack.pop().unwrap();
4575
4576                        let stmt_id = next_stmt_id.get_and_increment();
4577                        let out_ident =
4578                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
4579
4580                        match builders_or_callback {
4581                            BuildersOrCallback::Builders(graph_builders) => {
4582                                // A bounded value's update feed is already a valid feed of
4583                                // the unbounded singleton: consumers hold the latest update, so
4584                                // it need not be replayed on every tick.
4585                                graph_builders.add_dfir_at(
4586                                    &out_location,
4587                                    parse_quote! {
4588                                        #out_ident = #inner_ident;
4589                                    },
4590                                    None,
4591                                );
4592                            }
4593                            BuildersOrCallback::Callback(_, node_callback) => {
4594                                node_callback(node, next_stmt_id);
4595                            }
4596                        }
4597
4598                        ident_stack.push(out_ident);
4599                    }
4600
4601                    HydroNode::AssertIsConsistent { inner, trusted, .. } => {
4602                        let inner_ident = ident_stack.pop().unwrap();
4603
4604                        let stmt_id = next_stmt_id.get_and_increment();
4605                        let out_ident =
4606                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
4607
4608                        match builders_or_callback {
4609                            BuildersOrCallback::Builders(graph_builders) => {
4610                                graph_builders.assert_is_consistent(
4611                                    *trusted,
4612                                    &inner.metadata().location_id,
4613                                    inner_ident,
4614                                    &out_ident,
4615                                );
4616                            }
4617                            BuildersOrCallback::Callback(_, node_callback) => {
4618                                node_callback(node, next_stmt_id);
4619                            }
4620                        }
4621
4622                        ident_stack.push(out_ident);
4623                    }
4624
4625                    HydroNode::ObserveNonDet {
4626                        inner,
4627                        trusted,
4628                        metadata,
4629                        ..
4630                    } => {
4631                        let inner_ident = ident_stack.pop().unwrap();
4632
4633                        let stmt_id = next_stmt_id.get_and_increment();
4634                        let observe_ident =
4635                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
4636
4637                        match builders_or_callback {
4638                            BuildersOrCallback::Builders(graph_builders) => {
4639                                graph_builders.observe_nondet(
4640                                    *trusted,
4641                                    &inner.metadata().location_id,
4642                                    inner_ident,
4643                                    &inner.metadata().collection_kind,
4644                                    &observe_ident,
4645                                    &metadata.collection_kind,
4646                                    &metadata.op,
4647                                );
4648                            }
4649                            BuildersOrCallback::Callback(_, node_callback) => {
4650                                node_callback(node, next_stmt_id);
4651                            }
4652                        }
4653
4654                        ident_stack.push(observe_ident);
4655                    }
4656
4657                    HydroNode::Batch {
4658                        inner, metadata, ..
4659                    } => {
4660                        let inner_ident = ident_stack.pop().unwrap();
4661
4662                        let stmt_id = next_stmt_id.get_and_increment();
4663                        let batch_ident =
4664                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
4665
4666                        match builders_or_callback {
4667                            BuildersOrCallback::Builders(graph_builders) => {
4668                                graph_builders.batch(
4669                                    inner_ident,
4670                                    &inner.metadata().location_id,
4671                                    &inner.metadata().collection_kind,
4672                                    &batch_ident,
4673                                    &out_location,
4674                                    &metadata.op,
4675                                    fold_hooked_idents,
4676                                );
4677                            }
4678                            BuildersOrCallback::Callback(_, node_callback) => {
4679                                node_callback(node, next_stmt_id);
4680                            }
4681                        }
4682
4683                        ident_stack.push(batch_ident);
4684                    }
4685
4686                    HydroNode::Snapshot {
4687                        inner, metadata, ..
4688                    } => {
4689                        let inner_ident = ident_stack.pop().unwrap();
4690
4691                        let stmt_id = next_stmt_id.get_and_increment();
4692                        let snapshot_ident =
4693                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
4694
4695                        match builders_or_callback {
4696                            BuildersOrCallback::Builders(graph_builders) => {
4697                                graph_builders.snapshot(
4698                                    inner_ident,
4699                                    &inner.metadata().location_id,
4700                                    &inner.metadata().collection_kind,
4701                                    &snapshot_ident,
4702                                    &out_location,
4703                                    &metadata.op,
4704                                    fold_hooked_idents,
4705                                );
4706                            }
4707                            BuildersOrCallback::Callback(_, node_callback) => {
4708                                node_callback(node, next_stmt_id);
4709                            }
4710                        }
4711
4712                        ident_stack.push(snapshot_ident);
4713                    }
4714
4715                    HydroNode::YieldConcat {
4716                        inner, metadata, ..
4717                    } => {
4718                        let inner_ident = ident_stack.pop().unwrap();
4719
4720                        let stmt_id = next_stmt_id.get_and_increment();
4721                        let yield_ident =
4722                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
4723
4724                        match builders_or_callback {
4725                            BuildersOrCallback::Builders(graph_builders) => {
4726                                graph_builders.yield_from_tick(
4727                                    inner_ident,
4728                                    &inner.metadata().location_id,
4729                                    &inner.metadata().collection_kind,
4730                                    &yield_ident,
4731                                    &out_location,
4732                                    &metadata.collection_kind,
4733                                );
4734                            }
4735                            BuildersOrCallback::Callback(_, node_callback) => {
4736                                node_callback(node, next_stmt_id);
4737                            }
4738                        }
4739
4740                        ident_stack.push(yield_ident);
4741                    }
4742
4743                    HydroNode::BeginAtomic { inner, metadata } => {
4744                        let inner_ident = ident_stack.pop().unwrap();
4745
4746                        let stmt_id = next_stmt_id.get_and_increment();
4747                        let begin_ident =
4748                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
4749
4750                        match builders_or_callback {
4751                            BuildersOrCallback::Builders(graph_builders) => {
4752                                graph_builders.begin_atomic(
4753                                    inner_ident,
4754                                    &inner.metadata().location_id,
4755                                    &inner.metadata().collection_kind,
4756                                    &begin_ident,
4757                                    &out_location,
4758                                    &metadata.op,
4759                                );
4760                            }
4761                            BuildersOrCallback::Callback(_, node_callback) => {
4762                                node_callback(node, next_stmt_id);
4763                            }
4764                        }
4765
4766                        ident_stack.push(begin_ident);
4767                    }
4768
4769                    HydroNode::EndAtomic {
4770                        inner, metadata, ..
4771                    } => {
4772                        let inner_ident = ident_stack.pop().unwrap();
4773
4774                        let stmt_id = next_stmt_id.get_and_increment();
4775                        let end_ident =
4776                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
4777
4778                        match builders_or_callback {
4779                            BuildersOrCallback::Builders(graph_builders) => {
4780                                graph_builders.end_atomic(
4781                                    inner_ident,
4782                                    &inner.metadata().location_id,
4783                                    &inner.metadata().collection_kind,
4784                                    &end_ident,
4785                                    &metadata.collection_kind,
4786                                );
4787                            }
4788                            BuildersOrCallback::Callback(_, node_callback) => {
4789                                node_callback(node, next_stmt_id);
4790                            }
4791                        }
4792
4793                        ident_stack.push(end_ident);
4794                    }
4795
4796                    HydroNode::Source {
4797                        source, metadata, ..
4798                    } => {
4799                        if matches!(source, HydroSource::ExternalNetwork()) {
4800                            ident_stack.push(syn::Ident::new("DUMMY", Span::call_site()));
4801                        } else {
4802                            let stmt_id = next_stmt_id.get_and_increment();
4803                            let source_ident =
4804                                syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
4805
4806                            // For tick-located sources, holds the source pipeline (RHS) so that
4807                            // production codegen can hoist it to the root and window it into the
4808                            // tick's loop (DFIR sources may not live inside a `loop { ... }`).
4809                            let mut tick_source_rhs: Option<TokenStream> = None;
4810
4811                            let source_stmt = match source {
4812                                HydroSource::Stream(expr) => {
4813                                    debug_assert!(metadata.location_id.is_top_level());
4814                                    parse_quote! {
4815                                        #source_ident = source_stream(#expr);
4816                                    }
4817                                }
4818
4819                                HydroSource::ExternalNetwork() => {
4820                                    unreachable!()
4821                                }
4822
4823                                HydroSource::Iter(expr) => {
4824                                    if metadata.location_id.is_root() {
4825                                        parse_quote! {
4826                                            #source_ident = source_iter(#expr);
4827                                        }
4828                                    } else {
4829                                        // Located inside a tick or atomic region (which is fused
4830                                        // into its tick's loop). DFIR sources may not live inside a
4831                                        // `loop { ... }`, so hoist the source to the root and window
4832                                        // it into the loop.
4833                                        // TODO(shadaj): a more natural semantics would be to re-evaluate the expression on each tick
4834                                        tick_source_rhs = Some(quote! { source_iter(#expr) });
4835                                        // Unused: `tick_source_rhs` is emitted via
4836                                        // `add_tick_source` instead.
4837                                        parse_quote! {
4838                                            #source_ident = source_iter(#expr);
4839                                        }
4840                                    }
4841                                }
4842
4843                                HydroSource::Spin() => {
4844                                    debug_assert!(metadata.location_id.is_top_level());
4845                                    parse_quote! {
4846                                        #source_ident = spin();
4847                                    }
4848                                }
4849
4850                                HydroSource::ClusterMembers(target_loc, state) => {
4851                                    debug_assert!(metadata.location_id.is_top_level());
4852
4853                                    let members_tee_ident = syn::Ident::new(
4854                                        &format!(
4855                                            "__cluster_members_tee_{}_{}",
4856                                            metadata.location_id.root().key(),
4857                                            target_loc.key(),
4858                                        ),
4859                                        Span::call_site(),
4860                                    );
4861
4862                                    match state {
4863                                        ClusterMembersState::Stream(d) => {
4864                                            parse_quote! {
4865                                                #members_tee_ident = source_stream(#d) -> tee();
4866                                                #source_ident = #members_tee_ident;
4867                                            }
4868                                        },
4869                                        ClusterMembersState::Uninit => syn::parse_quote! {
4870                                            #source_ident = source_stream(DUMMY);
4871                                        },
4872                                        ClusterMembersState::Tee(..) => parse_quote! {
4873                                            #source_ident = #members_tee_ident;
4874                                        },
4875                                    }
4876                                }
4877
4878                                HydroSource::Embedded(ident) => {
4879                                    parse_quote! {
4880                                        #source_ident = source_stream(#ident);
4881                                    }
4882                                }
4883
4884                                HydroSource::EmbeddedSingleton(ident) => {
4885                                    parse_quote! {
4886                                        #source_ident = source_iter([#ident]);
4887                                    }
4888                                }
4889                            };
4890
4891                            match builders_or_callback {
4892                                BuildersOrCallback::Builders(graph_builders) => {
4893                                    if let Some(source_rhs) = tick_source_rhs {
4894                                        graph_builders.add_tick_source(
4895                                            &out_location,
4896                                            source_rhs,
4897                                            &source_ident,
4898                                            &metadata.collection_kind,
4899                                            true,
4900                                            Some(&stmt_id.to_string()),
4901                                        );
4902                                    } else {
4903                                        graph_builders.add_dfir_at(
4904                                            &out_location,
4905                                            source_stmt,
4906                                            Some(&stmt_id.to_string()),
4907                                        );
4908                                    }
4909                                }
4910                                BuildersOrCallback::Callback(_, node_callback) => {
4911                                    node_callback(node, next_stmt_id);
4912                                }
4913                            }
4914
4915                            ident_stack.push(source_ident);
4916                        }
4917                    }
4918
4919                    HydroNode::SingletonSource { value, first_tick_only, metadata } => {
4920                        let stmt_id = next_stmt_id.get_and_increment();
4921                        let source_ident =
4922                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
4923
4924                        match builders_or_callback {
4925                            BuildersOrCallback::Builders(graph_builders) => {
4926                                if *first_tick_only {
4927                                    assert!(
4928                                        !metadata.location_id.is_top_level(),
4929                                        "first_tick_only SingletonSource must be inside a tick"
4930                                    );
4931                                    // Delivered only on the first execution of the tick region.
4932                                    graph_builders.add_tick_source(
4933                                        &out_location,
4934                                        quote! { source_iter([#value]) },
4935                                        &source_ident,
4936                                        &metadata.collection_kind,
4937                                        false,
4938                                        Some(&stmt_id.to_string()),
4939                                    );
4940                                } else if metadata.location_id.is_root() {
4941                                    // Bounded or not, a root singleton's update feed for a
4942                                    // constant is the single update carrying it: consumers of the
4943                                    // feed (snapshots, update-stream combinators) hold the latest
4944                                    // update, so it need not be replayed on every tick.
4945                                    graph_builders.add_dfir_at(
4946                                        &out_location,
4947                                        parse_quote! {
4948                                            #source_ident = source_iter([#value]);
4949                                        },
4950                                        Some(&stmt_id.to_string()),
4951                                    );
4952                                } else {
4953                                    // A tick- or atomic-located singleton source (the atomic
4954                                    // region is fused into its tick's loop) that yields its value
4955                                    // on every firing. DFIR sources may not live inside a
4956                                    // `loop { ... }`, so hoist it to the root and window it in.
4957                                    graph_builders.add_tick_source(
4958                                        &out_location,
4959                                        quote! { source_iter([#value]) },
4960                                        &source_ident,
4961                                        &metadata.collection_kind,
4962                                        true,
4963                                        Some(&stmt_id.to_string()),
4964                                    );
4965                                }
4966                            }
4967                            BuildersOrCallback::Callback(_, node_callback) => {
4968                                node_callback(node, next_stmt_id);
4969                            }
4970                        }
4971
4972                        ident_stack.push(source_ident);
4973                    }
4974
4975                    HydroNode::CycleSource { cycle_id, .. } => {
4976                        let ident = cycle_id.as_ident();
4977
4978                        // consume a stmt id even though we did not emit anything so that we can instrument this
4979                        let _ = next_stmt_id.get_and_increment();
4980
4981                        match builders_or_callback {
4982                            BuildersOrCallback::Builders(_) => {}
4983                            BuildersOrCallback::Callback(_, node_callback) => {
4984                                node_callback(node, next_stmt_id);
4985                            }
4986                        }
4987
4988                        ident_stack.push(ident);
4989                    }
4990
4991                    HydroNode::Tee { inner, .. } => {
4992                        // we consume a stmt id regardless of if we emit the tee() operator,
4993                        // so that during rewrites we touch all recipients of the tee()
4994                        let stmt_id = next_stmt_id.get_and_increment();
4995
4996                        let ret_ident = if let Some(built_idents) =
4997                            built_tees.get(&(std::ptr::from_ref(inner.0.as_ref())))
4998                        {
4999                            match builders_or_callback {
5000                                BuildersOrCallback::Builders(_) => {}
5001                                BuildersOrCallback::Callback(_, node_callback) => {
5002                                    node_callback(node, next_stmt_id);
5003                                }
5004                            }
5005
5006                            built_idents[0].clone()
5007                        } else {
5008                            // The inner node was already processed by transform_bottom_up,
5009                            // so its ident is on the stack
5010                            let inner_ident = ident_stack.pop().unwrap();
5011
5012                            let tee_ident =
5013                                syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
5014
5015                            built_tees.insert(
5016                                std::ptr::from_ref(inner.0.as_ref()),
5017                                vec![tee_ident.clone()],
5018                            );
5019
5020                            match builders_or_callback {
5021                                BuildersOrCallback::Builders(graph_builders) => {
5022                                    // NOTE: With `forward_ref`, the fold codegen may not have
5023                                    // run yet when we reach this tee, so `fold_hooked_idents`
5024                                    // might not contain the inner ident. In that case we won't
5025                                    // propagate the "hooked" status to the tee and the
5026                                    // downstream singleton batch will use the normal
5027                                    // `SingletonHook` instead of `PassthroughSingletonHook`.
5028                                    // This is not a soundness issue: the fallback hook still
5029                                    // produces correct behavior, just with a redundant decision
5030                                    // point. TODO(https://github.com/hydro-project/hydro/issues/2856):
5031                                    // fix ordering so forward_ref folds are always processed
5032                                    // before their downstream tees.
5033                                    if fold_hooked_idents.contains(&inner_ident.to_string()) {
5034                                        fold_hooked_idents.insert(tee_ident.to_string());
5035                                    }
5036                                    graph_builders.add_dfir_at(
5037                                        &out_location,
5038                                        parse_quote! {
5039                                            #tee_ident = #inner_ident -> tee();
5040                                        },
5041                                        Some(&stmt_id.to_string()),
5042                                    );
5043                                }
5044                                BuildersOrCallback::Callback(_, node_callback) => {
5045                                    node_callback(node, next_stmt_id);
5046                                }
5047                            }
5048
5049                            tee_ident
5050                        };
5051
5052                        ident_stack.push(ret_ident);
5053                    }
5054
5055                    HydroNode::Reference { inner, kind, .. } => {
5056                        // we consume a stmt id regardless of if we emit the operator,
5057                        // so that during rewrites we touch all recipients
5058                        let stmt_id = next_stmt_id.get_and_increment();
5059
5060                        let ret_ident = if let Some(built_idents) =
5061                            built_tees.get(&(std::ptr::from_ref(inner.0.as_ref())))
5062                        {
5063                            built_idents[0].clone()
5064                        } else {
5065                            let inner_ident = ident_stack.pop().unwrap();
5066
5067                            let ref_ident =
5068                                syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
5069
5070                            built_tees.insert(
5071                                std::ptr::from_ref(inner.0.as_ref()),
5072                                vec![ref_ident.clone()],
5073                            );
5074
5075                            match builders_or_callback {
5076                                BuildersOrCallback::Builders(graph_builders) => {
5077                                    let op_ident = syn::Ident::new(
5078                                        match kind {
5079                                            crate::handoff_ref::HandoffRefKind::Singleton => "singleton",
5080                                            crate::handoff_ref::HandoffRefKind::Optional => "optional",
5081                                            crate::handoff_ref::HandoffRefKind::Vec => "handoff",
5082                                        },
5083                                        Span::call_site(),
5084                                    );
5085                                    graph_builders.add_dfir_at(
5086                                        &out_location,
5087                                        parse_quote! {
5088                                            #ref_ident = #inner_ident -> #op_ident();
5089                                        },
5090                                        Some(&stmt_id.to_string()),
5091                                    );
5092                                }
5093                                BuildersOrCallback::Callback(_, node_callback) => {
5094                                    node_callback(node, next_stmt_id);
5095                                }
5096                            }
5097
5098                            ref_ident
5099                        };
5100
5101                        ident_stack.push(ret_ident);
5102                    }
5103
5104                    HydroNode::PartitionSide {
5105                        inner, is_true, metadata: _,
5106                    } => {
5107                        let is_true = *is_true; // need to copy early to avoid borrow checking issues with node
5108                        let ptr = std::ptr::from_ref(inner.0.as_ref());
5109                        let stmt_id = next_stmt_id.get_and_increment();
5110
5111                        let ret_ident = if let Some(built_idents) = built_tees.get(&ptr) {
5112                            match builders_or_callback {
5113                                BuildersOrCallback::Builders(_) => {}
5114                                BuildersOrCallback::Callback(_, node_callback) => {
5115                                    node_callback(node, next_stmt_id);
5116                                }
5117                            }
5118
5119                            let idx = usize::from(!is_true);
5120                            built_idents[idx].clone()
5121                        } else {
5122                            // The `PartitionShared` node was already processed by transform_bottom_up,
5123                            // so its ident is on the stack
5124                            let partition_ident = ident_stack.pop().unwrap();
5125
5126                            let true_ident = syn::Ident::new(
5127                                &format!("stream_{}_true", stmt_id),
5128                                Span::call_site(),
5129                            );
5130                            let false_ident = syn::Ident::new(
5131                                &format!("stream_{}_false", stmt_id),
5132                                Span::call_site(),
5133                            );
5134
5135                            built_tees.insert(
5136                                ptr,
5137                                vec![true_ident.clone(), false_ident.clone()],
5138                            );
5139
5140                            let stmt_id = next_stmt_id.get_and_increment();
5141                            match builders_or_callback {
5142                                BuildersOrCallback::Builders(graph_builders) => {
5143                                    graph_builders.add_dfir_at(
5144                                        &out_location,
5145                                        parse_quote! {
5146                                            #true_ident = #partition_ident[0];
5147                                            #false_ident = #partition_ident[1];
5148                                        },
5149                                        Some(&stmt_id.to_string()),
5150                                    );
5151                                }
5152                                BuildersOrCallback::Callback(_, node_callback) => {
5153                                    node_callback(node, next_stmt_id);
5154                                }
5155                            }
5156
5157                            if is_true { true_ident } else { false_ident }
5158                        };
5159
5160                        ident_stack.push(ret_ident);
5161                    }
5162
5163                    HydroNode::PartitionShared { input, f, metadata } => {
5164                        // Pop input ident (pushed last by transform_children) before
5165                        // draining the closure's singleton ref idents below it.
5166                        let inner_ident = ident_stack.pop().unwrap();
5167                        let f_tokens = f.emit_tokens(&mut ident_stack);
5168
5169                        let inner_ident = {
5170                            maybe_observe_for_mut(
5171                                f, inner_ident,
5172                                &input.metadata().location_id,
5173                                &input.metadata().collection_kind,
5174                                &metadata.op,
5175                                builders_or_callback, next_stmt_id,
5176                            )
5177                        };
5178
5179                        let stmt_id = next_stmt_id.get_and_increment();
5180                        let partition_ident = syn::Ident::new(
5181                            &format!("stream_{}_partition", stmt_id),
5182                            Span::call_site(),
5183                        );
5184
5185                        let stmt_id = next_stmt_id.get_and_increment();
5186                        match builders_or_callback {
5187                            BuildersOrCallback::Builders(graph_builders) => {
5188                                graph_builders.add_dfir_at(
5189                                    &out_location,
5190                                    parse_quote! {
5191                                        #partition_ident = #inner_ident -> partition(|__item, __num_outputs| if (#f_tokens)(__item) { 0_usize } else { 1_usize });
5192                                    },
5193                                    Some(&stmt_id.to_string()),
5194                                );
5195                            }
5196                            BuildersOrCallback::Callback(_, node_callback) => {
5197                                node_callback(node, next_stmt_id);
5198                            }
5199                        }
5200                        ident_stack.push(partition_ident);
5201                    }
5202
5203                    HydroNode::Chain { .. } => {
5204                        // Children are processed left-to-right, so second is on top
5205                        let second_ident = ident_stack.pop().unwrap();
5206                        let first_ident = ident_stack.pop().unwrap();
5207
5208                        let stmt_id = next_stmt_id.get_and_increment();
5209                        let chain_ident =
5210                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
5211
5212                        match builders_or_callback {
5213                            BuildersOrCallback::Builders(graph_builders) => {
5214                                graph_builders.add_dfir_at(
5215                                    &out_location,
5216                                    parse_quote! {
5217                                        #chain_ident = chain();
5218                                        #first_ident -> [0]#chain_ident;
5219                                        #second_ident -> [1]#chain_ident;
5220                                    },
5221                                    Some(&stmt_id.to_string()),
5222                                );
5223                            }
5224                            BuildersOrCallback::Callback(_, node_callback) => {
5225                                node_callback(node, next_stmt_id);
5226                            }
5227                        }
5228
5229                        ident_stack.push(chain_ident);
5230                    }
5231
5232                    HydroNode::MergeOrdered { first, metadata, .. } => {
5233                        let second_ident = ident_stack.pop().unwrap();
5234                        let first_ident = ident_stack.pop().unwrap();
5235
5236                        let stmt_id = next_stmt_id.get_and_increment();
5237                        let merge_ident =
5238                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
5239
5240                        match builders_or_callback {
5241                            BuildersOrCallback::Builders(graph_builders) => {
5242                                graph_builders.merge_ordered(
5243                                    &first.metadata().location_id,
5244                                    first_ident,
5245                                    second_ident,
5246                                    &merge_ident,
5247                                    &first.metadata().collection_kind,
5248                                    &metadata.op,
5249                                    Some(&stmt_id.to_string()),
5250                                );
5251                            }
5252                            BuildersOrCallback::Callback(_, node_callback) => {
5253                                node_callback(node, next_stmt_id);
5254                            }
5255                        }
5256
5257                        ident_stack.push(merge_ident);
5258                    }
5259
5260                    HydroNode::ChainFirst { .. } => {
5261                        let second_ident = ident_stack.pop().unwrap();
5262                        let first_ident = ident_stack.pop().unwrap();
5263
5264                        let stmt_id = next_stmt_id.get_and_increment();
5265                        let chain_ident =
5266                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
5267
5268                        match builders_or_callback {
5269                            BuildersOrCallback::Builders(graph_builders) => {
5270                                graph_builders.add_dfir_at(
5271                                    &out_location,
5272                                    parse_quote! {
5273                                        #chain_ident = chain_first_n(1);
5274                                        #first_ident -> [0]#chain_ident;
5275                                        #second_ident -> [1]#chain_ident;
5276                                    },
5277                                    Some(&stmt_id.to_string()),
5278                                );
5279                            }
5280                            BuildersOrCallback::Callback(_, node_callback) => {
5281                                node_callback(node, next_stmt_id);
5282                            }
5283                        }
5284
5285                        ident_stack.push(chain_ident);
5286                    }
5287
5288                    HydroNode::CrossSingleton { right, .. } => {
5289                        let right_ident = ident_stack.pop().unwrap();
5290                        let left_ident = ident_stack.pop().unwrap();
5291
5292                        let stmt_id = next_stmt_id.get_and_increment();
5293                        let cross_ident =
5294                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
5295
5296                        match builders_or_callback {
5297                            BuildersOrCallback::Builders(graph_builders) => {
5298                                if right.metadata().location_id.is_top_level()
5299                                    && right.metadata().collection_kind.is_bounded()
5300                                {
5301                                    let lifetime =
5302                                        graph_builders.cross_tick_state_lifetime(&out_location);
5303                                    graph_builders.add_dfir_at(
5304                                        &out_location,
5305                                        parse_quote! {
5306                                            #cross_ident = cross_singleton::<#lifetime>();
5307                                            #left_ident -> [input]#cross_ident;
5308                                            #right_ident -> [single]#cross_ident;
5309                                        },
5310                                        Some(&stmt_id.to_string()),
5311                                    );
5312                                } else {
5313                                    graph_builders.add_dfir_at(
5314                                        &out_location,
5315                                        parse_quote! {
5316                                            #cross_ident = cross_singleton();
5317                                            #left_ident -> [input]#cross_ident;
5318                                            #right_ident -> [single]#cross_ident;
5319                                        },
5320                                        Some(&stmt_id.to_string()),
5321                                    );
5322                                }
5323                            }
5324                            BuildersOrCallback::Callback(_, node_callback) => {
5325                                node_callback(node, next_stmt_id);
5326                            }
5327                        }
5328
5329                        ident_stack.push(cross_ident);
5330                    }
5331
5332                    HydroNode::CrossProduct { .. } | HydroNode::Join { .. } => {
5333                        let operator: syn::Ident = if matches!(node, HydroNode::CrossProduct { .. }) {
5334                            parse_quote!(cross_join_multiset)
5335                        } else {
5336                            parse_quote!(join_multiset)
5337                        };
5338
5339                        let (HydroNode::CrossProduct { left, right, .. }
5340                        | HydroNode::Join { left, right, .. }) = node
5341                        else {
5342                            unreachable!()
5343                        };
5344
5345                        let is_top_level = left.metadata().location_id.is_top_level()
5346                            && right.metadata().location_id.is_top_level();
5347                        let left_top_level = left.metadata().location_id.is_top_level();
5348                        let right_top_level = right.metadata().location_id.is_top_level();
5349
5350                        let right_ident = ident_stack.pop().unwrap();
5351                        let left_ident = ident_stack.pop().unwrap();
5352
5353                        let stmt_id = next_stmt_id.get_and_increment();
5354                        let stream_ident =
5355                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
5356
5357                        match builders_or_callback {
5358                            BuildersOrCallback::Builders(graph_builders) => {
5359                                let left_lifetime = if left_top_level {
5360                                    graph_builders.cross_tick_state_lifetime(&out_location)
5361                                } else {
5362                                    graph_builders.tick_state_lifetime(&out_location)
5363                                };
5364
5365                                let right_lifetime = if right_top_level {
5366                                    graph_builders.cross_tick_state_lifetime(&out_location)
5367                                } else {
5368                                    graph_builders.tick_state_lifetime(&out_location)
5369                                };
5370
5371                                graph_builders.add_dfir_at(
5372                                    &out_location,
5373                                    if is_top_level {
5374                                        // if both inputs are root, the output is expected to have streamy semantics, so we need
5375                                        // a multiset_delta() to negate the replay behavior
5376                                        parse_quote! {
5377                                            #stream_ident = #operator::<#left_lifetime, #right_lifetime>() -> multiset_delta();
5378                                            #left_ident -> [0]#stream_ident;
5379                                            #right_ident -> [1]#stream_ident;
5380                                        }
5381                                    } else {
5382                                        parse_quote! {
5383                                            #stream_ident = #operator::<#left_lifetime, #right_lifetime>();
5384                                            #left_ident -> [0]#stream_ident;
5385                                            #right_ident -> [1]#stream_ident;
5386                                        }
5387                                    },
5388                                    Some(&stmt_id.to_string()),
5389                                );
5390                            }
5391                            BuildersOrCallback::Callback(_, node_callback) => {
5392                                node_callback(node, next_stmt_id);
5393                            }
5394                        }
5395
5396                        ident_stack.push(stream_ident);
5397                    }
5398
5399                    HydroNode::Difference { .. } | HydroNode::AntiJoin { .. } => {
5400                        let operator: syn::Ident = if matches!(node, HydroNode::Difference { .. }) {
5401                            parse_quote!(difference)
5402                        } else {
5403                            parse_quote!(anti_join)
5404                        };
5405
5406                        let (HydroNode::Difference { neg, .. } | HydroNode::AntiJoin { neg, .. }) =
5407                            node
5408                        else {
5409                            unreachable!()
5410                        };
5411
5412                        let neg_top_level = neg.metadata().location_id.is_top_level();
5413
5414                        let neg_ident = ident_stack.pop().unwrap();
5415                        let pos_ident = ident_stack.pop().unwrap();
5416
5417                        let stmt_id = next_stmt_id.get_and_increment();
5418                        let stream_ident =
5419                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
5420
5421                        match builders_or_callback {
5422                            BuildersOrCallback::Builders(graph_builders) => {
5423                                let neg_lifetime = if neg_top_level {
5424                                    graph_builders.cross_tick_state_lifetime(&out_location)
5425                                } else {
5426                                    graph_builders.tick_state_lifetime(&out_location)
5427                                };
5428                                let pos_lifetime =
5429                                    graph_builders.tick_state_lifetime(&out_location);
5430
5431                                graph_builders.add_dfir_at(
5432                                    &out_location,
5433                                    parse_quote! {
5434                                        #stream_ident = #operator::<#pos_lifetime, #neg_lifetime>();
5435                                        #pos_ident -> [pos]#stream_ident;
5436                                        #neg_ident -> [neg]#stream_ident;
5437                                    },
5438                                    Some(&stmt_id.to_string()),
5439                                );
5440                            }
5441                            BuildersOrCallback::Callback(_, node_callback) => {
5442                                node_callback(node, next_stmt_id);
5443                            }
5444                        }
5445
5446                        ident_stack.push(stream_ident);
5447                    }
5448
5449                    HydroNode::JoinHalf { .. } => {
5450                        let HydroNode::JoinHalf { right, .. } = node else {
5451                            unreachable!()
5452                        };
5453
5454                        assert!(
5455                            right.metadata().collection_kind.is_bounded(),
5456                            "JoinHalf requires the right (build) side to be Bounded, got {:?}",
5457                            right.metadata().collection_kind
5458                        );
5459
5460                        let build_top_level = right.metadata().location_id.is_top_level();
5461
5462                        let build_ident = ident_stack.pop().unwrap();
5463                        let probe_ident = ident_stack.pop().unwrap();
5464
5465                        let stmt_id = next_stmt_id.get_and_increment();
5466                        let stream_ident =
5467                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
5468
5469                        match builders_or_callback {
5470                            BuildersOrCallback::Builders(graph_builders) => {
5471                                let build_lifetime = if build_top_level {
5472                                    graph_builders.cross_tick_state_lifetime(&out_location)
5473                                } else {
5474                                    graph_builders.tick_state_lifetime(&out_location)
5475                                };
5476                                let probe_lifetime =
5477                                    graph_builders.tick_state_lifetime(&out_location);
5478
5479                                graph_builders.add_dfir_at(
5480                                    &out_location,
5481                                    parse_quote! {
5482                                        #stream_ident = join_multiset_half::<#build_lifetime, #probe_lifetime>();
5483                                        #probe_ident -> [probe]#stream_ident;
5484                                        #build_ident -> [build]#stream_ident;
5485                                    },
5486                                    Some(&stmt_id.to_string()),
5487                                );
5488                            }
5489                            BuildersOrCallback::Callback(_, node_callback) => {
5490                                node_callback(node, next_stmt_id);
5491                            }
5492                        }
5493
5494                        ident_stack.push(stream_ident);
5495                    }
5496
5497                    HydroNode::ResolveFutures { .. } => {
5498                        let input_ident = ident_stack.pop().unwrap();
5499
5500                        let stmt_id = next_stmt_id.get_and_increment();
5501                        let futures_ident =
5502                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
5503
5504                        match builders_or_callback {
5505                            BuildersOrCallback::Builders(graph_builders) => {
5506                                graph_builders.add_dfir_at(
5507                                    &out_location,
5508                                    parse_quote! {
5509                                        #futures_ident = #input_ident -> resolve_futures();
5510                                    },
5511                                    Some(&stmt_id.to_string()),
5512                                );
5513                            }
5514                            BuildersOrCallback::Callback(_, node_callback) => {
5515                                node_callback(node, next_stmt_id);
5516                            }
5517                        }
5518
5519                        ident_stack.push(futures_ident);
5520                    }
5521
5522                    HydroNode::ResolveFuturesBlocking { .. } => {
5523                        let input_ident = ident_stack.pop().unwrap();
5524
5525                        let stmt_id = next_stmt_id.get_and_increment();
5526                        let futures_ident =
5527                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
5528
5529                        match builders_or_callback {
5530                            BuildersOrCallback::Builders(graph_builders) => {
5531                                graph_builders.add_dfir_at(
5532                                    &out_location,
5533                                    parse_quote! {
5534                                        #futures_ident = #input_ident -> resolve_futures_blocking();
5535                                    },
5536                                    Some(&stmt_id.to_string()),
5537                                );
5538                            }
5539                            BuildersOrCallback::Callback(_, node_callback) => {
5540                                node_callback(node, next_stmt_id);
5541                            }
5542                        }
5543
5544                        ident_stack.push(futures_ident);
5545                    }
5546
5547                    HydroNode::ResolveFuturesOrdered { .. } => {
5548                        let input_ident = ident_stack.pop().unwrap();
5549
5550                        let stmt_id = next_stmt_id.get_and_increment();
5551                        let futures_ident =
5552                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
5553
5554                        match builders_or_callback {
5555                            BuildersOrCallback::Builders(graph_builders) => {
5556                                graph_builders.add_dfir_at(
5557                                    &out_location,
5558                                    parse_quote! {
5559                                        #futures_ident = #input_ident -> resolve_futures_ordered();
5560                                    },
5561                                    Some(&stmt_id.to_string()),
5562                                );
5563                            }
5564                            BuildersOrCallback::Callback(_, node_callback) => {
5565                                node_callback(node, next_stmt_id);
5566                            }
5567                        }
5568
5569                        ident_stack.push(futures_ident);
5570                    }
5571
5572                    HydroNode::Map {
5573                        f,
5574                        input,
5575                        metadata,
5576                    } => {
5577                        // Pop input ident (pushed last by transform_children).
5578                        let input_ident = ident_stack.pop().unwrap();
5579                        let f_tokens = f.emit_tokens(&mut ident_stack);
5580
5581                        let input_ident = maybe_observe_for_mut(
5582                            f,
5583                            input_ident,
5584                            &input.metadata().location_id,
5585                            &input.metadata().collection_kind,
5586                            &metadata.op,
5587                            builders_or_callback,
5588                            next_stmt_id,
5589                        );
5590
5591                        let stmt_id = next_stmt_id.get_and_increment();
5592                        let map_ident =
5593                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
5594
5595                        // A map over a tombstoned update feed transforms the *values* of
5596                        // updates, passing tombstones (`None`) through unchanged. For keyed
5597                        // feeds the inner closure transforms plain `(K, V)` entries and
5598                        // preserves the key (guaranteed by the `KeyedSingleton::map` /
5599                        // `map_with_key` construction), so a tombstoned key passes through
5600                        // with its key intact.
5601                        let map_op: TokenStream = match (
5602                            update_feed_repr(input.metadata()),
5603                            update_feed_repr(metadata),
5604                        ) {
5605                            (UpdateFeedRepr::Plain, UpdateFeedRepr::Plain) => {
5606                                quote! { map(#f_tokens) }
5607                            }
5608                            (UpdateFeedRepr::Tombstoned, UpdateFeedRepr::Tombstoned) => {
5609                                match &metadata.collection_kind {
5610                                    CollectionKind::Optional { .. } => {
5611                                        quote! {
5612                                            map({
5613                                                let mut __hydro_map_f = #f_tokens;
5614                                                move |__hydro_update| __hydro_update.map(&mut __hydro_map_f)
5615                                            })
5616                                        }
5617                                    }
5618                                    CollectionKind::KeyedSingleton { .. } => {
5619                                        quote! {
5620                                            map({
5621                                                let mut __hydro_map_f = #f_tokens;
5622                                                move |(__hydro_key, __hydro_update)| match __hydro_update {
5623                                                    ::std::option::Option::Some(__hydro_value) => {
5624                                                        let (__hydro_out_key, __hydro_out_value) =
5625                                                            (__hydro_map_f)((__hydro_key, __hydro_value));
5626                                                        (__hydro_out_key, ::std::option::Option::Some(__hydro_out_value))
5627                                                    }
5628                                                    ::std::option::Option::None => {
5629                                                        (__hydro_key, ::std::option::Option::None)
5630                                                    }
5631                                                }
5632                                            })
5633                                        }
5634                                    }
5635                                    other => panic!(
5636                                        "unexpected tombstoned update feed kind for `map`: {:?}",
5637                                        other
5638                                    ),
5639                                }
5640                            }
5641                            (in_repr, out_repr) => panic!(
5642                                "map may not change the update feed representation ({:?} -> {:?})",
5643                                in_repr, out_repr
5644                            ),
5645                        };
5646
5647                        match builders_or_callback {
5648                            BuildersOrCallback::Builders(graph_builders) => {
5649                                graph_builders.add_dfir_at(
5650                                    &out_location,
5651                                    parse_quote! {
5652                                        #map_ident = #input_ident -> #map_op;
5653                                    },
5654                                    Some(&stmt_id.to_string()),
5655                                );
5656                            }
5657                            BuildersOrCallback::Callback(_, node_callback) => {
5658                                node_callback(node, next_stmt_id);
5659                            }
5660                        }
5661
5662                        ident_stack.push(map_ident);
5663                    }
5664
5665                    HydroNode::FlatMap { f, input, metadata } => {
5666                        let input_ident = ident_stack.pop().unwrap();
5667                        let f_tokens = f.emit_tokens(&mut ident_stack);
5668
5669                        let input_ident = maybe_observe_for_mut(
5670                            f, input_ident,
5671                            &input.metadata().location_id,
5672                            &input.metadata().collection_kind,
5673                            &metadata.op,
5674                            builders_or_callback, next_stmt_id,
5675                        );
5676
5677                        let stmt_id = next_stmt_id.get_and_increment();
5678                        let flat_map_ident =
5679                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
5680
5681                        match builders_or_callback {
5682                            BuildersOrCallback::Builders(graph_builders) => {
5683                                graph_builders.add_dfir_at(
5684                                    &out_location,
5685                                    parse_quote! {
5686                                        #flat_map_ident = #input_ident -> flat_map(#f_tokens);
5687                                    },
5688                                    Some(&stmt_id.to_string()),
5689                                );
5690                            }
5691                            BuildersOrCallback::Callback(_, node_callback) => {
5692                                node_callback(node, next_stmt_id);
5693                            }
5694                        }
5695
5696                        ident_stack.push(flat_map_ident);
5697                    }
5698
5699                    HydroNode::FlatMapStreamBlocking { f, input, metadata } => {
5700                        let input_ident = ident_stack.pop().unwrap();
5701                        let f_tokens = f.emit_tokens(&mut ident_stack);
5702
5703                        let input_ident = maybe_observe_for_mut(
5704                            f, input_ident,
5705                            &input.metadata().location_id,
5706                            &input.metadata().collection_kind,
5707                            &metadata.op,
5708                            builders_or_callback, next_stmt_id,
5709                        );
5710
5711                        let stmt_id = next_stmt_id.get_and_increment();
5712                        let flat_map_stream_blocking_ident =
5713                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
5714
5715                        match builders_or_callback {
5716                            BuildersOrCallback::Builders(graph_builders) => {
5717                                graph_builders.add_dfir_at(
5718                                    &out_location,
5719                                    parse_quote! {
5720                                        #flat_map_stream_blocking_ident = #input_ident -> flat_map_stream_blocking(#f_tokens);
5721                                    },
5722                                    Some(&stmt_id.to_string()),
5723                                );
5724                            }
5725                            BuildersOrCallback::Callback(_, node_callback) => {
5726                                node_callback(node, next_stmt_id);
5727                            }
5728                        }
5729
5730                        ident_stack.push(flat_map_stream_blocking_ident);
5731                    }
5732
5733                    HydroNode::Filter { f, input, metadata } => {
5734                        let input_ident = ident_stack.pop().unwrap();
5735                        let f_tokens = f.emit_tokens(&mut ident_stack);
5736
5737                        let input_ident = maybe_observe_for_mut(
5738                            f, input_ident,
5739                            &input.metadata().location_id,
5740                            &input.metadata().collection_kind,
5741                            &metadata.op,
5742                            builders_or_callback, next_stmt_id,
5743                        );
5744
5745                        let stmt_id = next_stmt_id.get_and_increment();
5746                        let filter_ident =
5747                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
5748
5749                        // Filtering *state* (as opposed to events) makes absence explicit:
5750                        // - On a tombstoned update feed, each update's value is filtered, and a
5751                        //   filtered-out value becomes a tombstone — dropping the update
5752                        //   entirely would incorrectly leave the previous value observable.
5753                        // - A filter that takes a plain feed *into* a tombstoned feed (e.g.
5754                        //   `Singleton::filter` / `Optional::<InitNone>::filter` at the root,
5755                        //   which produce root unbounded optionals) emits an update for every
5756                        //   input value: `Some(v)` if it passes, a `None` tombstone if not.
5757                        let filter_op: TokenStream = match (
5758                            update_feed_repr(input.metadata()),
5759                            update_feed_repr(metadata),
5760                        ) {
5761                            (UpdateFeedRepr::Plain, UpdateFeedRepr::Plain) => {
5762                                quote! { filter(#f_tokens) }
5763                            }
5764                            (UpdateFeedRepr::Plain, UpdateFeedRepr::Tombstoned) => {
5765                                match &metadata.collection_kind {
5766                                    CollectionKind::Optional { .. } => {
5767                                        quote! {
5768                                            map({
5769                                                let mut __hydro_filter_f = #f_tokens;
5770                                                move |__hydro_value| {
5771                                                    if (__hydro_filter_f)(&__hydro_value) {
5772                                                        Some(__hydro_value)
5773                                                    } else {
5774                                                        None
5775                                                    }
5776                                                }
5777                                            })
5778                                        }
5779                                    }
5780                                    // `KeyedSingleton::filter` preserves the bound (`B -> B`),
5781                                    // so a plain keyed feed can never filter into a tombstoned
5782                                    // one.
5783                                    other => panic!(
5784                                        "unexpected tombstoned update feed kind for `filter`: {:?}",
5785                                        other
5786                                    ),
5787                                }
5788                            }
5789                            (UpdateFeedRepr::Tombstoned, UpdateFeedRepr::Tombstoned) => {
5790                                match &metadata.collection_kind {
5791                                    CollectionKind::Optional { .. } => {
5792                                        quote! {
5793                                            map({
5794                                                let mut __hydro_filter_f = #f_tokens;
5795                                                move |__hydro_update: Option<_>| {
5796                                                    __hydro_update.filter(|__hydro_value| (__hydro_filter_f)(__hydro_value))
5797                                                }
5798                                            })
5799                                        }
5800                                    }
5801                                    CollectionKind::KeyedSingleton { .. } => {
5802                                        // The inner closure filters plain `(K, V)` entries by
5803                                        // reference; a filtered-out entry tombstones its key.
5804                                        quote! {
5805                                            map({
5806                                                let mut __hydro_filter_f = #f_tokens;
5807                                                move |(__hydro_key, __hydro_update)| match __hydro_update {
5808                                                    ::std::option::Option::Some(__hydro_value) => {
5809                                                        let __hydro_entry = (__hydro_key, __hydro_value);
5810                                                        if (__hydro_filter_f)(&__hydro_entry) {
5811                                                            let (__hydro_key, __hydro_value) = __hydro_entry;
5812                                                            (__hydro_key, ::std::option::Option::Some(__hydro_value))
5813                                                        } else {
5814                                                            let (__hydro_key, _) = __hydro_entry;
5815                                                            (__hydro_key, ::std::option::Option::None)
5816                                                        }
5817                                                    }
5818                                                    ::std::option::Option::None => {
5819                                                        (__hydro_key, ::std::option::Option::None)
5820                                                    }
5821                                                }
5822                                            })
5823                                        }
5824                                    }
5825                                    other => panic!(
5826                                        "unexpected tombstoned update feed kind for `filter`: {:?}",
5827                                        other
5828                                    ),
5829                                }
5830                            }
5831                            (in_repr, out_repr) => panic!(
5832                                "filter may not un-tombstone an update feed ({:?} -> {:?})",
5833                                in_repr, out_repr
5834                            ),
5835                        };
5836
5837                        match builders_or_callback {
5838                            BuildersOrCallback::Builders(graph_builders) => {
5839                                graph_builders.add_dfir_at(
5840                                    &out_location,
5841                                    parse_quote! {
5842                                        #filter_ident = #input_ident -> #filter_op;
5843                                    },
5844                                    Some(&stmt_id.to_string()),
5845                                );
5846                            }
5847                            BuildersOrCallback::Callback(_, node_callback) => {
5848                                node_callback(node, next_stmt_id);
5849                            }
5850                        }
5851
5852                        ident_stack.push(filter_ident);
5853                    }
5854
5855                    HydroNode::FilterMap { f, input, metadata } => {
5856                        let input_ident = ident_stack.pop().unwrap();
5857                        let f_tokens = f.emit_tokens(&mut ident_stack);
5858
5859                        let input_ident = maybe_observe_for_mut(
5860                            f, input_ident,
5861                            &input.metadata().location_id,
5862                            &input.metadata().collection_kind,
5863                            &metadata.op,
5864                            builders_or_callback, next_stmt_id,
5865                        );
5866
5867                        let stmt_id = next_stmt_id.get_and_increment();
5868                        let filter_map_ident =
5869                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
5870
5871                        // See the `Filter` arm: filtering state makes absence explicit.
5872                        // - Plain -> tombstoned (e.g. `Singleton::filter_map` /
5873                        //   `Optional::<InitNone>::filter_map` at the root): `f` already returns
5874                        //   `Option<U>`, which is exactly the update record: `map(f)`.
5875                        // - Tombstoned -> tombstoned: apply `f` to the value of each update;
5876                        //   both "was a tombstone" and "filtered out" yield a tombstone. For
5877                        //   keyed feeds the inner closure consumes the `(K, V)` entry, so the
5878                        //   key is cloned up front to tombstone filtered-out entries
5879                        //   (generated code requires `K: Clone`).
5880                        let filter_map_op: TokenStream = match (
5881                            update_feed_repr(input.metadata()),
5882                            update_feed_repr(metadata),
5883                        ) {
5884                            (UpdateFeedRepr::Plain, UpdateFeedRepr::Plain) => {
5885                                quote! { filter_map(#f_tokens) }
5886                            }
5887                            (UpdateFeedRepr::Plain, UpdateFeedRepr::Tombstoned) => {
5888                                match &metadata.collection_kind {
5889                                    CollectionKind::Optional { .. } => {
5890                                        quote! { map(#f_tokens) }
5891                                    }
5892                                    // `KeyedSingleton::filter_map` erases monotonicity but
5893                                    // never *introduces* `Unbounded` (`EraseMonotonic` of the
5894                                    // plain keyed kinds is itself plain), so a plain keyed
5895                                    // feed can never filter-map into a tombstoned one.
5896                                    other => panic!(
5897                                        "unexpected tombstoned update feed kind for `filter_map`: {:?}",
5898                                        other
5899                                    ),
5900                                }
5901                            }
5902                            (UpdateFeedRepr::Tombstoned, UpdateFeedRepr::Tombstoned) => {
5903                                match &metadata.collection_kind {
5904                                    CollectionKind::Optional { .. } => {
5905                                        quote! {
5906                                            map({
5907                                                let mut __hydro_filter_map_f = #f_tokens;
5908                                                move |__hydro_update| {
5909                                                    __hydro_update.and_then(&mut __hydro_filter_map_f)
5910                                                }
5911                                            })
5912                                        }
5913                                    }
5914                                    CollectionKind::KeyedSingleton { .. } => {
5915                                        quote! {
5916                                            map({
5917                                                let mut __hydro_filter_map_f = #f_tokens;
5918                                                move |(__hydro_key, __hydro_update)| match __hydro_update {
5919                                                    ::std::option::Option::Some(__hydro_value) => {
5920                                                        let __hydro_key_backup =
5921                                                            ::std::clone::Clone::clone(&__hydro_key);
5922                                                        match (__hydro_filter_map_f)((__hydro_key, __hydro_value)) {
5923                                                            ::std::option::Option::Some((__hydro_out_key, __hydro_out_value)) => {
5924                                                                (__hydro_out_key, ::std::option::Option::Some(__hydro_out_value))
5925                                                            }
5926                                                            ::std::option::Option::None => {
5927                                                                (__hydro_key_backup, ::std::option::Option::None)
5928                                                            }
5929                                                        }
5930                                                    }
5931                                                    ::std::option::Option::None => {
5932                                                        (__hydro_key, ::std::option::Option::None)
5933                                                    }
5934                                                }
5935                                            })
5936                                        }
5937                                    }
5938                                    other => panic!(
5939                                        "unexpected tombstoned update feed kind for `filter_map`: {:?}",
5940                                        other
5941                                    ),
5942                                }
5943                            }
5944                            (in_repr, out_repr) => panic!(
5945                                "filter_map may not un-tombstone an update feed ({:?} -> {:?})",
5946                                in_repr, out_repr
5947                            ),
5948                        };
5949
5950                        match builders_or_callback {
5951                            BuildersOrCallback::Builders(graph_builders) => {
5952                                graph_builders.add_dfir_at(
5953                                    &out_location,
5954                                    parse_quote! {
5955                                        #filter_map_ident = #input_ident -> #filter_map_op;
5956                                    },
5957                                    Some(&stmt_id.to_string()),
5958                                );
5959                            }
5960                            BuildersOrCallback::Callback(_, node_callback) => {
5961                                node_callback(node, next_stmt_id);
5962                            }
5963                        }
5964
5965                        ident_stack.push(filter_map_ident);
5966                    }
5967
5968                    HydroNode::Sort { .. } => {
5969                        let input_ident = ident_stack.pop().unwrap();
5970
5971                        let stmt_id = next_stmt_id.get_and_increment();
5972                        let sort_ident =
5973                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
5974
5975                        match builders_or_callback {
5976                            BuildersOrCallback::Builders(graph_builders) => {
5977                                graph_builders.add_dfir_at(
5978                                    &out_location,
5979                                    parse_quote! {
5980                                        #sort_ident = #input_ident -> sort();
5981                                    },
5982                                    Some(&stmt_id.to_string()),
5983                                );
5984                            }
5985                            BuildersOrCallback::Callback(_, node_callback) => {
5986                                node_callback(node, next_stmt_id);
5987                            }
5988                        }
5989
5990                        ident_stack.push(sort_ident);
5991                    }
5992
5993                    HydroNode::DeferTick { metadata, .. } => {
5994                        let input_ident = ident_stack.pop().unwrap();
5995
5996                        let stmt_id = next_stmt_id.get_and_increment();
5997                        let defer_tick_ident =
5998                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
5999
6000                        match builders_or_callback {
6001                            BuildersOrCallback::Builders(graph_builders) => {
6002                                let stmt: dfir_lang::parse::DfirCode = if metadata.location_id.is_root() {
6003                                    // A top-level defer is a root-level DFIR `defer_tick()`: it is
6004                                    // non-lazy, so deferred elements schedule the next DFIR tick
6005                                    // on their own (there is no tick region to fire otherwise).
6006                                    parse_quote! {
6007                                        #defer_tick_ident = #input_ident -> defer_tick();
6008                                    }
6009                                } else {
6010                                    // Inside a tick, deferred data must not fire the tick by
6011                                    // itself, so the defer is lazy.
6012                                    parse_quote! {
6013                                        #defer_tick_ident = #input_ident -> defer_tick_lazy();
6014                                    }
6015                                };
6016                                graph_builders.add_dfir_at(
6017                                    &out_location,
6018                                    stmt,
6019                                    Some(&stmt_id.to_string()),
6020                                );
6021                            }
6022                            BuildersOrCallback::Callback(_, node_callback) => {
6023                                node_callback(node, next_stmt_id);
6024                            }
6025                        }
6026
6027                        ident_stack.push(defer_tick_ident);
6028                    }
6029
6030                    HydroNode::Enumerate { input, .. } => {
6031                        let input_ident = ident_stack.pop().unwrap();
6032
6033                        let stmt_id = next_stmt_id.get_and_increment();
6034                        let enumerate_ident =
6035                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
6036
6037                        match builders_or_callback {
6038                            BuildersOrCallback::Builders(graph_builders) => {
6039                                let lifetime = if input.metadata().location_id.is_top_level() {
6040                                    graph_builders.cross_tick_state_lifetime(&out_location)
6041                                } else {
6042                                    graph_builders.tick_state_lifetime(&out_location)
6043                                };
6044                                graph_builders.add_dfir_at(
6045                                    &out_location,
6046                                    parse_quote! {
6047                                        #enumerate_ident = #input_ident -> enumerate::<#lifetime>();
6048                                    },
6049                                    Some(&stmt_id.to_string()),
6050                                );
6051                            }
6052                            BuildersOrCallback::Callback(_, node_callback) => {
6053                                node_callback(node, next_stmt_id);
6054                            }
6055                        }
6056
6057                        ident_stack.push(enumerate_ident);
6058                    }
6059
6060                    HydroNode::Inspect { f, input, metadata } => {
6061                        let input_ident = ident_stack.pop().unwrap();
6062                        let f_tokens = f.emit_tokens(&mut ident_stack);
6063
6064                        let input_ident = maybe_observe_for_mut(
6065                            f, input_ident,
6066                            &input.metadata().location_id,
6067                            &input.metadata().collection_kind,
6068                            &metadata.op,
6069                            builders_or_callback, next_stmt_id,
6070                        );
6071
6072                        let stmt_id = next_stmt_id.get_and_increment();
6073                        let inspect_ident =
6074                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
6075
6076                        // A tombstoned update feed (root unbounded Optional/KeyedSingleton)
6077                        // cannot reach this arm today: no `Optional`/`Singleton` API
6078                        // constructs `Inspect` nodes, and `KeyedSingleton::inspect` /
6079                        // `inspect_with_key` are only available for `ValueBound = Bounded`
6080                        // kinds (`BoundedValue`/`Bounded`), which keep the plain entry
6081                        // representation. Guard against silently inspecting raw update
6082                        // records if a future API change makes this reachable.
6083                        if update_feed_repr(input.metadata()) == UpdateFeedRepr::Tombstoned
6084                            || update_feed_repr(metadata) == UpdateFeedRepr::Tombstoned
6085                        {
6086                            todo!(
6087                                "`inspect` on a tombstoned update feed (root unbounded \
6088                                 Optional/KeyedSingleton) is not yet supported"
6089                            );
6090                        }
6091
6092                        match builders_or_callback {
6093                            BuildersOrCallback::Builders(graph_builders) => {
6094                                graph_builders.add_dfir_at(
6095                                    &out_location,
6096                                    parse_quote! {
6097                                        #inspect_ident = #input_ident -> inspect(#f_tokens);
6098                                    },
6099                                    Some(&stmt_id.to_string()),
6100                                );
6101                            }
6102                            BuildersOrCallback::Callback(_, node_callback) => {
6103                                node_callback(node, next_stmt_id);
6104                            }
6105                        }
6106
6107                        ident_stack.push(inspect_ident);
6108                    }
6109
6110                    HydroNode::Unique { input, .. } => {
6111                        let input_ident = ident_stack.pop().unwrap();
6112
6113                        let stmt_id = next_stmt_id.get_and_increment();
6114                        let unique_ident =
6115                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
6116
6117                        match builders_or_callback {
6118                            BuildersOrCallback::Builders(graph_builders) => {
6119                                let lifetime = if input.metadata().location_id.is_top_level() {
6120                                    graph_builders.cross_tick_state_lifetime(&out_location)
6121                                } else {
6122                                    graph_builders.tick_state_lifetime(&out_location)
6123                                };
6124
6125                                graph_builders.add_dfir_at(
6126                                    &out_location,
6127                                    parse_quote! {
6128                                        #unique_ident = #input_ident -> unique::<#lifetime>();
6129                                    },
6130                                    Some(&stmt_id.to_string()),
6131                                );
6132                            }
6133                            BuildersOrCallback::Callback(_, node_callback) => {
6134                                node_callback(node, next_stmt_id);
6135                            }
6136                        }
6137
6138                        ident_stack.push(unique_ident);
6139                    }
6140
6141                    HydroNode::Fold { .. } | HydroNode::FoldKeyed { .. } | HydroNode::Scan { .. } | HydroNode::ScanAsyncBlocking { .. } => {
6142                        let operator: syn::Ident = if let HydroNode::Fold { input, .. } = node {
6143                            if input.metadata().location_id.is_root()
6144                                && input.metadata().collection_kind.is_bounded()
6145                            {
6146                                parse_quote!(fold_no_replay)
6147                            } else {
6148                                parse_quote!(fold)
6149                            }
6150                        } else if matches!(node, HydroNode::Scan { .. }) {
6151                            parse_quote!(scan)
6152                        } else if matches!(node, HydroNode::ScanAsyncBlocking { .. }) {
6153                            parse_quote!(scan_async_blocking)
6154                        } else if let HydroNode::FoldKeyed { input, .. } = node {
6155                            if input.metadata().location_id.is_root()
6156                                && input.metadata().collection_kind.is_bounded()
6157                            {
6158                                todo!("Fold keyed on a top-level bounded collection is not yet supported")
6159                            } else {
6160                                parse_quote!(fold_keyed)
6161                            }
6162                        } else {
6163                            unreachable!()
6164                        };
6165
6166                        let (HydroNode::Fold { input, .. }
6167                        | HydroNode::FoldKeyed { input, .. }
6168                        | HydroNode::Scan { input, .. }
6169                        | HydroNode::ScanAsyncBlocking { input, .. }) = node
6170                        else {
6171                            unreachable!()
6172                        };
6173
6174                        let input_top_level = input.metadata().location_id.is_top_level();
6175
6176                        let input_ident = ident_stack.pop().unwrap();
6177
6178                        let (HydroNode::Fold { init, acc, .. }
6179                        | HydroNode::FoldKeyed { init, acc, .. }
6180                        | HydroNode::Scan { init, acc, .. }
6181                        | HydroNode::ScanAsyncBlocking { init, acc, .. }) = &*node
6182                        else {
6183                            unreachable!()
6184                        };
6185
6186                        let acc_tokens = acc.emit_tokens(&mut ident_stack);
6187                        let init_tokens = init.emit_tokens(&mut ident_stack);
6188
6189                        let stmt_id = next_stmt_id.get_and_increment();
6190                        let fold_ident =
6191                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
6192
6193                        match builders_or_callback {
6194                            BuildersOrCallback::Builders(graph_builders) => {
6195                                let lifetime = if input_top_level {
6196                                    graph_builders.cross_tick_state_lifetime(&out_location)
6197                                } else {
6198                                    graph_builders.tick_state_lifetime(&out_location)
6199                                };
6200
6201                                if matches!(node, HydroNode::Fold { .. })
6202                                    && node.metadata().location_id.is_root()
6203                                    && !graph_builders.singleton_intermediates()
6204                                    && !node.metadata().collection_kind.is_bounded()
6205                                {
6206                                    // At the root, the singleton is an update feed: `fold_no_replay`
6207                                    // emits the initial value once (it always emits on the first
6208                                    // tick, even with no input), then the accumulator only on ticks
6209                                    // with new input (consumers hold the latest update), instead of
6210                                    // replaying it on every tick.
6211                                    graph_builders.add_dfir_at(
6212                                        &out_location,
6213                                        parse_quote! {
6214                                            #fold_ident = #input_ident -> fold_no_replay::<#lifetime>(#init_tokens, #acc_tokens);
6215                                        },
6216                                        Some(&stmt_id.to_string()),
6217                                    );
6218                                } else if matches!(node, HydroNode::Fold { .. })
6219                                    && node.metadata().location_id.is_root()
6220                                    && graph_builders.singleton_intermediates()
6221                                    && !node.metadata().collection_kind.is_bounded()
6222                                {
6223                                    let HydroNode::Fold { input, .. } = &*node else { unreachable!() };
6224                                    let hooked_input_ident = graph_builders.emit_fold_hook(
6225                                        &input.metadata().location_id,
6226                                        &input_ident,
6227                                        &input.metadata().collection_kind,
6228                                        &node.metadata().op,
6229                                    );
6230
6231                                    let (effective_input, wrapped_acc) = if let Some(ref hooked) = hooked_input_ident {
6232                                        let acc: syn::Expr = parse_quote!({
6233                                            let mut __inner = #acc_tokens;
6234                                            move |__state, __batch: Vec<_>| {
6235                                                if __batch.is_empty() {
6236                                                    return None;
6237                                                }
6238                                                for __value in __batch {
6239                                                    __inner(__state, __value);
6240                                                }
6241                                                Some(__state.clone())
6242                                            }
6243                                        });
6244                                        (hooked, acc)
6245                                    } else {
6246                                        let acc: syn::Expr = parse_quote!({
6247                                            let mut __inner = #acc_tokens;
6248                                            move |__state, __value| {
6249                                                __inner(__state, __value);
6250                                                Some(__state.clone())
6251                                            }
6252                                        });
6253                                        (&input_ident, acc)
6254                                    };
6255
6256                                    graph_builders.add_dfir_at(
6257                                        &out_location,
6258                                        parse_quote! {
6259                                            source_iter([(#init_tokens)()]) -> [0]#fold_ident;
6260                                            #effective_input -> scan::<#lifetime>(#init_tokens, #wrapped_acc) -> [1]#fold_ident;
6261                                            #fold_ident = chain();
6262                                        },
6263                                        Some(&stmt_id.to_string()),
6264                                    );
6265
6266                                    // A *scripted* fold releases exactly one element per
6267                                    // decision, producing one new version per release, so
6268                                    // its snapshot takes the ordinary (scriptable) path
6269                                    // rather than the fuzz-passthrough shortcut.
6270                                    if hooked_input_ident.is_some()
6271                                        && node.metadata().op.sim_hook_id.is_none()
6272                                    {
6273                                        fold_hooked_idents.insert(fold_ident.to_string());
6274                                    }
6275                                } else if matches!(node, HydroNode::FoldKeyed { .. })
6276                                    && node.metadata().location_id.is_root()
6277                                    && !node.metadata().collection_kind.is_bounded()
6278                                {
6279                                    // At the root, the keyed singleton is an update feed: emit only
6280                                    // the entry each input updates (consumers hold the latest value
6281                                    // per key), not every entry every tick. (In production
6282                                    // `emit_fold_hook` is a no-op.)
6283                                    let HydroNode::FoldKeyed { input, .. } = &*node else { unreachable!() };
6284                                    let root = crate::staging_util::get_this_crate();
6285                                    let hooked_input_ident = graph_builders.emit_fold_hook(
6286                                        &input.metadata().location_id,
6287                                        &input_ident,
6288                                        &input.metadata().collection_kind,
6289                                        &node.metadata().op,
6290                                    );
6291
6292                                    let wrapped_acc: syn::Expr = parse_quote!({
6293                                        let mut __init = #init_tokens;
6294                                        let mut __inner = #acc_tokens;
6295                                        move |__state, __kv: (_, _)| {
6296                                            // TODO(shadaj): we can avoid the clone when the entry exists
6297                                            let __state = __state
6298                                                .entry(::std::clone::Clone::clone(&__kv.0))
6299                                                .or_insert_with(&__init);
6300                                            __inner(__state, __kv.1);
6301                                            Some((__kv.0, ::std::clone::Clone::clone(&*__state)))
6302                                        }
6303                                    });
6304
6305                                    if let Some(hooked_input_ident) = hooked_input_ident {
6306                                        graph_builders.add_dfir_at(
6307                                            &out_location,
6308                                            parse_quote! {
6309                                                #fold_ident = #hooked_input_ident -> flatten() -> scan::<#lifetime>(|| #root::runtime_support::dfir_rs::rustc_hash::FxHashMap::default(), #wrapped_acc);
6310                                            },
6311                                            Some(&stmt_id.to_string()),
6312                                        );
6313
6314                                        fold_hooked_idents.insert(fold_ident.to_string());
6315                                    } else {
6316                                        graph_builders.add_dfir_at(
6317                                            &out_location,
6318                                            parse_quote! {
6319                                                #fold_ident = #input_ident -> scan::<#lifetime>(|| #root::runtime_support::dfir_rs::rustc_hash::FxHashMap::default(), #wrapped_acc);
6320                                            },
6321                                            Some(&stmt_id.to_string()),
6322                                        );
6323                                    }
6324                                } else if (matches!(node, HydroNode::Fold { .. })
6325                                    || matches!(node, HydroNode::FoldKeyed { .. }))
6326                                    && !node.metadata().location_id.is_top_level()
6327                                    && graph_builders.singleton_intermediates()
6328                                {
6329                                    let input_ref = match &*node {
6330                                        HydroNode::Fold { input, .. } => input,
6331                                        HydroNode::FoldKeyed { input, .. } => input,
6332                                        _ => unreachable!(),
6333                                    };
6334                                    let hooked_input_ident = graph_builders.emit_fold_hook(
6335                                        &input_ref.metadata().location_id,
6336                                        &input_ident,
6337                                        &input_ref.metadata().collection_kind,
6338                                        &node.metadata().op,
6339                                    );
6340
6341                                    let actual_input = hooked_input_ident.as_ref().unwrap_or(&input_ident);
6342                                    graph_builders.add_dfir_at(
6343                                        &out_location,
6344                                        parse_quote! {
6345                                            #fold_ident = #actual_input -> #operator::<#lifetime>(#init_tokens, #acc_tokens);
6346                                        },
6347                                        Some(&stmt_id.to_string()),
6348                                    );
6349                                } else {
6350                                    // No `fold`-family API currently produces a root unbounded
6351                                    // (tombstoned) keyed singleton (`KeyedStream::fold` yields
6352                                    // monotone keyed bounds), so there are no update records to
6353                                    // wrap here; fail loudly if that ever changes rather than
6354                                    // emitting plain entries onto a tombstoned feed.
6355                                    assert_eq!(
6356                                        update_feed_repr(node.metadata()),
6357                                        UpdateFeedRepr::Plain,
6358                                        "`fold`-family aggregation into a tombstoned update feed \
6359                                         (root unbounded Optional/KeyedSingleton) is not supported"
6360                                    );
6361                                    graph_builders.add_dfir_at(
6362                                        &out_location,
6363                                        parse_quote! {
6364                                            #fold_ident = #input_ident -> #operator::<#lifetime>(#init_tokens, #acc_tokens);
6365                                        },
6366                                        Some(&stmt_id.to_string()),
6367                                    );
6368                                }
6369                            }
6370                            BuildersOrCallback::Callback(_, node_callback) => {
6371                                node_callback(node, next_stmt_id);
6372                            }
6373                        }
6374
6375                        ident_stack.push(fold_ident);
6376                    }
6377
6378                    HydroNode::Reduce { .. } | HydroNode::ReduceKeyed { .. } => {
6379                        let operator: syn::Ident = if let HydroNode::Reduce { input, .. } = node {
6380                            // At the root, the result is an update feed: emit it only on ticks with
6381                            // new input (consumers hold the latest update), bounded or not.
6382                            if input.metadata().location_id.is_root() {
6383                                parse_quote!(reduce_no_replay)
6384                            } else {
6385                                parse_quote!(reduce)
6386                            }
6387                        } else if let HydroNode::ReduceKeyed { input, .. } = node {
6388                            if input.metadata().location_id.is_root()
6389                                && input.metadata().collection_kind.is_bounded()
6390                            {
6391                                todo!(
6392                                    "Calling keyed reduce on a top-level bounded collection is not supported"
6393                                )
6394                            } else {
6395                                parse_quote!(reduce_keyed)
6396                            }
6397                        } else {
6398                            unreachable!()
6399                        };
6400
6401                        let (HydroNode::Reduce { input, .. } | HydroNode::ReduceKeyed { input, .. }) = node
6402                        else {
6403                            unreachable!()
6404                        };
6405
6406                        let input_top_level = input.metadata().location_id.is_top_level();
6407
6408                        let input_ident = ident_stack.pop().unwrap();
6409
6410                        let (HydroNode::Reduce { f, .. } | HydroNode::ReduceKeyed { f, .. }) = &*node
6411                        else {
6412                            unreachable!()
6413                        };
6414
6415                        let f_tokens = f.emit_tokens(&mut ident_stack);
6416
6417                        let stmt_id = next_stmt_id.get_and_increment();
6418                        let reduce_ident =
6419                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
6420
6421                        match builders_or_callback {
6422                            BuildersOrCallback::Builders(graph_builders) => {
6423                                let lifetime = if input_top_level {
6424                                    graph_builders.cross_tick_state_lifetime(&out_location)
6425                                } else {
6426                                    graph_builders.tick_state_lifetime(&out_location)
6427                                };
6428
6429                                if matches!(node, HydroNode::Reduce { .. })
6430                                    && node.metadata().location_id.is_root()
6431                                    && graph_builders.singleton_intermediates()
6432                                    && !node.metadata().collection_kind.is_bounded()
6433                                {
6434                                    todo!(
6435                                        "Reduce with optional intermediates is not yet supported in simulator"
6436                                    );
6437                                } else if matches!(node, HydroNode::ReduceKeyed { .. })
6438                                    && node.metadata().location_id.is_root()
6439                                    && graph_builders.singleton_intermediates()
6440                                    && !node.metadata().collection_kind.is_bounded()
6441                                {
6442                                    todo!(
6443                                        "Reduce keyed with optional intermediates is not yet supported in simulator"
6444                                    );
6445                                } else {
6446                                    // A root unbounded keyed singleton is a tombstoned
6447                                    // `(K, Option<V>)` update feed: wrap each emitted entry as
6448                                    // an upsert. (`reduce_keyed` never removes keys, so no
6449                                    // tombstones are needed.)
6450                                    let wrap_op: TokenStream = if matches!(
6451                                        node.metadata().collection_kind,
6452                                        CollectionKind::KeyedSingleton { .. }
6453                                    ) && update_feed_repr(node.metadata())
6454                                        == UpdateFeedRepr::Tombstoned
6455                                    {
6456                                        quote! { -> map(|(__hydro_key, __hydro_value)| (__hydro_key, ::std::option::Option::Some(__hydro_value))) }
6457                                    } else {
6458                                        quote! {}
6459                                    };
6460                                    if matches!(node, HydroNode::ReduceKeyed { .. })
6461                                        && node.metadata().location_id.is_root()
6462                                        && !node.metadata().collection_kind.is_bounded()
6463                                    {
6464                                        let root = crate::staging_util::get_this_crate();
6465                                        // At the root, the keyed singleton is an update feed:
6466                                        // emit only the entry each input updates (consumers hold
6467                                        // the latest value per key), not every entry every tick.
6468                                        graph_builders.add_dfir_at(
6469                                            &out_location,
6470                                            parse_quote! {
6471                                                #reduce_ident = #input_ident -> scan::<#lifetime>(
6472                                                    || #root::runtime_support::dfir_rs::rustc_hash::FxHashMap::default(),
6473                                                    {
6474                                                        let __reduce_keyed_fn = #f_tokens;
6475                                                        move |__state, (__key, __value)| {
6476                                                            let __acc = match __state.entry(::std::clone::Clone::clone(&__key)) {
6477                                                                ::std::collections::hash_map::Entry::Occupied(e) => {
6478                                                                    let __acc = e.into_mut();
6479                                                                    __reduce_keyed_fn(__acc, __value);
6480                                                                    __acc
6481                                                                }
6482                                                                ::std::collections::hash_map::Entry::Vacant(e) => e.insert(__value),
6483                                                            };
6484                                                            Some((__key, ::std::clone::Clone::clone(&*__acc)))
6485                                                        }
6486                                                    },
6487                                                ) #wrap_op;
6488                                            },
6489                                            Some(&stmt_id.to_string()),
6490                                        );
6491                                    } else {
6492                                        graph_builders.add_dfir_at(
6493                                            &out_location,
6494                                            parse_quote! {
6495                                                #reduce_ident = #input_ident -> #operator::<#lifetime>(#f_tokens) #wrap_op;
6496                                            },
6497                                            Some(&stmt_id.to_string()),
6498                                        );
6499                                    }
6500                                }
6501                            }
6502                            BuildersOrCallback::Callback(_, node_callback) => {
6503                                node_callback(node, next_stmt_id);
6504                            }
6505                        }
6506
6507                        ident_stack.push(reduce_ident);
6508                    }
6509
6510                      HydroNode::ReduceKeyedWatermark {
6511                          f,
6512                          input,
6513                          watermark,
6514                          metadata,
6515                      } => {
6516
6517                          // watermark is processed second, so it's on top
6518                          let watermark_ident = ident_stack.pop().unwrap();
6519                          let watermark_location = watermark.metadata().location_id.clone();
6520                          let input_ident = ident_stack.pop().unwrap();
6521                          let f_tokens = f.emit_tokens(&mut ident_stack);
6522
6523                        let stmt_id = next_stmt_id.get_and_increment();
6524                        let chain_ident = syn::Ident::new(
6525                            &format!("reduce_keyed_watermark_chain_{}", stmt_id),
6526                            Span::call_site(),
6527                        );
6528
6529                        let fold_ident =
6530                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
6531
6532                        let agg_operator: syn::Ident = if input.metadata().location_id.is_root()
6533                            && input.metadata().collection_kind.is_bounded()
6534                        {
6535                            parse_quote!(fold_no_replay)
6536                        } else {
6537                            parse_quote!(fold)
6538                        };
6539
6540                          match builders_or_callback {
6541                              BuildersOrCallback::Builders(graph_builders) => {
6542                                  // The watermark lives at its own (tick) location; if that is a
6543                                  // different loop context than where this reduce is emitted
6544                                  // (`out_location`), un-window it so the edge does not illegally
6545                                  // exit the loop.
6546                                  let watermark_ident = graph_builders.unwindow_for_consume(
6547                                      watermark_ident,
6548                                      &watermark_location,
6549                                      &out_location,
6550                                  );
6551
6552                                  let lifetime = if input.metadata().location_id.is_top_level() {
6553                                      graph_builders.cross_tick_state_lifetime(&out_location)
6554                                  } else {
6555                                      graph_builders.tick_state_lifetime(&out_location)
6556                                  };
6557
6558                                if metadata.location_id.is_root()
6559                                    && graph_builders.singleton_intermediates()
6560                                    && !metadata.collection_kind.is_bounded()
6561                                {
6562                                    todo!(
6563                                        "Reduce keyed watermarked on a top-level bounded collection is not yet supported"
6564                                    )
6565                                } else if update_feed_repr(metadata) == UpdateFeedRepr::Tombstoned {
6566                                    // A root unbounded keyed singleton is a tombstoned
6567                                    // `(K, Option<V>)` update feed (see
6568                                    // [`CollectionKind::root_repr_is_tombstoned_update_feed`]).
6569                                    // Instead of re-emitting the whole entry map, emit *deltas*:
6570                                    // each payload that lands in the map yields an upsert
6571                                    // `(k, Some(v))` with the key's new reduced value, and each
6572                                    // key garbage-collected by a watermark advance yields a
6573                                    // tombstone `(k, None)`. Downstream consumers reconstruct
6574                                    // the current map by applying updates (see
6575                                    // [`DfirBuilder::batch`]). Generated code requires
6576                                    // `K: Clone` and `V: Clone`, as the whole-map form below
6577                                    // does too (there the clones are hidden inside the `fold`
6578                                    // operator, which clones its accumulator — the entire map —
6579                                    // each time it emits downstream).
6580                                    graph_builders.add_dfir_at(
6581                                        &out_location,
6582                                        parse_quote! {
6583                                            #chain_ident = chain();
6584                                            #input_ident
6585                                                -> map(|x| (Some(x), None))
6586                                                -> [0]#chain_ident;
6587                                            #watermark_ident
6588                                                -> map(|watermark| (None, Some(watermark)))
6589                                                -> [1]#chain_ident;
6590
6591                                            #fold_ident = #chain_ident
6592                                                -> scan::<#lifetime>(|| (::std::collections::HashMap::new(), None), {
6593                                                    let __reduce_keyed_fn = #f_tokens;
6594                                                    move |(map, opt_curr_watermark), (opt_payload, opt_watermark)| {
6595                                                        let mut deltas = ::std::vec::Vec::new();
6596                                                        if let Some((k, v)) = opt_payload {
6597                                                            if let Some(curr_watermark) = *opt_curr_watermark {
6598                                                                if k < curr_watermark {
6599                                                                    return Some(deltas);
6600                                                                }
6601                                                            }
6602                                                            match map.entry(k) {
6603                                                                ::std::collections::hash_map::Entry::Vacant(e) => {
6604                                                                    let key = ::std::clone::Clone::clone(e.key());
6605                                                                    let value = ::std::clone::Clone::clone(e.insert(v));
6606                                                                    deltas.push((key, ::std::option::Option::Some(value)));
6607                                                                }
6608                                                                ::std::collections::hash_map::Entry::Occupied(mut e) => {
6609                                                                    __reduce_keyed_fn(e.get_mut(), v);
6610                                                                    deltas.push((
6611                                                                        ::std::clone::Clone::clone(e.key()),
6612                                                                        ::std::option::Option::Some(::std::clone::Clone::clone(e.get())),
6613                                                                    ));
6614                                                                }
6615                                                            }
6616                                                        } else {
6617                                                            let watermark = opt_watermark.unwrap();
6618                                                            if let Some(curr_watermark) = *opt_curr_watermark {
6619                                                                if watermark <= curr_watermark {
6620                                                                    return Some(deltas);
6621                                                                }
6622                                                            }
6623                                                            map.retain(|k, _| {
6624                                                                if *k >= watermark {
6625                                                                    true
6626                                                                } else {
6627                                                                    deltas.push((
6628                                                                        ::std::clone::Clone::clone(k),
6629                                                                        ::std::option::Option::None,
6630                                                                    ));
6631                                                                    false
6632                                                                }
6633                                                            });
6634                                                            *opt_curr_watermark = Some(watermark);
6635                                                        }
6636                                                        Some(deltas)
6637                                                    }
6638                                                })
6639                                                -> flatten();
6640                                        },
6641                                        Some(&stmt_id.to_string()),
6642                                    );
6643                                } else {
6644                                    graph_builders.add_dfir_at(
6645                                        &out_location,
6646                                        parse_quote! {
6647                                            #chain_ident = chain();
6648                                            #input_ident
6649                                                -> map(|x| (Some(x), None))
6650                                                -> [0]#chain_ident;
6651                                            #watermark_ident
6652                                                -> map(|watermark| (None, Some(watermark)))
6653                                                -> [1]#chain_ident;
6654
6655                                            #fold_ident = #chain_ident
6656                                                -> #agg_operator::<#lifetime>(|| (::std::collections::HashMap::new(), None), {
6657                                                    let __reduce_keyed_fn = #f_tokens;
6658                                                    move |(map, opt_curr_watermark), (opt_payload, opt_watermark)| {
6659                                                        if let Some((k, v)) = opt_payload {
6660                                                            if let Some(curr_watermark) = *opt_curr_watermark {
6661                                                                if k < curr_watermark {
6662                                                                    return;
6663                                                                }
6664                                                            }
6665                                                            match map.entry(k) {
6666                                                                ::std::collections::hash_map::Entry::Vacant(e) => {
6667                                                                    e.insert(v);
6668                                                                }
6669                                                                ::std::collections::hash_map::Entry::Occupied(mut e) => {
6670                                                                    __reduce_keyed_fn(e.get_mut(), v);
6671                                                                }
6672                                                            }
6673                                                        } else {
6674                                                            let watermark = opt_watermark.unwrap();
6675                                                            if let Some(curr_watermark) = *opt_curr_watermark {
6676                                                                if watermark <= curr_watermark {
6677                                                                    return;
6678                                                                }
6679                                                            }
6680                                                            map.retain(|k, _| *k >= watermark);
6681                                                            *opt_curr_watermark = Some(watermark);
6682                                                        }
6683                                                    }
6684                                                })
6685                                                -> flat_map(|(map, _curr_watermark)| map);
6686                                        },
6687                                        Some(&stmt_id.to_string()),
6688                                    );
6689                                }
6690                            }
6691                            BuildersOrCallback::Callback(_, node_callback) => {
6692                                node_callback(node, next_stmt_id);
6693                            }
6694                        }
6695
6696                        ident_stack.push(fold_ident);
6697                    }
6698
6699                    HydroNode::Network {
6700                        networking_info,
6701                        serialize,
6702                        deserialize,
6703                        instantiate_fn,
6704                        input,
6705                        ..
6706                    } => {
6707                        let input_ident = ident_stack.pop().unwrap();
6708
6709                        let stmt_id = next_stmt_id.get_and_increment();
6710                        let receiver_stream_ident =
6711                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
6712
6713                        // For embedded (external) serialization, this synthesizes only the
6714                        // member-id tag conversions (if any) and passes the raw payload through.
6715                        let serialize_pipeline = serialize.pipeline();
6716                        let deserialize_pipeline = deserialize.pipeline();
6717
6718                        match builders_or_callback {
6719                            BuildersOrCallback::Builders(graph_builders) => {
6720                                let (sink_expr, source_expr) = match instantiate_fn {
6721                                    DebugInstantiate::Building => (
6722                                        syn::parse_quote!(DUMMY_SINK),
6723                                        syn::parse_quote!(DUMMY_SOURCE),
6724                                    ),
6725
6726                                    DebugInstantiate::Finalized(finalized) => {
6727                                        (finalized.sink.clone(), finalized.source.clone())
6728                                    }
6729                                };
6730
6731                                graph_builders.create_network(
6732                                    &input.metadata().location_id,
6733                                    &out_location,
6734                                    input_ident,
6735                                    &receiver_stream_ident,
6736                                    serialize_pipeline.as_ref(),
6737                                    sink_expr,
6738                                    source_expr,
6739                                    deserialize_pipeline.as_ref(),
6740                                    serialize.external_element_type(),
6741                                    stmt_id,
6742                                    networking_info,
6743                                );
6744                            }
6745                            BuildersOrCallback::Callback(_, node_callback) => {
6746                                node_callback(node, next_stmt_id);
6747                            }
6748                        }
6749
6750                        ident_stack.push(receiver_stream_ident);
6751                    }
6752
6753                    HydroNode::ExternalInput {
6754                        instantiate_fn,
6755                        deserialize_fn: deserialize_pipeline,
6756                        ..
6757                    } => {
6758                        let stmt_id = next_stmt_id.get_and_increment();
6759                        let receiver_stream_ident =
6760                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
6761
6762                        match builders_or_callback {
6763                            BuildersOrCallback::Builders(graph_builders) => {
6764                                let (_, source_expr) = match instantiate_fn {
6765                                    DebugInstantiate::Building => (
6766                                        syn::parse_quote!(DUMMY_SINK),
6767                                        syn::parse_quote!(DUMMY_SOURCE),
6768                                    ),
6769
6770                                    DebugInstantiate::Finalized(finalized) => {
6771                                        (finalized.sink.clone(), finalized.source.clone())
6772                                    }
6773                                };
6774
6775                                graph_builders.create_external_source(
6776                                    &out_location,
6777                                    source_expr,
6778                                    &receiver_stream_ident,
6779                                    deserialize_pipeline.as_ref(),
6780                                    stmt_id,
6781                                );
6782                            }
6783                            BuildersOrCallback::Callback(_, node_callback) => {
6784                                node_callback(node, next_stmt_id);
6785                            }
6786                        }
6787
6788                        ident_stack.push(receiver_stream_ident);
6789                    }
6790
6791                    HydroNode::Counter {
6792                        tag,
6793                        duration,
6794                        prefix,
6795                        ..
6796                    } => {
6797                        let input_ident = ident_stack.pop().unwrap();
6798
6799                        let stmt_id = next_stmt_id.get_and_increment();
6800                        let counter_ident =
6801                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
6802
6803                        match builders_or_callback {
6804                            BuildersOrCallback::Builders(graph_builders) => {
6805                                let arg = format!("{}({})", prefix, tag);
6806                                graph_builders.add_dfir_at(
6807                                    &out_location,
6808                                    parse_quote! {
6809                                        #counter_ident = #input_ident -> _counter(#arg, #duration);
6810                                    },
6811                                    Some(&stmt_id.to_string()),
6812                                );
6813                            }
6814                            BuildersOrCallback::Callback(_, node_callback) => {
6815                                node_callback(node, next_stmt_id);
6816                            }
6817                        }
6818
6819                        ident_stack.push(counter_ident);
6820                    }
6821
6822                    HydroNode::VersionedNetworkFork {
6823                        channel_id,
6824                        senders,
6825                        metadata,
6826                        ..
6827                    } => {
6828                        // sender idents are pushed in order of the 'senders' member.
6829                        let split_at = ident_stack.len() - senders.len();
6830                        let sender_idents = ident_stack.split_off(split_at);
6831
6832                        let stmt_id = next_stmt_id.get_and_increment();
6833
6834                        // All senders share the channel, so the raw element type (for embedded
6835                        // serialization) is read from the first sender.
6836                        let external_element_type =
6837                            senders.first().and_then(|(_, _, s)| s.external_element_type());
6838
6839                        match builders_or_callback {
6840                            BuildersOrCallback::Builders(graph_builders) => {
6841                                let sender_args: Vec<(LocationId, syn::Ident, Option<DebugExpr>)> =
6842                                    senders
6843                                        .iter()
6844                                        .zip(sender_idents)
6845                                        .map(|((_version, sender, serialize), ident)| {
6846                                            (
6847                                                sender.metadata().location_id.clone(),
6848                                                ident,
6849                                                serialize.pipeline(),
6850                                            )
6851                                        })
6852                                        .collect();
6853                                graph_builders.create_versioned_network_fork(
6854                                    *channel_id,
6855                                    &metadata.location_id,
6856                                    sender_args,
6857                                    external_element_type,
6858                                    stmt_id,
6859                                );
6860                            }
6861                            BuildersOrCallback::Callback(_, node_callback) => {
6862                                node_callback(node, next_stmt_id);
6863                            }
6864                        }
6865                    }
6866
6867                    HydroNode::VersionedNetwork {
6868                        fork,
6869                        deserialize,
6870                        metadata,
6871                        ..
6872                    } => {
6873                        let stmt_id = next_stmt_id.get_and_increment();
6874                        let receiver_stream_ident =
6875                            syn::Ident::new(&format!("stream_{}", stmt_id), Span::call_site());
6876
6877                        // The wire element type is determined by the channel's *source* kind, which
6878                        // all senders share; read it from the shared fork's first sender.
6879                        let (channel_id, source_loc) = {
6880                            let fork_ref = fork.0.borrow();
6881                            let HydroNode::VersionedNetworkFork {
6882                                channel_id,
6883                                senders,
6884                                ..
6885                            } = &*fork_ref
6886                            else {
6887                                unreachable!("VersionedNetwork.fork must be a VersionedNetworkFork");
6888                            };
6889                            let source_loc = senders
6890                                .first()
6891                                .map(|(_v, sender, _s)| sender.metadata().location_id.clone())
6892                                .expect("a VersionedNetworkFork always has at least one sender");
6893                            (*channel_id, source_loc)
6894                        };
6895
6896                        let deserialize_pipeline = deserialize.pipeline();
6897                        let external_element_type = deserialize.external_element_type();
6898
6899                        match builders_or_callback {
6900                            BuildersOrCallback::Builders(graph_builders) => {
6901                                graph_builders.create_versioned_network(
6902                                    channel_id,
6903                                    &source_loc,
6904                                    &metadata.location_id,
6905                                    &receiver_stream_ident,
6906                                    deserialize_pipeline.as_ref(),
6907                                    external_element_type,
6908                                    stmt_id,
6909                                );
6910                            }
6911                            BuildersOrCallback::Callback(_, node_callback) => {
6912                                node_callback(node, next_stmt_id);
6913                            }
6914                        }
6915
6916                        ident_stack.push(receiver_stream_ident);
6917                    }
6918                }
6919            },
6920            seen_tees,
6921            false,
6922        );
6923
6924        let ret = ident_stack
6925            .pop()
6926            .expect("ident_stack should have exactly one element after traversal");
6927        assert!(
6928            ident_stack.is_empty(),
6929            "ident_stack should be empty after popping the final ident, but has {} remaining element(s). \
6930             This indicates a bug in the code gen: some node pushed idents that were never consumed.",
6931            ident_stack.len()
6932        );
6933        ret
6934    }
6935
6936    pub fn visit_debug_expr(&mut self, mut transform: impl FnMut(&mut DebugExpr)) {
6937        match self {
6938            HydroNode::Placeholder => {
6939                panic!()
6940            }
6941            HydroNode::Cast { .. }
6942            | HydroNode::CastUpdateStream { .. }
6943            | HydroNode::ObserveNonDet { .. }
6944            | HydroNode::UnboundSingleton { .. }
6945            | HydroNode::AssertIsConsistent { .. } => {}
6946            HydroNode::Source { source, .. } => match source {
6947                HydroSource::Stream(expr) | HydroSource::Iter(expr) => transform(expr),
6948                HydroSource::ExternalNetwork()
6949                | HydroSource::Spin()
6950                | HydroSource::ClusterMembers(_, _)
6951                | HydroSource::Embedded(_)
6952                | HydroSource::EmbeddedSingleton(_) => {} // TODO: what goes here?
6953            },
6954            HydroNode::SingletonSource { value, .. } => {
6955                transform(value);
6956            }
6957            HydroNode::CycleSource { .. }
6958            | HydroNode::Tee { .. }
6959            | HydroNode::Reference { .. }
6960            | HydroNode::YieldConcat { .. }
6961            | HydroNode::BeginAtomic { .. }
6962            | HydroNode::EndAtomic { .. }
6963            | HydroNode::Batch { .. }
6964            | HydroNode::Snapshot { .. }
6965            | HydroNode::Chain { .. }
6966            | HydroNode::MergeOrdered { .. }
6967            | HydroNode::ChainFirst { .. }
6968            | HydroNode::CrossProduct { .. }
6969            | HydroNode::CrossSingleton { .. }
6970            | HydroNode::ResolveFutures { .. }
6971            | HydroNode::ResolveFuturesBlocking { .. }
6972            | HydroNode::ResolveFuturesOrdered { .. }
6973            | HydroNode::Join { .. }
6974            | HydroNode::JoinHalf { .. }
6975            | HydroNode::Difference { .. }
6976            | HydroNode::AntiJoin { .. }
6977            | HydroNode::DeferTick { .. }
6978            | HydroNode::Enumerate { .. }
6979            | HydroNode::Unique { .. }
6980            | HydroNode::Sort { .. }
6981            | HydroNode::PartitionSide { .. }
6982            | HydroNode::VersionedNetworkFork { .. }
6983            | HydroNode::VersionedNetwork { .. } => {}
6984            HydroNode::Map { f, .. }
6985            | HydroNode::FlatMap { f, .. }
6986            | HydroNode::FlatMapStreamBlocking { f, .. }
6987            | HydroNode::Filter { f, .. }
6988            | HydroNode::FilterMap { f, .. }
6989            | HydroNode::Inspect { f, .. }
6990            | HydroNode::PartitionShared { f, .. }
6991            | HydroNode::Reduce { f, .. }
6992            | HydroNode::ReduceKeyed { f, .. }
6993            | HydroNode::ReduceKeyedWatermark { f, .. } => {
6994                transform(&mut f.expr);
6995            }
6996            HydroNode::Fold { init, acc, .. }
6997            | HydroNode::Scan { init, acc, .. }
6998            | HydroNode::ScanAsyncBlocking { init, acc, .. }
6999            | HydroNode::FoldKeyed { init, acc, .. } => {
7000                transform(&mut init.expr);
7001                transform(&mut acc.expr);
7002            }
7003            HydroNode::Network {
7004                serialize,
7005                deserialize,
7006                ..
7007            } => {
7008                if let NetworkSend::Custom {
7009                    serialize_fn: Some(serialize_fn),
7010                } = serialize
7011                {
7012                    transform(serialize_fn);
7013                }
7014                if let NetworkRecv::Custom {
7015                    deserialize_fn: Some(deserialize_fn),
7016                } = deserialize
7017                {
7018                    transform(deserialize_fn);
7019                }
7020            }
7021            HydroNode::ExternalInput { deserialize_fn, .. } => {
7022                if let Some(deserialize_fn) = deserialize_fn {
7023                    transform(deserialize_fn);
7024                }
7025            }
7026            HydroNode::Counter { duration, .. } => {
7027                transform(duration);
7028            }
7029        }
7030    }
7031
7032    pub fn op_metadata(&self) -> &HydroIrOpMetadata {
7033        &self.metadata().op
7034    }
7035
7036    pub fn metadata(&self) -> &HydroIrMetadata {
7037        match self {
7038            HydroNode::Placeholder => {
7039                panic!()
7040            }
7041            HydroNode::VersionedNetworkFork { metadata, .. }
7042            | HydroNode::VersionedNetwork { metadata, .. } => metadata,
7043            HydroNode::Cast { metadata, .. }
7044            | HydroNode::CastUpdateStream { metadata, .. }
7045            | HydroNode::ObserveNonDet { metadata, .. }
7046            | HydroNode::AssertIsConsistent { metadata, .. }
7047            | HydroNode::UnboundSingleton { metadata, .. }
7048            | HydroNode::Source { metadata, .. }
7049            | HydroNode::SingletonSource { metadata, .. }
7050            | HydroNode::CycleSource { metadata, .. }
7051            | HydroNode::Tee { metadata, .. }
7052            | HydroNode::Reference { metadata, .. }
7053            | HydroNode::PartitionSide { metadata, .. }
7054            | HydroNode::PartitionShared { metadata, .. }
7055            | HydroNode::YieldConcat { metadata, .. }
7056            | HydroNode::BeginAtomic { metadata, .. }
7057            | HydroNode::EndAtomic { metadata, .. }
7058            | HydroNode::Batch { metadata, .. }
7059            | HydroNode::Snapshot { metadata, .. }
7060            | HydroNode::Chain { metadata, .. }
7061            | HydroNode::MergeOrdered { metadata, .. }
7062            | HydroNode::ChainFirst { metadata, .. }
7063            | HydroNode::CrossProduct { metadata, .. }
7064            | HydroNode::CrossSingleton { metadata, .. }
7065            | HydroNode::Join { metadata, .. }
7066            | HydroNode::JoinHalf { metadata, .. }
7067            | HydroNode::Difference { metadata, .. }
7068            | HydroNode::AntiJoin { metadata, .. }
7069            | HydroNode::ResolveFutures { metadata, .. }
7070            | HydroNode::ResolveFuturesBlocking { metadata, .. }
7071            | HydroNode::ResolveFuturesOrdered { metadata, .. }
7072            | HydroNode::Map { metadata, .. }
7073            | HydroNode::FlatMap { metadata, .. }
7074            | HydroNode::FlatMapStreamBlocking { metadata, .. }
7075            | HydroNode::Filter { metadata, .. }
7076            | HydroNode::FilterMap { metadata, .. }
7077            | HydroNode::DeferTick { metadata, .. }
7078            | HydroNode::Enumerate { metadata, .. }
7079            | HydroNode::Inspect { metadata, .. }
7080            | HydroNode::Unique { metadata, .. }
7081            | HydroNode::Sort { metadata, .. }
7082            | HydroNode::Scan { metadata, .. }
7083            | HydroNode::ScanAsyncBlocking { metadata, .. }
7084            | HydroNode::Fold { metadata, .. }
7085            | HydroNode::FoldKeyed { metadata, .. }
7086            | HydroNode::Reduce { metadata, .. }
7087            | HydroNode::ReduceKeyed { metadata, .. }
7088            | HydroNode::ReduceKeyedWatermark { metadata, .. }
7089            | HydroNode::ExternalInput { metadata, .. }
7090            | HydroNode::Network { metadata, .. }
7091            | HydroNode::Counter { metadata, .. } => metadata,
7092        }
7093    }
7094
7095    pub fn op_metadata_mut(&mut self) -> &mut HydroIrOpMetadata {
7096        &mut self.metadata_mut().op
7097    }
7098
7099    pub fn metadata_mut(&mut self) -> &mut HydroIrMetadata {
7100        match self {
7101            HydroNode::Placeholder => {
7102                panic!()
7103            }
7104            HydroNode::VersionedNetworkFork { metadata, .. }
7105            | HydroNode::VersionedNetwork { metadata, .. } => metadata,
7106            HydroNode::Cast { metadata, .. }
7107            | HydroNode::CastUpdateStream { metadata, .. }
7108            | HydroNode::ObserveNonDet { metadata, .. }
7109            | HydroNode::AssertIsConsistent { metadata, .. }
7110            | HydroNode::UnboundSingleton { metadata, .. }
7111            | HydroNode::Source { metadata, .. }
7112            | HydroNode::SingletonSource { metadata, .. }
7113            | HydroNode::CycleSource { metadata, .. }
7114            | HydroNode::Tee { metadata, .. }
7115            | HydroNode::Reference { metadata, .. }
7116            | HydroNode::PartitionSide { metadata, .. }
7117            | HydroNode::PartitionShared { metadata, .. }
7118            | HydroNode::YieldConcat { metadata, .. }
7119            | HydroNode::BeginAtomic { metadata, .. }
7120            | HydroNode::EndAtomic { metadata, .. }
7121            | HydroNode::Batch { metadata, .. }
7122            | HydroNode::Snapshot { metadata, .. }
7123            | HydroNode::Chain { metadata, .. }
7124            | HydroNode::MergeOrdered { metadata, .. }
7125            | HydroNode::ChainFirst { metadata, .. }
7126            | HydroNode::CrossProduct { metadata, .. }
7127            | HydroNode::CrossSingleton { metadata, .. }
7128            | HydroNode::Join { metadata, .. }
7129            | HydroNode::JoinHalf { metadata, .. }
7130            | HydroNode::Difference { metadata, .. }
7131            | HydroNode::AntiJoin { metadata, .. }
7132            | HydroNode::ResolveFutures { metadata, .. }
7133            | HydroNode::ResolveFuturesBlocking { metadata, .. }
7134            | HydroNode::ResolveFuturesOrdered { metadata, .. }
7135            | HydroNode::Map { metadata, .. }
7136            | HydroNode::FlatMap { metadata, .. }
7137            | HydroNode::FlatMapStreamBlocking { metadata, .. }
7138            | HydroNode::Filter { metadata, .. }
7139            | HydroNode::FilterMap { metadata, .. }
7140            | HydroNode::DeferTick { metadata, .. }
7141            | HydroNode::Enumerate { metadata, .. }
7142            | HydroNode::Inspect { metadata, .. }
7143            | HydroNode::Unique { metadata, .. }
7144            | HydroNode::Sort { metadata, .. }
7145            | HydroNode::Scan { metadata, .. }
7146            | HydroNode::ScanAsyncBlocking { metadata, .. }
7147            | HydroNode::Fold { metadata, .. }
7148            | HydroNode::FoldKeyed { metadata, .. }
7149            | HydroNode::Reduce { metadata, .. }
7150            | HydroNode::ReduceKeyed { metadata, .. }
7151            | HydroNode::ReduceKeyedWatermark { metadata, .. }
7152            | HydroNode::ExternalInput { metadata, .. }
7153            | HydroNode::Network { metadata, .. }
7154            | HydroNode::Counter { metadata, .. } => metadata,
7155        }
7156    }
7157
7158    pub fn input(&self) -> Vec<&HydroNode> {
7159        match self {
7160            HydroNode::Placeholder => {
7161                panic!()
7162            }
7163            HydroNode::Source { .. }
7164            | HydroNode::SingletonSource { .. }
7165            | HydroNode::ExternalInput { .. }
7166            | HydroNode::CycleSource { .. }
7167            | HydroNode::Tee { .. }
7168            | HydroNode::Reference { .. }
7169            | HydroNode::PartitionSide { .. }
7170            | HydroNode::VersionedNetwork { .. } => {
7171                // Tee/PartitionSide/VersionedNetwork find their input in separate special ways
7172                vec![]
7173            }
7174            HydroNode::Cast { inner, .. }
7175            | HydroNode::CastUpdateStream { inner, .. }
7176            | HydroNode::ObserveNonDet { inner, .. }
7177            | HydroNode::YieldConcat { inner, .. }
7178            | HydroNode::BeginAtomic { inner, .. }
7179            | HydroNode::EndAtomic { inner, .. }
7180            | HydroNode::Batch { inner, .. }
7181            | HydroNode::Snapshot { inner, .. }
7182            | HydroNode::UnboundSingleton { inner, .. }
7183            | HydroNode::AssertIsConsistent { inner, .. } => {
7184                vec![inner]
7185            }
7186            HydroNode::Chain { first, second, .. }
7187            | HydroNode::MergeOrdered { first, second, .. }
7188            | HydroNode::ChainFirst { first, second, .. } => {
7189                vec![first, second]
7190            }
7191            HydroNode::CrossProduct { left, right, .. }
7192            | HydroNode::CrossSingleton { left, right, .. }
7193            | HydroNode::Join { left, right, .. }
7194            | HydroNode::JoinHalf { left, right, .. } => {
7195                vec![left, right]
7196            }
7197            HydroNode::Difference { pos, neg, .. } | HydroNode::AntiJoin { pos, neg, .. } => {
7198                vec![pos, neg]
7199            }
7200            HydroNode::Counter { input, .. }
7201            | HydroNode::DeferTick { input, .. }
7202            | HydroNode::Enumerate { input, .. }
7203            | HydroNode::Filter { input, .. }
7204            | HydroNode::FilterMap { input, .. }
7205            | HydroNode::FlatMap { input, .. }
7206            | HydroNode::FlatMapStreamBlocking { input, .. }
7207            | HydroNode::Fold { input, .. }
7208            | HydroNode::FoldKeyed { input, .. }
7209            | HydroNode::Inspect { input, .. }
7210            | HydroNode::Map { input, .. }
7211            | HydroNode::Network { input, .. }
7212            | HydroNode::PartitionShared { input, .. }
7213            | HydroNode::Reduce { input, .. }
7214            | HydroNode::ReduceKeyed { input, .. }
7215            | HydroNode::ResolveFutures { input, .. }
7216            | HydroNode::ResolveFuturesBlocking { input, .. }
7217            | HydroNode::ResolveFuturesOrdered { input, .. }
7218            | HydroNode::Scan { input, .. }
7219            | HydroNode::ScanAsyncBlocking { input, .. }
7220            | HydroNode::Sort { input, .. }
7221            | HydroNode::Unique { input, .. } => {
7222                vec![input]
7223            }
7224            HydroNode::ReduceKeyedWatermark {
7225                input, watermark, ..
7226            } => {
7227                vec![input, watermark]
7228            }
7229            HydroNode::VersionedNetworkFork { senders, .. } => senders
7230                .iter()
7231                .map(|(_version, sender, _serialize)| sender.as_ref())
7232                .collect(),
7233        }
7234    }
7235
7236    pub fn input_metadata(&self) -> Vec<&HydroIrMetadata> {
7237        self.input()
7238            .iter()
7239            .map(|input_node| input_node.metadata())
7240            .collect()
7241    }
7242
7243    /// Returns `true` if this node is a Tee or Partition whose inner Rc
7244    /// has other live references, meaning the upstream is already driven
7245    /// by another consumer and does not need a Null sink.
7246    pub fn is_shared_with_others(&self) -> bool {
7247        match self {
7248            HydroNode::Tee { inner, .. } | HydroNode::PartitionSide { inner, .. } => {
7249                Rc::strong_count(&inner.0) > 1
7250            }
7251            // A zero-output reference node is valid in DFIR (it drains itself at
7252            // end of tick), so it doesn't need to be driven by another consumer.
7253            HydroNode::Reference { .. } => false,
7254            _ => false,
7255        }
7256    }
7257
7258    pub fn print_root(&self) -> String {
7259        match self {
7260            HydroNode::Placeholder => {
7261                panic!()
7262            }
7263            HydroNode::Cast { .. } => "Cast()".to_owned(),
7264            HydroNode::CastUpdateStream { .. } => "CastUpdateStream()".to_owned(),
7265            HydroNode::UnboundSingleton { .. } => "UnboundSingleton()".to_owned(),
7266            HydroNode::ObserveNonDet { .. } => "ObserveNonDet()".to_owned(),
7267            HydroNode::AssertIsConsistent { .. } => "AssertIsConsistent()".to_owned(),
7268            HydroNode::Source { source, .. } => format!("Source({:?})", source),
7269            HydroNode::SingletonSource {
7270                value,
7271                first_tick_only,
7272                ..
7273            } => format!(
7274                "SingletonSource({:?}, first_tick_only={})",
7275                value, first_tick_only
7276            ),
7277            HydroNode::CycleSource { cycle_id, .. } => format!("CycleSource({})", cycle_id),
7278            HydroNode::Tee { inner, .. } => {
7279                format!("Tee({})", inner.0.borrow().print_root())
7280            }
7281            HydroNode::Reference { inner, kind, .. } => {
7282                format!("Reference({:?}, {})", kind, inner.0.borrow().print_root())
7283            }
7284            HydroNode::PartitionSide { inner, is_true, .. } => {
7285                format!(
7286                    "PartitionSide(is_true={}, {})",
7287                    is_true,
7288                    inner.0.borrow().print_root(),
7289                )
7290            }
7291            HydroNode::PartitionShared { f, .. } => format!("PartitionShared({:?})", f),
7292            HydroNode::YieldConcat { .. } => "YieldConcat()".to_owned(),
7293            HydroNode::BeginAtomic { .. } => "BeginAtomic()".to_owned(),
7294            HydroNode::EndAtomic { .. } => "EndAtomic()".to_owned(),
7295            HydroNode::Batch { .. } => "Batch()".to_owned(),
7296            HydroNode::Snapshot { .. } => "Snapshot()".to_owned(),
7297            HydroNode::Chain { first, second, .. } => {
7298                format!("Chain({}, {})", first.print_root(), second.print_root())
7299            }
7300            HydroNode::MergeOrdered { first, second, .. } => {
7301                format!(
7302                    "MergeOrdered({}, {})",
7303                    first.print_root(),
7304                    second.print_root()
7305                )
7306            }
7307            HydroNode::ChainFirst { first, second, .. } => {
7308                format!(
7309                    "ChainFirst({}, {})",
7310                    first.print_root(),
7311                    second.print_root()
7312                )
7313            }
7314            HydroNode::CrossProduct { left, right, .. } => {
7315                format!(
7316                    "CrossProduct({}, {})",
7317                    left.print_root(),
7318                    right.print_root()
7319                )
7320            }
7321            HydroNode::CrossSingleton { left, right, .. } => {
7322                format!(
7323                    "CrossSingleton({}, {})",
7324                    left.print_root(),
7325                    right.print_root()
7326                )
7327            }
7328            HydroNode::Join { left, right, .. } => {
7329                format!("Join({}, {})", left.print_root(), right.print_root())
7330            }
7331            HydroNode::JoinHalf { left, right, .. } => {
7332                format!("JoinHalf({}, {})", left.print_root(), right.print_root())
7333            }
7334            HydroNode::Difference { pos, neg, .. } => {
7335                format!("Difference({}, {})", pos.print_root(), neg.print_root())
7336            }
7337            HydroNode::AntiJoin { pos, neg, .. } => {
7338                format!("AntiJoin({}, {})", pos.print_root(), neg.print_root())
7339            }
7340            HydroNode::ResolveFutures { .. } => "ResolveFutures()".to_owned(),
7341            HydroNode::ResolveFuturesBlocking { .. } => "ResolveFuturesBlocking()".to_owned(),
7342            HydroNode::ResolveFuturesOrdered { .. } => "ResolveFuturesOrdered()".to_owned(),
7343            HydroNode::Map { f, .. } => format!("Map({:?})", f),
7344            HydroNode::FlatMap { f, .. } => format!("FlatMap({:?})", f),
7345            HydroNode::FlatMapStreamBlocking { f, .. } => format!("FlatMapStreamBlocking({:?})", f),
7346            HydroNode::Filter { f, .. } => format!("Filter({:?})", f),
7347            HydroNode::FilterMap { f, .. } => format!("FilterMap({:?})", f),
7348            HydroNode::DeferTick { .. } => "DeferTick()".to_owned(),
7349            HydroNode::Enumerate { .. } => "Enumerate()".to_owned(),
7350            HydroNode::Inspect { f, .. } => format!("Inspect({:?})", f),
7351            HydroNode::Unique { .. } => "Unique()".to_owned(),
7352            HydroNode::Sort { .. } => "Sort()".to_owned(),
7353            HydroNode::Fold { init, acc, .. } => format!("Fold({:?}, {:?})", init, acc),
7354            HydroNode::Scan { init, acc, .. } => format!("Scan({:?}, {:?})", init, acc),
7355            HydroNode::ScanAsyncBlocking { init, acc, .. } => {
7356                format!("ScanAsyncBlocking({:?}, {:?})", init, acc)
7357            }
7358            HydroNode::FoldKeyed { init, acc, .. } => format!("FoldKeyed({:?}, {:?})", init, acc),
7359            HydroNode::Reduce { f, .. } => format!("Reduce({:?})", f),
7360            HydroNode::ReduceKeyed { f, .. } => format!("ReduceKeyed({:?})", f),
7361            HydroNode::ReduceKeyedWatermark { f, .. } => format!("ReduceKeyedWatermark({:?})", f),
7362            HydroNode::Network { .. } => "Network()".to_owned(),
7363            HydroNode::ExternalInput { .. } => "ExternalInput()".to_owned(),
7364            HydroNode::Counter { tag, duration, .. } => {
7365                format!("Counter({:?}, {:?})", tag, duration)
7366            }
7367            HydroNode::VersionedNetworkFork {
7368                channel_name,
7369                senders,
7370                ..
7371            } => {
7372                let versions: Vec<u32> = senders.iter().map(|(v, _, _)| *v).collect();
7373                format!(
7374                    "VersionedNetworkFork({}, senders={:?})",
7375                    channel_name, versions
7376                )
7377            }
7378            HydroNode::VersionedNetwork { version, .. } => {
7379                format!("VersionedNetwork(v{})", version)
7380            }
7381        }
7382    }
7383}
7384
7385#[cfg(feature = "build")]
7386#[expect(clippy::too_many_arguments, reason = "networking codegen")]
7387fn instantiate_network<'a, D>(
7388    env: &mut D::InstantiateEnv,
7389    from_location: &LocationId,
7390    to_location: &LocationId,
7391    processes: &SparseSecondaryMap<LocationKey, D::Process>,
7392    clusters: &SparseSecondaryMap<LocationKey, D::Cluster>,
7393    name: Option<&str>,
7394    networking_info: &crate::networking::NetworkingInfo,
7395    external_types: Option<(&syn::Type, &syn::Type)>,
7396) -> (syn::Expr, syn::Expr, Box<dyn FnOnce()>)
7397where
7398    D: Deploy<'a>,
7399{
7400    if external_types.is_some() {
7401        assert!(
7402            D::SUPPORTS_EXTERNAL_SERIALIZATION,
7403            "`EMBEDDED` channels are implemented by the host of an embedded dataflow and are \
7404             only supported by the embedded deployment backend (and the simulator). Use `TCP` \
7405             or `UDP` (with `.bincode()`) for this deployment target instead."
7406        );
7407    }
7408
7409    let ((sink, source), connect_fn) = match (from_location, to_location) {
7410        (&LocationId::Process(from), &LocationId::Process(to)) => {
7411            let from_node = processes
7412                .get(from)
7413                .unwrap_or_else(|| {
7414                    panic!("A process used in the graph was not instantiated: {}", from)
7415                })
7416                .clone();
7417            let to_node = processes
7418                .get(to)
7419                .unwrap_or_else(|| {
7420                    panic!("A process used in the graph was not instantiated: {}", to)
7421                })
7422                .clone();
7423
7424            let sink_port = from_node.next_port();
7425            let source_port = to_node.next_port();
7426
7427            (
7428                D::o2o_sink_source(
7429                    env,
7430                    &from_node,
7431                    &sink_port,
7432                    &to_node,
7433                    &source_port,
7434                    name,
7435                    networking_info,
7436                    external_types,
7437                ),
7438                D::o2o_connect(&from_node, &sink_port, &to_node, &source_port),
7439            )
7440        }
7441        (&LocationId::Process(from), &LocationId::Cluster(to)) => {
7442            let from_node = processes
7443                .get(from)
7444                .unwrap_or_else(|| {
7445                    panic!("A process used in the graph was not instantiated: {}", from)
7446                })
7447                .clone();
7448            let to_node = clusters
7449                .get(to)
7450                .unwrap_or_else(|| {
7451                    panic!("A cluster used in the graph was not instantiated: {}", to)
7452                })
7453                .clone();
7454
7455            let sink_port = from_node.next_port();
7456            let source_port = to_node.next_port();
7457
7458            (
7459                D::o2m_sink_source(
7460                    env,
7461                    &from_node,
7462                    &sink_port,
7463                    &to_node,
7464                    &source_port,
7465                    name,
7466                    networking_info,
7467                    external_types,
7468                ),
7469                D::o2m_connect(&from_node, &sink_port, &to_node, &source_port),
7470            )
7471        }
7472        (&LocationId::Cluster(from), &LocationId::Process(to)) => {
7473            let from_node = clusters
7474                .get(from)
7475                .unwrap_or_else(|| {
7476                    panic!("A cluster used in the graph was not instantiated: {}", from)
7477                })
7478                .clone();
7479            let to_node = processes
7480                .get(to)
7481                .unwrap_or_else(|| {
7482                    panic!("A process used in the graph was not instantiated: {}", to)
7483                })
7484                .clone();
7485
7486            let sink_port = from_node.next_port();
7487            let source_port = to_node.next_port();
7488
7489            (
7490                D::m2o_sink_source(
7491                    env,
7492                    &from_node,
7493                    &sink_port,
7494                    &to_node,
7495                    &source_port,
7496                    name,
7497                    networking_info,
7498                    external_types,
7499                ),
7500                D::m2o_connect(&from_node, &sink_port, &to_node, &source_port),
7501            )
7502        }
7503        (&LocationId::Cluster(from), &LocationId::Cluster(to)) => {
7504            let from_node = clusters
7505                .get(from)
7506                .unwrap_or_else(|| {
7507                    panic!("A cluster used in the graph was not instantiated: {}", from)
7508                })
7509                .clone();
7510            let to_node = clusters
7511                .get(to)
7512                .unwrap_or_else(|| {
7513                    panic!("A cluster used in the graph was not instantiated: {}", to)
7514                })
7515                .clone();
7516
7517            let sink_port = from_node.next_port();
7518            let source_port = to_node.next_port();
7519
7520            (
7521                D::m2m_sink_source(
7522                    env,
7523                    &from_node,
7524                    &sink_port,
7525                    &to_node,
7526                    &source_port,
7527                    name,
7528                    networking_info,
7529                    external_types,
7530                ),
7531                D::m2m_connect(&from_node, &sink_port, &to_node, &source_port),
7532            )
7533        }
7534        (LocationId::Tick { .. }, _) => panic!(),
7535        (_, LocationId::Tick { .. }) => panic!(),
7536        (LocationId::Atomic(_), _) => panic!(),
7537        (_, LocationId::Atomic(_)) => panic!(),
7538    };
7539    (sink, source, connect_fn)
7540}
7541
7542#[cfg(test)]
7543mod serde_test;
7544
7545#[cfg(test)]
7546mod test {
7547    use std::mem::size_of;
7548
7549    use stageleft::{QuotedWithContext, q};
7550
7551    use super::*;
7552
7553    #[test]
7554    #[cfg_attr(
7555        not(feature = "build"),
7556        ignore = "expects inclusion of feature-gated fields"
7557    )]
7558    fn hydro_node_size() {
7559        assert_eq!(size_of::<HydroNode>(), 280);
7560    }
7561
7562    #[test]
7563    #[cfg_attr(
7564        not(feature = "build"),
7565        ignore = "expects inclusion of feature-gated fields"
7566    )]
7567    fn hydro_root_size() {
7568        assert_eq!(size_of::<HydroRoot>(), 152);
7569    }
7570
7571    #[test]
7572    fn test_simplify_q_macro_basic() {
7573        // Test basic non-q! expression
7574        let simple_expr: syn::Expr = syn::parse_str("x + y").unwrap();
7575        let result = simplify_q_macro(simple_expr.clone());
7576        assert_eq!(result, simple_expr);
7577    }
7578
7579    #[test]
7580    fn test_simplify_q_macro_actual_stageleft_call() {
7581        // Test a simplified version of what a real stageleft call might look like
7582        let stageleft_call = q!(|x: usize| x + 1).splice_fn1_ctx(&());
7583        let result = simplify_q_macro(stageleft_call);
7584        // This should be processed by our visitor and simplified to q!(...)
7585        // since we detect the stageleft::runtime_support::fn_* pattern
7586        hydro_build_utils::assert_snapshot!(result.to_token_stream().to_string());
7587    }
7588
7589    #[test]
7590    fn test_closure_no_pipe_at_start() {
7591        // Test a closure that does not start with a pipe
7592        let stageleft_call = q!({
7593            let foo = 123;
7594            move |b: usize| b + foo
7595        })
7596        .splice_fn1_ctx(&());
7597        let result = simplify_q_macro(stageleft_call);
7598        hydro_build_utils::assert_snapshot!(result.to_token_stream().to_string());
7599    }
7600}