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