Skip to main content

hydro_lang/live_collections/
singleton.rs

1//! Definitions for the [`Singleton`] live collection.
2
3use std::cell::RefCell;
4use std::marker::PhantomData;
5use std::ops::{Deref, Not};
6use std::rc::Rc;
7
8use sealed::sealed;
9use stageleft::{IntoQuotedMut, QuotedWithContext, QuotedWithContextWithProps, q};
10
11use super::OperatorContext;
12use super::boundedness::{Bounded, Boundedness, IsBounded, Unbounded};
13use super::optional::{InitNone, Optional};
14use super::sliced::sliced;
15use super::stream::{AtLeastOnce, ExactlyOnce, NoOrder, Stream, TotalOrder};
16use crate::compile::builder::{CycleId, FlowState};
17use crate::compile::ir::{
18    CollectionKind, HydroIrOpMetadata, HydroNode, HydroRoot, SharedNode, SingletonBoundKind,
19};
20#[cfg(stageleft_runtime)]
21use crate::forward_handle::{CycleCollection, CycleCollectionWithInitial, ReceiverComplete};
22use crate::forward_handle::{ForwardRef, TickCycle};
23#[cfg(feature = "tokio")]
24use crate::location::TopLevel;
25#[cfg(stageleft_runtime)]
26use crate::location::dynamic::{DynLocation, LocationId};
27use crate::location::tick::Atomic;
28use crate::location::{Location, Tick, check_matching_location};
29use crate::nondet::{NonDet, nondet};
30use crate::properties::{
31    ApplyMonotoneStream, ApplyOrderPreservingSingleton, Proved, SingletonMapFuncAlgebra,
32    StreamMapFuncAlgebra, ValidMutCommutativityFor, ValidMutIdempotenceFor,
33};
34
35/// A marker trait indicating which components of a [`Singleton`] may change.
36///
37/// In addition to [`Bounded`] (immutable) and [`Unbounded`] (arbitrarily mutable), this also
38/// includes an additional variant [`Monotonic`], which means that the value will only grow.
39pub trait SingletonBound {
40    /// The [`Boundedness`] that this [`Singleton`] would be erased to.
41    type UnderlyingBound: Boundedness + ApplyMonotoneStream<Proved, Self::StreamToMonotone>;
42
43    /// The [`Boundedness`] of this [`Singleton`] if it is produced from a [`Stream`] with [`Self`] boundedness.
44    type StreamToMonotone: SingletonBound<UnderlyingBound = Self::UnderlyingBound>;
45
46    /// Returns the [`SingletonBoundKind`] corresponding to this type.
47    fn bound_kind() -> SingletonBoundKind;
48}
49
50impl SingletonBound for Unbounded {
51    type UnderlyingBound = Unbounded;
52
53    type StreamToMonotone = Monotonic;
54
55    fn bound_kind() -> SingletonBoundKind {
56        SingletonBoundKind::Unbounded
57    }
58}
59
60impl SingletonBound for Bounded {
61    type UnderlyingBound = Bounded;
62
63    type StreamToMonotone = Bounded;
64
65    fn bound_kind() -> SingletonBoundKind {
66        SingletonBoundKind::Bounded
67    }
68}
69
70/// Marks that the [`Singleton`] is monotonic, which means that its value will only grow over time.
71pub enum Monotonic {}
72
73impl SingletonBound for Monotonic {
74    type UnderlyingBound = Unbounded;
75
76    type StreamToMonotone = Monotonic;
77
78    fn bound_kind() -> SingletonBoundKind {
79        SingletonBoundKind::Monotonic
80    }
81}
82
83#[sealed]
84#[diagnostic::on_unimplemented(
85    message = "the input singleton must be monotonic (`Monotonic`) or bounded (`Bounded`), but has bound `{Self}`",
86    label = "required here",
87    note = "strengthen the monotonicity upstream, or consider a different API",
88    note = "to intentionally process a non-deterministic snapshot or batch, you may want to use a `sliced!` region; this introduces non-determinism, so avoid it unless necessary"
89)]
90/// Marker trait that is implemented for the [`Monotonic`] boundedness guarantee.
91pub trait IsMonotonic: SingletonBound {}
92
93#[sealed]
94#[diagnostic::do_not_recommend]
95impl IsMonotonic for Monotonic {}
96
97#[sealed]
98#[diagnostic::do_not_recommend]
99impl<B: IsBounded> IsMonotonic for B {}
100
101/// A single Rust value that can asynchronously change over time.
102///
103/// If the singleton is [`Bounded`], the value is frozen and will not change. But if it is
104/// [`Unbounded`], the value will asynchronously change over time.
105///
106/// Singletons are often used to capture state in a Hydro program, such as an event counter which is
107/// a single number that will asynchronously change as events are processed. Singletons also appear
108/// when dealing with bounded collections, to perform regular Rust computations on concrete values,
109/// such as getting the length of a batch of requests.
110///
111/// Type Parameters:
112/// - `Type`: the type of the value in this singleton
113/// - `Loc`: the [`Location`] where the singleton is materialized
114/// - `Bound`: tracks whether the value is [`Bounded`] (fixed) or [`Unbounded`] (changing asynchronously)
115pub struct Singleton<Type, Loc, Bound: SingletonBound> {
116    pub(crate) location: Loc,
117    pub(crate) ir_node: Rc<RefCell<HydroNode>>,
118    pub(crate) flow_state: FlowState,
119
120    _phantom: PhantomData<(Type, Loc, Bound)>,
121}
122
123impl<T, L, B: SingletonBound> Drop for Singleton<T, L, B> {
124    fn drop(&mut self) {
125        let ir_node = self.ir_node.replace(HydroNode::Placeholder);
126        if !matches!(ir_node, HydroNode::Placeholder) && !ir_node.is_shared_with_others() {
127            self.flow_state.borrow_mut().try_push_root(HydroRoot::Null {
128                input: Box::new(ir_node),
129                op_metadata: HydroIrOpMetadata::new(),
130            });
131        }
132    }
133}
134
135impl<'a, T, L> From<Singleton<T, L, Bounded>> for Singleton<T, L, Unbounded>
136where
137    T: Clone,
138    L: Location<'a>,
139{
140    fn from(value: Singleton<T, L, Bounded>) -> Self {
141        let location = value.location().clone();
142        Singleton::new(
143            location.clone(),
144            HydroNode::UnboundSingleton {
145                inner: Box::new(value.ir_node.replace(HydroNode::Placeholder)),
146                metadata: location
147                    .new_node_metadata(Singleton::<T, L, Unbounded>::collection_kind()),
148            },
149        )
150    }
151}
152
153impl<'a, T, L> CycleCollectionWithInitial<'a, TickCycle> for Singleton<T, Tick<L>, Bounded>
154where
155    L: Location<'a>,
156{
157    type Location = Tick<L>;
158
159    fn location(&self) -> &Self::Location {
160        self.location()
161    }
162
163    fn create_source_with_initial(cycle_id: CycleId, initial: Self, location: Tick<L>) -> Self {
164        let from_previous_tick: Optional<T, Tick<L>, Bounded> = Optional::new(
165            location.clone(),
166            HydroNode::DeferTick {
167                input: Box::new(HydroNode::CycleSource {
168                    cycle_id,
169                    metadata: location.new_node_metadata(Self::collection_kind()),
170                }),
171                metadata: location
172                    .new_node_metadata(Optional::<T, Tick<L>, Bounded>::collection_kind()),
173            },
174        );
175
176        from_previous_tick.unwrap_or(initial)
177    }
178}
179
180impl<'a, T, L> ReceiverComplete<'a, TickCycle> for Singleton<T, Tick<L>, Bounded>
181where
182    L: Location<'a>,
183{
184    fn complete(self, cycle_id: CycleId, expected_location: LocationId) {
185        assert_eq!(
186            Location::id(&self.location),
187            expected_location,
188            "locations do not match"
189        );
190        self.location
191            .flow_state()
192            .borrow_mut()
193            .push_root(HydroRoot::CycleSink {
194                cycle_id,
195                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
196                op_metadata: HydroIrOpMetadata::new(),
197            });
198    }
199}
200
201impl<'a, T, L, B: SingletonBound> CycleCollection<'a, ForwardRef> for Singleton<T, L, B>
202where
203    L: Location<'a>,
204{
205    type Location = L;
206
207    fn create_source(cycle_id: CycleId, location: L) -> Self {
208        Singleton::new(
209            location.clone(),
210            HydroNode::CycleSource {
211                cycle_id,
212                metadata: location.new_node_metadata(Self::collection_kind()),
213            },
214        )
215    }
216}
217
218impl<'a, T, L, B: SingletonBound> ReceiverComplete<'a, ForwardRef> for Singleton<T, L, B>
219where
220    L: Location<'a>,
221{
222    fn complete(self, cycle_id: CycleId, expected_location: LocationId) {
223        assert_eq!(
224            Location::id(&self.location),
225            expected_location,
226            "locations do not match"
227        );
228        self.location
229            .flow_state()
230            .borrow_mut()
231            .push_root(HydroRoot::CycleSink {
232                cycle_id,
233                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
234                op_metadata: HydroIrOpMetadata::new(),
235            });
236    }
237}
238
239impl<'a, T, L, B: SingletonBound> Clone for Singleton<T, L, B>
240where
241    T: Clone,
242    L: Location<'a>,
243{
244    fn clone(&self) -> Self {
245        if !matches!(self.ir_node.borrow().deref(), HydroNode::Tee { .. }) {
246            let orig_ir_node = self.ir_node.replace(HydroNode::Placeholder);
247            *self.ir_node.borrow_mut() = HydroNode::Tee {
248                inner: SharedNode(Rc::new(RefCell::new(orig_ir_node))),
249                metadata: self.location.new_node_metadata(Self::collection_kind()),
250            };
251        }
252
253        if let HydroNode::Tee { inner, metadata } = self.ir_node.borrow().deref() {
254            Singleton {
255                location: self.location.clone(),
256                flow_state: self.flow_state.clone(),
257                ir_node: super::tracked_ir_node(
258                    &self.flow_state,
259                    HydroNode::Tee {
260                        inner: SharedNode(inner.0.clone()),
261                        metadata: metadata.clone(),
262                    },
263                ),
264                _phantom: PhantomData,
265            }
266        } else {
267            unreachable!()
268        }
269    }
270}
271
272/// [`Singleton::zip`] of two bounded singletons (see [`super::optional::zip_bounded`]).
273#[cfg(stageleft_runtime)]
274fn zip_singletons<'a, T, U, L: Location<'a>, B: SingletonBound>(
275    me: Singleton<T, L, B>,
276    other: Singleton<U, L, B>,
277) -> Singleton<(T, U), L, B> {
278    let location = me.location.clone();
279    let me: Optional<T, L, Bounded> = Optional::new(
280        location.clone(),
281        HydroNode::Cast {
282            inner: Box::new(me.ir_node.replace(HydroNode::Placeholder)),
283            metadata: location.new_node_metadata(Optional::<T, L, Bounded>::collection_kind()),
284        },
285    );
286    let other: Optional<U, L, Bounded> = Optional::new(
287        location.clone(),
288        HydroNode::Cast {
289            inner: Box::new(other.ir_node.replace(HydroNode::Placeholder)),
290            metadata: location.new_node_metadata(Optional::<U, L, Bounded>::collection_kind()),
291        },
292    );
293    let out = super::optional::zip_bounded(me, other);
294    Singleton::new(
295        location.clone(),
296        HydroNode::Cast {
297            inner: Box::new(out.ir_node.replace(HydroNode::Placeholder)),
298            metadata: location.new_node_metadata(Singleton::<(T, U), L, B>::collection_kind()),
299        },
300    )
301}
302
303impl<'a, T, L, B: SingletonBound> Singleton<T, L, B>
304where
305    L: Location<'a>,
306{
307    pub(crate) fn new(location: L, ir_node: HydroNode) -> Self {
308        debug_assert_eq!(ir_node.metadata().location_id, Location::id(&location));
309        debug_assert_eq!(ir_node.metadata().collection_kind, Self::collection_kind());
310        let flow_state = location.flow_state().clone();
311        let ir_node = super::tracked_ir_node(&flow_state, ir_node);
312        Singleton {
313            location,
314            flow_state,
315            ir_node,
316            _phantom: PhantomData,
317        }
318    }
319
320    pub(crate) fn collection_kind() -> CollectionKind {
321        CollectionKind::Singleton {
322            bound: B::bound_kind(),
323            element_type: stageleft::quote_type::<T>().into(),
324        }
325    }
326
327    /// Exposes this collection's top-level update feed as a stream whose elements are exactly
328    /// the feed's updates, in the order they were emitted.
329    ///
330    /// **Contract.** Relative to "every version of the collection, exactly once, in order", the
331    /// stream may *stutter* (repeat the current version, consecutively) and *skip*
332    /// (omit non-final versions); the final version is always eventually delivered. Which
333    /// versions appear depends on timing, so the caller's `nondet` must justify that its use is
334    /// invariant to stuttering and skipping (e.g. an idempotent "latest value" fold, or a
335    /// monotone threshold).
336    ///
337    /// **Simulator soundness.** The simulator emits every version exactly once and does not
338    /// explore skips, so a caller must never expose these updates (or anything derived from
339    /// them update-by-update) to user code or an output. It must route them into logic that
340    /// keeps the full trajectory of versions available and then through a simulator hook that
341    /// picks among them nondeterministically: fold them back into a singleton-like state that
342    /// is later snapshotted, or batch them into a tick. When combining several feeds, batch each
343    /// one into the same tick rather than interleaving them deterministically (e.g. with
344    /// `chain`), so the simulator explores every pairing of their versions. See
345    /// [`HydroNode::CastUpdateStream`] for the full contract.
346    ///
347    /// The collection must be located at a root (process or cluster) location.
348    pub(crate) fn into_update_stream(
349        self,
350        _nondet: NonDet,
351    ) -> Stream<T, L::DropConsistency, Unbounded, TotalOrder, ExactlyOnce> {
352        assert!(
353            self.location.id().is_root(),
354            "`into_update_stream` requires a root location, got {:?}",
355            self.location.id()
356        );
357        let target_location = self.location.drop_consistency();
358        Stream::new(
359            target_location.clone(),
360            HydroNode::CastUpdateStream {
361                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
362                metadata: target_location.new_node_metadata(Stream::<
363                    T,
364                    L::DropConsistency,
365                    Unbounded,
366                    TotalOrder,
367                    ExactlyOnce,
368                >::collection_kind()),
369            },
370        )
371    }
372
373    /// Returns the [`Location`] where this singleton is being materialized.
374    pub fn location(&self) -> &L {
375        &self.location
376    }
377
378    /// Creates a lightweight reference handle to this singleton that can be captured
379    /// inside `q!()` closures. The handle resolves to `&T` at runtime.
380    ///
381    /// The singleton must be bounded, otherwise reading it would be non-deterministic.
382    /// The handle can only be captured in closures passed to operators on collections at
383    /// the same location with **matching boundedness**; capturing it in a closure over an
384    /// unbounded collection is rejected at compile time, since the bounded singleton is only
385    /// materialized on the first tick while the closure would keep running on later ticks,
386    /// where accessing the reference would crash.
387    ///
388    /// ```rust
389    /// # #[cfg(feature = "deploy")] {
390    /// # use hydro_lang::prelude::*;
391    /// # use futures::StreamExt;
392    /// # tokio_test::block_on(async {
393    /// # let mut deployment = hydro_deploy::Deployment::new();
394    /// # let mut builder = hydro_lang::compile::builder::FlowBuilder::new();
395    /// # let process = builder.process::<()>();
396    /// # let external = builder.external::<()>();
397    /// let my_count = process
398    ///     .source_iter(q!(0..5i32))
399    ///     .fold(q!(|| 0i32), q!(|acc: &mut i32, x| *acc += x));
400    /// let count_ref = my_count.by_ref();
401    /// let out_port = process
402    ///     .source_iter(q!(1..=3i32))
403    ///     .map(q!(|x| x + *count_ref))
404    ///     .send_bincode_external(&external);
405    /// # let nodes = builder
406    /// #     .with_default_optimize()
407    /// #     .with_process(&process, deployment.Localhost())
408    /// #     .with_external(&external, deployment.Localhost())
409    /// #     .deploy(&mut deployment);
410    /// # deployment.deploy().await.unwrap();
411    /// # let mut out_recv = nodes.connect(out_port).await;
412    /// # deployment.start().await.unwrap();
413    /// # let mut results = Vec::new();
414    /// # for _ in 0..3 { results.push(out_recv.next().await.unwrap()); }
415    /// # results.sort();
416    /// // fold(0..5) = 10, so results are 11, 12, 13
417    /// # assert_eq!(results, vec![11, 12, 13]);
418    /// # });
419    /// # }
420    /// ```
421    pub fn by_ref(
422        &self,
423    ) -> crate::handoff_ref::SingletonRef<'a, '_, T, L, <B as SingletonBound>::UnderlyingBound>
424    where
425        B: IsBounded,
426    {
427        crate::handoff_ref::SingletonRef::new(&self.ir_node)
428    }
429
430    /// Returns a mutable reference handle to this singleton that can be captured inside `q!()`
431    /// closures. The handle resolves to `&mut T` at runtime.
432    ///
433    /// Mutable references are ordered via access groups in the generated DFIR code, ensuring
434    /// exclusive access at each point in the execution order.
435    ///
436    /// ```rust
437    /// # #[cfg(feature = "deploy")] {
438    /// # use hydro_lang::prelude::*;
439    /// # use futures::StreamExt;
440    /// # tokio_test::block_on(async {
441    /// # let mut deployment = hydro_deploy::Deployment::new();
442    /// # let mut builder = hydro_lang::compile::builder::FlowBuilder::new();
443    /// # let process = builder.process::<()>();
444    /// # let external = builder.external::<()>();
445    /// let my_count = process
446    ///     .source_iter(q!(0..5i32))
447    ///     .fold(q!(|| 0i32), q!(|acc: &mut i32, x| *acc += x));
448    /// let count_mut = my_count.by_mut();
449    /// let out_port = process
450    ///     .source_iter(q!(1..=3i32))
451    ///     .map(q!(|x| {
452    ///         *count_mut += x;
453    ///         *count_mut
454    ///     }))
455    ///     .send_bincode_external(&external);
456    /// # let nodes = builder
457    /// #     .with_default_optimize()
458    /// #     .with_process(&process, deployment.Localhost())
459    /// #     .with_external(&external, deployment.Localhost())
460    /// #     .deploy(&mut deployment);
461    /// # deployment.deploy().await.unwrap();
462    /// # let mut out_recv = nodes.connect(out_port).await;
463    /// # deployment.start().await.unwrap();
464    /// # let mut results = Vec::new();
465    /// # for _ in 0..3 { results.push(out_recv.next().await.unwrap()); }
466    /// # results.sort();
467    /// // fold(0..5) = 10, then each map adds x: results are 11, 13, 16
468    /// # assert_eq!(results, vec![11, 13, 16]);
469    /// # });
470    /// # }
471    /// ```
472    pub fn by_mut(
473        &self,
474    ) -> crate::handoff_ref::SingletonMut<'a, '_, T, L, <B as SingletonBound>::UnderlyingBound>
475    where
476        B: IsBounded,
477    {
478        crate::handoff_ref::SingletonMut::new(&self.ir_node)
479    }
480
481    /// Weakens the consistency of this live collection to not guarantee any consistency across
482    /// cluster members (if this collection is on a cluster).
483    pub fn weaken_consistency(self) -> Singleton<T, L::DropConsistency, B>
484    where
485        L: Location<'a>,
486    {
487        if L::consistency()
488            .is_none_or(|c| c == crate::location::dynamic::ClusterConsistency::NoConsistency)
489        {
490            // already no consistency
491            Singleton::new(
492                self.location.drop_consistency(),
493                self.ir_node.replace(HydroNode::Placeholder),
494            )
495        } else {
496            Singleton::new(
497                self.location.drop_consistency(),
498                HydroNode::Cast {
499                    inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
500                    metadata:
501                        self.location
502                            .clone()
503                            .drop_consistency()
504                            .new_node_metadata(
505                                Singleton::<T, L::DropConsistency, B>::collection_kind(),
506                            ),
507                },
508            )
509        }
510    }
511
512    /// Casts this live collection to have the consistency guarantees specified in the given
513    /// location type parameter. The developer must ensure that the strengthened consistency
514    /// is actually guaranteed, via the proof field (see [`crate::prelude::manual_proof`]).
515    pub fn assert_has_consistency_of<L2: Location<'a, DropConsistency = L::DropConsistency>>(
516        self,
517        _proof: impl crate::properties::ConsistencyProof,
518    ) -> Singleton<T, L2, B>
519    where
520        L: Location<'a>,
521    {
522        if L::consistency() == L2::consistency() {
523            Singleton::new(
524                self.location.with_consistency_of(),
525                self.ir_node.replace(HydroNode::Placeholder),
526            )
527        } else {
528            Singleton::new(
529                self.location.with_consistency_of(),
530                HydroNode::AssertIsConsistent {
531                    inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
532                    trusted: false,
533                    metadata: self
534                        .location
535                        .clone()
536                        .with_consistency_of::<L2>()
537                        .new_node_metadata(Singleton::<T, L2, B>::collection_kind()),
538                },
539            )
540        }
541    }
542
543    /// Drops the monotonicity property of the [`Singleton`].
544    pub fn ignore_monotonic(self) -> Singleton<T, L, B::UnderlyingBound> {
545        if B::bound_kind() == B::UnderlyingBound::bound_kind() {
546            Singleton::new(
547                self.location.clone(),
548                self.ir_node.replace(HydroNode::Placeholder),
549            )
550        } else {
551            Singleton::new(
552                self.location.clone(),
553                HydroNode::Cast {
554                    inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
555                    metadata:
556                        self.location.new_node_metadata(
557                            Singleton::<T, L, B::UnderlyingBound>::collection_kind(),
558                        ),
559                },
560            )
561        }
562    }
563
564    /// Transforms the singleton value by applying a function `f` to it,
565    /// continuously as the input is updated.
566    ///
567    /// # Example
568    /// ```rust
569    /// # #[cfg(feature = "deploy")] {
570    /// # use hydro_lang::prelude::*;
571    /// # use futures::StreamExt;
572    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
573    /// let tick = process.tick();
574    /// # // ticks are lazy by default, forces the tick to run
575    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
576    /// let singleton = tick.singleton(q!(5));
577    /// singleton.map(q!(|v| v * 2)).all_ticks()
578    /// # }, |mut stream| async move {
579    /// // 10
580    /// # assert_eq!(stream.next().await.unwrap(), 10);
581    /// # }));
582    /// # }
583    /// ```
584    pub fn map<U, F, OP, B2: SingletonBound>(
585        self,
586        f: impl IntoQuotedMut<
587            'a,
588            F,
589            OperatorContext<L, <B as SingletonBound>::UnderlyingBound>,
590            SingletonMapFuncAlgebra<T, <B as SingletonBound>::UnderlyingBound, OP>,
591        >,
592    ) -> Singleton<U, L, B2>
593    where
594        F: Fn(T) -> U + 'a,
595        B: ApplyOrderPreservingSingleton<OP, B2>,
596    {
597        let (f, proof) = f
598            .splice_fn1_ctx_props(
599                &OperatorContext::<L, <B as SingletonBound>::UnderlyingBound>::new(&self.location),
600            );
601        let _ = proof.register_proof(&f);
602        let f = f.into();
603        Singleton::new(
604            self.location.clone(),
605            HydroNode::Map {
606                f,
607                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
608                metadata: self
609                    .location
610                    .new_node_metadata(Singleton::<U, L, B2>::collection_kind()),
611            },
612        )
613    }
614
615    /// Transforms the singleton value by applying a function `f` to it and then flattening
616    /// the result into a stream, preserving the order of elements.
617    ///
618    /// The function `f` is applied to the singleton value to produce an iterator, and all items
619    /// from that iterator are emitted in the output stream in deterministic order.
620    ///
621    /// The implementation of [`Iterator`] for the output type `I` must produce items in a
622    /// **deterministic** order. For example, `I` could be a `Vec`, but not a `HashSet`.
623    /// If the order is not deterministic, use [`Singleton::flat_map_unordered`] instead.
624    ///
625    /// # Example
626    /// ```rust
627    /// # #[cfg(feature = "deploy")] {
628    /// # use hydro_lang::prelude::*;
629    /// # use futures::StreamExt;
630    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
631    /// let tick = process.tick();
632    /// # // ticks are lazy by default, forces the tick to run
633    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
634    /// let singleton = tick.singleton(q!(vec![1, 2, 3]));
635    /// singleton.flat_map_ordered(q!(|v| v)).all_ticks()
636    /// # }, |mut stream| async move {
637    /// // 1, 2, 3
638    /// # for w in vec![1, 2, 3] {
639    /// #     assert_eq!(stream.next().await.unwrap(), w);
640    /// # }
641    /// # }));
642    /// # }
643    /// ```
644    pub fn flat_map_ordered<U, I, F, C, Idemp, const WAS_MUT: bool>(
645        self,
646        f: impl IntoQuotedMut<
647            'a,
648            F,
649            OperatorContext<L, Bounded>,
650            StreamMapFuncAlgebra<T, Bounded, C, Idemp, L::SimHookScope>,
651        >,
652    ) -> Stream<U, L, Bounded, TotalOrder, ExactlyOnce>
653    where
654        B: IsBounded,
655        I: IntoIterator<Item = U>,
656        F: FnMut(T) -> I + 'a,
657        C: ValidMutCommutativityFor<F, T, I, TotalOrder, WAS_MUT>,
658        Idemp: ValidMutIdempotenceFor<F, T, I, ExactlyOnce, WAS_MUT>,
659    {
660        self.into_stream().flat_map_ordered(f)
661    }
662
663    /// Like [`Singleton::flat_map_ordered`], but allows the implementation of [`Iterator`]
664    /// for the output type `I` to produce items in any order.
665    ///
666    /// The function `f` is applied to the singleton value to produce an iterator, and all items
667    /// from that iterator are emitted in the output stream in non-deterministic order.
668    ///
669    /// # Example
670    /// ```rust
671    /// # #[cfg(feature = "deploy")] {
672    /// # use hydro_lang::{prelude::*, live_collections::stream::{NoOrder, ExactlyOnce}};
673    /// # use futures::StreamExt;
674    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test::<_, _, _, NoOrder, ExactlyOnce>(|process| {
675    /// let tick = process.tick();
676    /// # // ticks are lazy by default, forces the tick to run
677    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
678    /// let singleton = tick.singleton(q!(
679    ///     std::collections::HashSet::<i32>::from_iter(vec![1, 2, 3])
680    /// ));
681    /// singleton.flat_map_unordered(q!(|v| v)).all_ticks()
682    /// # }, |mut stream| async move {
683    /// // 1, 2, 3, but in no particular order
684    /// # let mut results = Vec::new();
685    /// # for _ in 0..3 {
686    /// #     results.push(stream.next().await.unwrap());
687    /// # }
688    /// # results.sort();
689    /// # assert_eq!(results, vec![1, 2, 3]);
690    /// # }));
691    /// # }
692    /// ```
693    pub fn flat_map_unordered<U, I, F, C, Idemp, const WAS_MUT: bool>(
694        self,
695        f: impl IntoQuotedMut<
696            'a,
697            F,
698            OperatorContext<L, Bounded>,
699            StreamMapFuncAlgebra<T, Bounded, C, Idemp, L::SimHookScope>,
700        >,
701    ) -> Stream<U, L, Bounded, NoOrder, ExactlyOnce>
702    where
703        B: IsBounded,
704        I: IntoIterator<Item = U>,
705        F: FnMut(T) -> I + 'a,
706        C: ValidMutCommutativityFor<F, T, I, TotalOrder, WAS_MUT>,
707        Idemp: ValidMutIdempotenceFor<F, T, I, ExactlyOnce, WAS_MUT>,
708    {
709        self.into_stream().flat_map_unordered(f)
710    }
711
712    /// Flattens the singleton value into a stream, preserving the order of elements.
713    ///
714    /// The singleton value must implement [`IntoIterator`], and all items from that iterator
715    /// are emitted in the output stream in deterministic order.
716    ///
717    /// The implementation of [`Iterator`] for the element type `T` must produce items in a
718    /// **deterministic** order. For example, `T` could be a `Vec`, but not a `HashSet`.
719    /// If the order is not deterministic, use [`Singleton::flatten_unordered`] instead.
720    ///
721    /// # Example
722    /// ```rust
723    /// # #[cfg(feature = "deploy")] {
724    /// # use hydro_lang::prelude::*;
725    /// # use futures::StreamExt;
726    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
727    /// let tick = process.tick();
728    /// # // ticks are lazy by default, forces the tick to run
729    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
730    /// let singleton = tick.singleton(q!(vec![1, 2, 3]));
731    /// singleton.flatten_ordered().all_ticks()
732    /// # }, |mut stream| async move {
733    /// // 1, 2, 3
734    /// # for w in vec![1, 2, 3] {
735    /// #     assert_eq!(stream.next().await.unwrap(), w);
736    /// # }
737    /// # }));
738    /// # }
739    /// ```
740    pub fn flatten_ordered<U>(self) -> Stream<U, L, Bounded, TotalOrder, ExactlyOnce>
741    where
742        B: IsBounded,
743        T: IntoIterator<Item = U>,
744    {
745        self.flat_map_ordered(q!(|x| x))
746    }
747
748    /// Like [`Singleton::flatten_ordered`], but allows the implementation of [`Iterator`]
749    /// for the element type `T` to produce items in any order.
750    ///
751    /// The singleton value must implement [`IntoIterator`], and all items from that iterator
752    /// are emitted in the output stream in non-deterministic order.
753    ///
754    /// # Example
755    /// ```rust
756    /// # #[cfg(feature = "deploy")] {
757    /// # use hydro_lang::{prelude::*, live_collections::stream::{NoOrder, ExactlyOnce}};
758    /// # use futures::StreamExt;
759    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test::<_, _, _, NoOrder, ExactlyOnce>(|process| {
760    /// let tick = process.tick();
761    /// # // ticks are lazy by default, forces the tick to run
762    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
763    /// let singleton = tick.singleton(q!(
764    ///     std::collections::HashSet::<i32>::from_iter(vec![1, 2, 3])
765    /// ));
766    /// singleton.flatten_unordered().all_ticks()
767    /// # }, |mut stream| async move {
768    /// // 1, 2, 3, but in no particular order
769    /// # let mut results = Vec::new();
770    /// # for _ in 0..3 {
771    /// #     results.push(stream.next().await.unwrap());
772    /// # }
773    /// # results.sort();
774    /// # assert_eq!(results, vec![1, 2, 3]);
775    /// # }));
776    /// # }
777    /// ```
778    pub fn flatten_unordered<U>(self) -> Stream<U, L, Bounded, NoOrder, ExactlyOnce>
779    where
780        B: IsBounded,
781        T: IntoIterator<Item = U>,
782    {
783        self.flat_map_unordered(q!(|x| x))
784    }
785
786    /// Creates an optional containing the singleton value if it satisfies a predicate `f`.
787    ///
788    /// If the predicate returns `true`, the output optional contains the same value.
789    /// If the predicate returns `false`, the output optional is empty.
790    ///
791    /// The closure `f` receives a reference `&T` rather than an owned value `T` because filtering does
792    /// not modify or take ownership of the value. If you need to modify the value while filtering
793    /// use [`Singleton::filter_map`] instead.
794    ///
795    /// # Example
796    /// ```rust
797    /// # #[cfg(feature = "deploy")] {
798    /// # use hydro_lang::prelude::*;
799    /// # use futures::StreamExt;
800    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
801    /// let tick = process.tick();
802    /// # // ticks are lazy by default, forces the tick to run
803    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
804    /// let singleton = tick.singleton(q!(5));
805    /// singleton.filter(q!(|&x| x > 3)).all_ticks()
806    /// # }, |mut stream| async move {
807    /// // 5
808    /// # assert_eq!(stream.next().await.unwrap(), 5);
809    /// # }));
810    /// # }
811    /// ```
812    pub fn filter<F>(
813        self,
814        f: impl IntoQuotedMut<'a, F, OperatorContext<L, <B as SingletonBound>::UnderlyingBound>>,
815    ) -> Optional<T, L, B::UnderlyingBound>
816    where
817        F: Fn(&T) -> bool + 'a,
818    {
819        let f = f
820            .splice_fn1_borrow_ctx(
821                &OperatorContext::<L, <B as SingletonBound>::UnderlyingBound>::new(&self.location),
822            )
823            .into();
824        Optional::new(
825            self.location.clone(),
826            HydroNode::Filter {
827                f,
828                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
829                metadata: self
830                    .location
831                    .new_node_metadata(Optional::<T, L, B::UnderlyingBound>::collection_kind()),
832            },
833        )
834    }
835
836    /// An operator that both filters and maps. It yields the value only if the supplied
837    /// closure `f` returns `Some(value)`.
838    ///
839    /// If the closure returns `Some(new_value)`, the output optional contains `new_value`.
840    /// If the closure returns `None`, the output optional is empty.
841    ///
842    /// # Example
843    /// ```rust
844    /// # #[cfg(feature = "deploy")] {
845    /// # use hydro_lang::prelude::*;
846    /// # use futures::StreamExt;
847    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
848    /// let tick = process.tick();
849    /// # // ticks are lazy by default, forces the tick to run
850    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
851    /// let singleton = tick.singleton(q!("42"));
852    /// singleton
853    ///     .filter_map(q!(|s| s.parse::<i32>().ok()))
854    ///     .all_ticks()
855    /// # }, |mut stream| async move {
856    /// // 42
857    /// # assert_eq!(stream.next().await.unwrap(), 42);
858    /// # }));
859    /// # }
860    /// ```
861    pub fn filter_map<U, F>(
862        self,
863        f: impl IntoQuotedMut<'a, F, OperatorContext<L, <B as SingletonBound>::UnderlyingBound>>,
864    ) -> Optional<U, L, B::UnderlyingBound>
865    where
866        F: Fn(T) -> Option<U> + 'a,
867    {
868        let f = f
869            .splice_fn1_ctx(
870                &OperatorContext::<L, <B as SingletonBound>::UnderlyingBound>::new(&self.location),
871            )
872            .into();
873        Optional::new(
874            self.location.clone(),
875            HydroNode::FilterMap {
876                f,
877                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
878                metadata: self
879                    .location
880                    .new_node_metadata(Optional::<U, L, B::UnderlyingBound>::collection_kind()),
881            },
882        )
883    }
884
885    /// Combines this singleton with another [`Singleton`] or [`Optional`] by tupling their values.
886    ///
887    /// If the other value is a [`Singleton`], the output will be a [`Singleton`], but if it is an
888    /// [`Optional`], the output will be an [`Optional`] that is non-null only if the argument is
889    /// non-null. This is useful for combining several pieces of state together.
890    ///
891    /// # Example
892    /// ```rust
893    /// # #[cfg(feature = "deploy")] {
894    /// # use hydro_lang::prelude::*;
895    /// # use futures::StreamExt;
896    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
897    /// let tick = process.tick();
898    /// let numbers = process
899    ///   .source_iter(q!(vec![123, 456]))
900    ///   .batch(&tick, nondet!(/** test */));
901    /// let count = numbers.clone().count(); // Singleton
902    /// let max = numbers.max(); // Optional
903    /// count.zip(max).all_ticks()
904    /// # }, |mut stream| async move {
905    /// // [(2, 456)]
906    /// # for w in vec![(2, 456)] {
907    /// #     assert_eq!(stream.next().await.unwrap(), w);
908    /// # }
909    /// # }));
910    /// # }
911    /// ```
912    pub fn zip<O>(self, other: O) -> <Self as ZipResult<'a, O>>::Out
913    where
914        Self: ZipResult<'a, O, Location = L>,
915        B: IsBounded,
916    {
917        check_matching_location(&self.location, &Self::other_location(&other));
918
919        let location = self.location().clone();
920        let other_location = <Self as ZipResult<'a, O>>::other_location(&other);
921        let me: Optional<T, L, Bounded> = Optional::new(
922            location.clone(),
923            HydroNode::Cast {
924                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
925                metadata: location.new_node_metadata(Optional::<T, L, Bounded>::collection_kind()),
926            },
927        );
928        let other: Optional<<Self as ZipResult<'a, O>>::OtherType, L, Bounded> = Optional::new(
929            other_location.clone(),
930            HydroNode::Cast {
931                inner: Box::new(Self::other_ir_node(other)),
932                metadata: other_location.new_node_metadata(Optional::<
933                    <Self as ZipResult<'a, O>>::OtherType,
934                    L,
935                    Bounded,
936                >::collection_kind()),
937            },
938        );
939        let out = super::optional::zip_bounded(me, other);
940        Self::make(location, out.ir_node.replace(HydroNode::Placeholder))
941    }
942
943    /// Filters this singleton into an [`Optional`], passing through the singleton value if the
944    /// boolean signal is `true`, otherwise the output is null.
945    ///
946    /// # Example
947    /// ```rust
948    /// # #[cfg(feature = "deploy")] {
949    /// # use hydro_lang::prelude::*;
950    /// # use futures::StreamExt;
951    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
952    /// let tick = process.tick();
953    /// // ticks are lazy by default, forces the second tick to run
954    /// tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
955    ///
956    /// let signal = tick.optional_first_tick(q!(())).is_some(); // true on tick 1, false on tick 2
957    /// let batch_first_tick = process
958    ///   .source_iter(q!(vec![1]))
959    ///   .batch(&tick, nondet!(/** test */));
960    /// let batch_second_tick = process
961    ///   .source_iter(q!(vec![1, 2, 3]))
962    ///   .batch(&tick, nondet!(/** test */))
963    ///   .defer_tick();
964    /// batch_first_tick.chain(batch_second_tick).count()
965    ///   .filter_if(signal)
966    ///   .all_ticks()
967    /// # }, |mut stream| async move {
968    /// // [1]
969    /// # for w in vec![1] {
970    /// #     assert_eq!(stream.next().await.unwrap(), w);
971    /// # }
972    /// # }));
973    /// # }
974    /// ```
975    pub fn filter_if(
976        self,
977        signal: Singleton<bool, L, B>,
978    ) -> Optional<T, L, <B as SingletonBound>::UnderlyingBound>
979    where
980        B: IsBounded,
981    {
982        self.zip(signal.filter(q!(|b| *b))).map(q!(|(d, _)| d))
983    }
984
985    /// Filters this singleton into an [`Optional`], passing through the singleton value if the
986    /// argument (a [`Bounded`] [`Optional`]) is non-null, otherwise the output is null.
987    ///
988    /// Useful for conditionally processing, such as only emitting a singleton's value outside
989    /// a tick if some other condition is satisfied.
990    ///
991    /// # Example
992    /// ```rust
993    /// # #[cfg(feature = "deploy")] {
994    /// # use hydro_lang::prelude::*;
995    /// # use futures::StreamExt;
996    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
997    /// let tick = process.tick();
998    /// // ticks are lazy by default, forces the second tick to run
999    /// tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1000    ///
1001    /// let batch_first_tick = process
1002    ///   .source_iter(q!(vec![1]))
1003    ///   .batch(&tick, nondet!(/** test */));
1004    /// let batch_second_tick = process
1005    ///   .source_iter(q!(vec![1, 2, 3]))
1006    ///   .batch(&tick, nondet!(/** test */))
1007    ///   .defer_tick(); // appears on the second tick
1008    /// let some_on_first_tick = tick.optional_first_tick(q!(()));
1009    /// batch_first_tick.chain(batch_second_tick).count()
1010    ///   .filter_if_some(some_on_first_tick)
1011    ///   .all_ticks()
1012    /// # }, |mut stream| async move {
1013    /// // [1]
1014    /// # for w in vec![1] {
1015    /// #     assert_eq!(stream.next().await.unwrap(), w);
1016    /// # }
1017    /// # }));
1018    /// # }
1019    /// ```
1020    #[deprecated(note = "use `filter_if` with `Optional::is_some()` instead")]
1021    pub fn filter_if_some<U>(
1022        self,
1023        signal: Optional<U, L, B>,
1024    ) -> Optional<T, L, <B as SingletonBound>::UnderlyingBound>
1025    where
1026        B: IsBounded,
1027    {
1028        self.filter_if(signal.is_some())
1029    }
1030
1031    /// Filters this singleton into an [`Optional`], passing through the singleton value if the
1032    /// argument (a [`Bounded`] [`Optional`]) is null, otherwise the output is null.
1033    ///
1034    /// Like [`Singleton::filter_if_some`], this is useful for conditional processing, but inverts
1035    /// the condition.
1036    ///
1037    /// # Example
1038    /// ```rust
1039    /// # #[cfg(feature = "deploy")] {
1040    /// # use hydro_lang::prelude::*;
1041    /// # use futures::StreamExt;
1042    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1043    /// let tick = process.tick();
1044    /// // ticks are lazy by default, forces the second tick to run
1045    /// tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1046    ///
1047    /// let batch_first_tick = process
1048    ///   .source_iter(q!(vec![1]))
1049    ///   .batch(&tick, nondet!(/** test */));
1050    /// let batch_second_tick = process
1051    ///   .source_iter(q!(vec![1, 2, 3]))
1052    ///   .batch(&tick, nondet!(/** test */))
1053    ///   .defer_tick(); // appears on the second tick
1054    /// let some_on_first_tick = tick.optional_first_tick(q!(()));
1055    /// batch_first_tick.chain(batch_second_tick).count()
1056    ///   .filter_if_none(some_on_first_tick)
1057    ///   .all_ticks()
1058    /// # }, |mut stream| async move {
1059    /// // [3]
1060    /// # for w in vec![3] {
1061    /// #     assert_eq!(stream.next().await.unwrap(), w);
1062    /// # }
1063    /// # }));
1064    /// # }
1065    /// ```
1066    #[deprecated(note = "use `filter_if` with `!Optional::is_some()` instead")]
1067    pub fn filter_if_none<U>(
1068        self,
1069        other: Optional<U, L, B>,
1070    ) -> Optional<T, L, <B as SingletonBound>::UnderlyingBound>
1071    where
1072        B: IsBounded,
1073    {
1074        self.filter_if(other.is_none())
1075    }
1076
1077    /// Returns a [`Singleton`] containing `true` if this singleton's value equals the other's.
1078    ///
1079    /// # Example
1080    /// ```rust
1081    /// # #[cfg(feature = "deploy")] {
1082    /// # use hydro_lang::prelude::*;
1083    /// # use futures::StreamExt;
1084    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1085    /// let tick = process.tick();
1086    /// # // ticks are lazy by default, forces the tick to run
1087    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1088    /// let a = tick.singleton(q!(5));
1089    /// let b = tick.singleton(q!(5));
1090    /// a.equals(b).all_ticks()
1091    /// # }, |mut stream| async move {
1092    /// // [true]
1093    /// # assert_eq!(stream.next().await.unwrap(), true);
1094    /// # }));
1095    /// # }
1096    /// ```
1097    pub fn equals(self, other: Singleton<T, L, B>) -> Singleton<bool, L, B>
1098    where
1099        T: PartialEq,
1100        B: IsBounded,
1101    {
1102        self.zip(other).map(q!(|(a, b)| a == b))
1103    }
1104
1105    /// Returns a [`Stream`] that emits an event the first time the singleton has a value that is
1106    /// greater than or equal to the provided threshold. The event will have the value of the
1107    /// given threshold.
1108    ///
1109    /// This requires the incoming singleton to be monotonic, because otherwise the detection of
1110    /// the threshold would be non-deterministic.
1111    ///
1112    /// # Example
1113    /// ```rust
1114    /// # #[cfg(feature = "deploy")] {
1115    /// # use hydro_lang::prelude::*;
1116    /// # use futures::StreamExt;
1117    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1118    /// let a = // singleton 1 ~> 5 ~> 10
1119    /// # process.singleton(q!(5));
1120    /// let b = process.singleton(q!(4));
1121    /// a.threshold_greater_or_equal(b)
1122    /// # }, |mut stream| async move {
1123    /// // [4]
1124    /// # assert_eq!(stream.next().await.unwrap(), 4);
1125    /// # }));
1126    /// # }
1127    /// ```
1128    pub fn threshold_greater_or_equal<B2: IsBounded>(
1129        self,
1130        threshold: Singleton<T, L, B2>,
1131    ) -> Stream<T, L, B::UnderlyingBound>
1132    where
1133        T: Clone + PartialOrd,
1134        B: IsMonotonic,
1135    {
1136        let threshold = threshold.make_bounded();
1137        let self_location = self.location().clone();
1138        match self.try_make_bounded() {
1139            Ok(bounded) => {
1140                let uncasted = threshold
1141                    .zip(bounded)
1142                    .into_stream()
1143                    .filter_map(q!(|(t, m)| if m < t { None } else { Some(t) }));
1144
1145                Stream::new(
1146                    uncasted.location.clone(),
1147                    uncasted.ir_node.replace(HydroNode::Placeholder),
1148                )
1149            }
1150            Err(me) if me.location.id().is_root() => {
1151                let updates = me.into_update_stream(nondet!(
1152                    /// The singleton is monotone, so a version crosses the threshold iff every
1153                    /// later version does: stuttering and skipping intermediate versions cannot
1154                    /// change whether (or when the final version shows that) it is crossed.
1155                ));
1156                let uncasted = sliced! {
1157                    let batch = use::batch(updates, nondet!(/** thresholds are deterministic */));
1158                    let mut remaining_threshold = use::state(|l| {
1159                        let as_option: Optional<_, _, _> = threshold.clone_into_tick(l).into();
1160                        as_option
1161                    });
1162                    let latest = batch.last();
1163
1164                    // A firing without new versions (`latest` is null) must keep the remaining
1165                    // threshold: drop it only once it has been passed.
1166                    let passed = remaining_threshold
1167                        .clone()
1168                        .zip(latest)
1169                        .filter(q!(|(t, m)| m >= t))
1170                        .map(q!(|(t, _)| t));
1171                    remaining_threshold = remaining_threshold.filter_if(!passed.clone().is_some());
1172                    passed.into_stream()
1173                };
1174
1175                Stream::new(
1176                    self_location,
1177                    uncasted.ir_node.replace(HydroNode::Placeholder),
1178                )
1179            }
1180            Err(me) => {
1181                let uncasted = sliced! {
1182                    let me = use::snapshot(me, nondet!(/** thresholds are deterministic */));
1183                    let mut remaining_threshold = use::state(|l| {
1184                        let as_option: Optional<_, _, _> = threshold.clone_into_tick(l).into();
1185                        as_option
1186                    });
1187
1188                    let (not_passed, passed) = remaining_threshold.zip(me).into_stream().partition(q!(|(t, m)| m < t));
1189                    remaining_threshold = not_passed.first().map(q!(|(t, _)| t));
1190                    passed.map(q!(|(t, _)| t))
1191                };
1192
1193                Stream::new(
1194                    self_location,
1195                    uncasted.ir_node.replace(HydroNode::Placeholder),
1196                )
1197            }
1198        }
1199    }
1200
1201    /// An operator which allows you to "name" a `HydroNode`.
1202    /// This is only used for testing, to correlate certain `HydroNode`s with IDs.
1203    pub fn ir_node_named(self, name: &str) -> Singleton<T, L, B> {
1204        {
1205            let mut node = self.ir_node.borrow_mut();
1206            let metadata = node.metadata_mut();
1207            metadata.tag = Some(name.to_owned());
1208        }
1209        self
1210    }
1211}
1212
1213impl<'a, L: Location<'a>, B: SingletonBound> Not for Singleton<bool, L, B> {
1214    type Output = Singleton<bool, L, B::UnderlyingBound>;
1215
1216    fn not(self) -> Self::Output {
1217        self.map(q!(|b| !b))
1218    }
1219}
1220
1221impl<'a, T, L, B: SingletonBound> Singleton<Option<T>, L, B>
1222where
1223    L: Location<'a>,
1224{
1225    /// Converts a `Singleton<Option<U>, L, B>` into an `Optional<U, L, B>` by unwrapping
1226    /// the inner `Option`.
1227    ///
1228    /// This is implemented as an identity [`Singleton::filter_map`], passing through the
1229    /// `Option<U>` directly. If the singleton's value is `Some(v)`, the resulting
1230    /// [`Optional`] contains `v`; if `None`, the [`Optional`] is empty.
1231    ///
1232    /// # Example
1233    /// ```rust
1234    /// # #[cfg(feature = "deploy")] {
1235    /// # use hydro_lang::prelude::*;
1236    /// # use futures::StreamExt;
1237    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1238    /// let tick = process.tick();
1239    /// # // ticks are lazy by default, forces the tick to run
1240    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1241    /// let singleton = tick.singleton(q!(Some(42)));
1242    /// singleton.into_optional().all_ticks()
1243    /// # }, |mut stream| async move {
1244    /// // 42
1245    /// # assert_eq!(stream.next().await.unwrap(), 42);
1246    /// # }));
1247    /// # }
1248    /// ```
1249    pub fn into_optional(self) -> Optional<T, L, B::UnderlyingBound> {
1250        self.filter_map(q!(|v| v))
1251    }
1252}
1253
1254impl<'a, L, B: SingletonBound> Singleton<bool, L, B>
1255where
1256    L: Location<'a>,
1257{
1258    /// Returns a [`Singleton`] containing the logical AND of this and another boolean singleton.
1259    ///
1260    /// # Example
1261    /// ```rust
1262    /// # #[cfg(feature = "deploy")] {
1263    /// # use hydro_lang::prelude::*;
1264    /// # use futures::StreamExt;
1265    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1266    /// let tick = process.tick();
1267    /// // ticks are lazy by default, forces the second tick to run
1268    /// tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1269    ///
1270    /// let a = tick.optional_first_tick(q!(())).is_some(); // true, false
1271    /// let b = tick.singleton(q!(true)); // true, true
1272    /// a.and(b).all_ticks()
1273    /// # }, |mut stream| async move {
1274    /// // [true, false]
1275    /// # for w in vec![true, false] {
1276    /// #     assert_eq!(stream.next().await.unwrap(), w);
1277    /// # }
1278    /// # }));
1279    /// # }
1280    /// ```
1281    pub fn and(self, other: Singleton<bool, L, B>) -> Singleton<bool, L, Bounded>
1282    where
1283        B: IsBounded,
1284    {
1285        zip_singletons(self, other)
1286            .map(q!(|(a, b)| a && b))
1287            .make_bounded()
1288    }
1289
1290    /// Returns a [`Singleton`] containing the logical OR of this and another boolean singleton.
1291    ///
1292    /// # Example
1293    /// ```rust
1294    /// # #[cfg(feature = "deploy")] {
1295    /// # use hydro_lang::prelude::*;
1296    /// # use futures::StreamExt;
1297    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1298    /// let tick = process.tick();
1299    /// // ticks are lazy by default, forces the second tick to run
1300    /// tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1301    ///
1302    /// let a = tick.optional_first_tick(q!(())).is_some(); // true, false
1303    /// let b = tick.singleton(q!(false)); // false, false
1304    /// a.or(b).all_ticks()
1305    /// # }, |mut stream| async move {
1306    /// // [true, false]
1307    /// # for w in vec![true, false] {
1308    /// #     assert_eq!(stream.next().await.unwrap(), w);
1309    /// # }
1310    /// # }));
1311    /// # }
1312    /// ```
1313    pub fn or(self, other: Singleton<bool, L, B>) -> Singleton<bool, L, Bounded>
1314    where
1315        B: IsBounded,
1316    {
1317        zip_singletons(self, other)
1318            .map(q!(|(a, b)| a || b))
1319            .make_bounded()
1320    }
1321}
1322
1323impl<'a, T, L, B: SingletonBound> Singleton<T, Atomic<L>, B>
1324where
1325    L: Location<'a>,
1326{
1327    /// Returns a singleton value corresponding to the latest snapshot of the singleton
1328    /// being atomically processed. The snapshot at tick `t + 1` is guaranteed to include
1329    /// at least all relevant data that contributed to the snapshot at tick `t`. Furthermore,
1330    /// all snapshots of this singleton into the atomic-associated tick will observe the
1331    /// same value each tick.
1332    ///
1333    /// # Non-Determinism
1334    /// Because this picks a snapshot of a singleton whose value is continuously changing,
1335    /// the output singleton has a non-deterministic value since the snapshot can be at an
1336    /// arbitrary point in time.
1337    pub fn snapshot_atomic<L2: Location<'a, DropConsistency = L::DropConsistency>>(
1338        self,
1339        tick: &Tick<L2>,
1340        mut nondet: NonDet<Option<crate::sim_hooks::SnapshotHook<T, L::SimHookScope>>>,
1341    ) -> Singleton<T, Tick<L::DropConsistency>, Bounded> {
1342        assert_eq!(
1343            Location::id(tick.parent_location()),
1344            Location::id(self.location.tick.parent_location())
1345        );
1346
1347        let mut metadata =
1348            tick.new_node_metadata(Singleton::<T, Tick<L>, Bounded>::collection_kind());
1349
1350        metadata.op.sim_hook_id = nondet.take_hook().map(|h| h.id);
1351        Singleton::new(
1352            tick.drop_consistency(),
1353            HydroNode::Snapshot {
1354                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1355                metadata,
1356            },
1357        )
1358    }
1359}
1360
1361impl<'a, T, L, B: SingletonBound> Singleton<T, L, B>
1362where
1363    L: Location<'a>,
1364{
1365    /// Given a tick, returns a singleton value corresponding to a snapshot of the singleton
1366    /// as of that tick. The snapshot at tick `t + 1` is guaranteed to include at least all
1367    /// relevant data that contributed to the snapshot at tick `t`.
1368    ///
1369    /// # Non-Determinism
1370    /// Because this picks a snapshot of a singleton whose value is continuously changing,
1371    /// the output singleton has a non-deterministic value since the snapshot can be at an
1372    /// arbitrary point in time.
1373    ///
1374    /// In simulation tests, the snapshot decisions can be scripted by attaching a
1375    /// [`SnapshotHook`](crate::sim_hooks::SnapshotHook) to the guard via
1376    /// `nondet!(/** reason */ hook = my_hook)`.
1377    pub fn snapshot<L2: Location<'a, DropConsistency = L::DropConsistency>>(
1378        self,
1379        tick: &Tick<L2>,
1380        mut nondet: NonDet<Option<crate::sim_hooks::SnapshotHook<T, L::SimHookScope>>>,
1381    ) -> Singleton<T, Tick<L::DropConsistency>, Bounded> {
1382        assert_eq!(
1383            Location::id(tick.parent_location()),
1384            Location::id(&self.location)
1385        );
1386
1387        let mut metadata =
1388            tick.new_node_metadata(Singleton::<T, Tick<L>, Bounded>::collection_kind());
1389        metadata.op.sim_hook_id = nondet.take_hook().map(|h| h.id);
1390        Singleton::new(
1391            tick.drop_consistency(),
1392            HydroNode::Snapshot {
1393                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1394                metadata,
1395            },
1396        )
1397    }
1398
1399    /// Eagerly samples the singleton as fast as possible, returning a stream of snapshots
1400    /// with order corresponding to increasing prefixes of data contributing to the singleton.
1401    ///
1402    /// # Non-Determinism
1403    /// At runtime, the singleton will be arbitrarily sampled as fast as possible, but due
1404    /// to non-deterministic batching and arrival of inputs, the output stream is
1405    /// non-deterministic.
1406    ///
1407    /// In simulation tests, the internal snapshot decisions can be scripted by attaching
1408    /// a [`SnapshotHook`](crate::sim_hooks::SnapshotHook) to the guard via
1409    /// `nondet!(/** reason */ hook = my_hook)`.
1410    pub fn sample_eager(
1411        self,
1412        mut nondet: NonDet<Option<crate::sim_hooks::SnapshotHook<T, L::SimHookScope>>>,
1413    ) -> Stream<T, L::DropConsistency, Unbounded, TotalOrder, AtLeastOnce> {
1414        let snapshot_hook = nondet.take_hook();
1415        if self.location.id().is_root() {
1416            assert!(
1417                snapshot_hook.is_none(),
1418                "sim hooks are not supported on `sample_eager` of a root-located singleton"
1419            );
1420            let updates = self.into_update_stream(nondet!(
1421                /// which versions are sampled is captured by the caller's guard
1422            ));
1423            // Sample the latest version in each batch of updates. Batching (explored by the
1424            // simulator) determines which versions are skipped.
1425            sliced! {
1426                let batch = use::batch(updates, nondet!(
1427                    /// which versions are sampled is captured by the caller's guard
1428                ));
1429                batch.last().into_stream()
1430            }
1431            .weaken_retries()
1432        } else {
1433            sliced! {
1434                let snapshot = use::snapshot(self, nondet!(
1435                    /// which snapshots are sampled is captured by the caller's guard
1436                    hook = snapshot_hook
1437                ));
1438                snapshot.into_stream()
1439            }
1440            .weaken_retries()
1441        }
1442    }
1443
1444    /// Given a time interval, returns a stream corresponding to snapshots of the singleton
1445    /// value taken at various points in time. Because the input singleton may be
1446    /// [`Unbounded`], there are no guarantees on what these snapshots are other than they
1447    /// represent the value of the singleton given some prefix of the streams leading up to
1448    /// it.
1449    ///
1450    /// # Non-Determinism
1451    /// The output stream is non-deterministic in which elements are sampled, since this
1452    /// is controlled by a clock.
1453    ///
1454    /// In simulation tests, the internal snapshot decisions and the batching of clock
1455    /// samples can be scripted through the guard's composite hook payload, e.g.
1456    /// `nondet!(/** reason */ hook = (snapshot_hook.into(), None))`.
1457    #[cfg(feature = "tokio")]
1458    #[expect(
1459        clippy::type_complexity,
1460        reason = "composite hook payload names each internal operator's handle type"
1461    )]
1462    pub fn sample_every(
1463        self,
1464        interval: impl QuotedWithContext<'a, std::time::Duration, L> + Copy + 'a,
1465        mut nondet: NonDet<(
1466            Option<crate::sim_hooks::SnapshotHook<T, L::SimHookScope>>,
1467            Option<crate::sim_hooks::BatchHook<(), TotalOrder, AtLeastOnce, L::SimHookScope>>,
1468        )>,
1469    ) -> Stream<T, L::DropConsistency, Unbounded, TotalOrder, AtLeastOnce>
1470    where
1471        L: TopLevel<'a>,
1472    {
1473        let samples = self.location.source_interval(interval);
1474        let (snapshot_hook, samples_hook) = nondet.take_hook();
1475        sliced! {
1476            let snapshot = use::snapshot(self, nondet!(
1477                /// which snapshots are sampled is captured by the caller's guard
1478                hook = snapshot_hook
1479            ));
1480            let sample_batch = use::batch(samples, nondet!(
1481                /// sample timing is captured by the caller's guard
1482                hook = samples_hook
1483            ));
1484
1485            snapshot.filter_if(sample_batch.first().is_some()).into_stream()
1486        }
1487        .weaken_retries()
1488    }
1489
1490    /// Strengthens the boundedness guarantee to `Bounded`, given that `B: IsBounded`, which
1491    /// implies that `B == Bounded`.
1492    pub fn make_bounded(self) -> Singleton<T, L, Bounded>
1493    where
1494        B: IsBounded,
1495    {
1496        Singleton::new(
1497            self.location.clone(),
1498            self.ir_node.replace(HydroNode::Placeholder),
1499        )
1500    }
1501
1502    fn try_make_bounded(self) -> Result<Singleton<T, L, Bounded>, Singleton<T, L, B>> {
1503        if B::UnderlyingBound::BOUNDED {
1504            Ok(Singleton::new(
1505                self.location.clone(),
1506                self.ir_node.replace(HydroNode::Placeholder),
1507            ))
1508        } else {
1509            Err(self)
1510        }
1511    }
1512
1513    /// Clones this bounded singleton into a tick, returning a singleton that has the
1514    /// same value as the outer singleton. Because the outer singleton is bounded, this
1515    /// is deterministic because there is only a single immutable version.
1516    pub fn clone_into_tick<L2: Location<'a, DropConsistency = L::DropConsistency>>(
1517        self,
1518        tick: &Tick<L2>,
1519    ) -> Singleton<T, Tick<L2>, Bounded>
1520    where
1521        B: IsBounded,
1522        T: Clone,
1523    {
1524        // TODO(shadaj): avoid printing simulator logs for this snapshot
1525        let inner = self.snapshot(
1526            tick,
1527            nondet!(/** bounded top-level singleton so deterministic */),
1528        );
1529        Singleton::new(tick.clone(), inner.ir_node.replace(HydroNode::Placeholder))
1530    }
1531
1532    /// Converts this singleton into a [`Stream`] containing a single element, the value.
1533    ///
1534    /// # Example
1535    /// ```rust
1536    /// # #[cfg(feature = "deploy")] {
1537    /// # use hydro_lang::prelude::*;
1538    /// # use futures::StreamExt;
1539    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1540    /// let tick = process.tick();
1541    /// let batch_input = process
1542    ///   .source_iter(q!(vec![123, 456]))
1543    ///   .batch(&tick, nondet!(/** test */));
1544    /// batch_input.clone().chain(
1545    ///   batch_input.count().into_stream()
1546    /// ).all_ticks()
1547    /// # }, |mut stream| async move {
1548    /// // [123, 456, 2]
1549    /// # for w in vec![123, 456, 2] {
1550    /// #     assert_eq!(stream.next().await.unwrap(), w);
1551    /// # }
1552    /// # }));
1553    /// # }
1554    /// ```
1555    pub fn into_stream(self) -> Stream<T, L, Bounded, TotalOrder, ExactlyOnce>
1556    where
1557        B: IsBounded,
1558    {
1559        Stream::new(
1560            self.location.clone(),
1561            HydroNode::Cast {
1562                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1563                metadata: self.location.new_node_metadata(Stream::<
1564                    T,
1565                    Tick<L>,
1566                    Bounded,
1567                    TotalOrder,
1568                    ExactlyOnce,
1569                >::collection_kind()),
1570            },
1571        )
1572    }
1573
1574    /// Resolves the singleton's [`Future`] value by blocking until it completes,
1575    /// producing a singleton of the resolved output.
1576    ///
1577    /// This is useful when the singleton contains an async computation that must
1578    /// be awaited before further processing. The future is polled to completion
1579    /// before the output value is emitted.
1580    ///
1581    /// # Example
1582    /// ```rust
1583    /// # #[cfg(feature = "deploy")] {
1584    /// # use hydro_lang::prelude::*;
1585    /// # use futures::StreamExt;
1586    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1587    /// let tick = process.tick();
1588    /// # // ticks are lazy by default, forces the tick to run
1589    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1590    /// let singleton = tick.singleton(q!(5));
1591    /// singleton
1592    ///     .map(q!(|v| async move { v * 2 }))
1593    ///     .resolve_future_blocking()
1594    ///     .all_ticks()
1595    /// # }, |mut stream| async move {
1596    /// // 10
1597    /// # assert_eq!(stream.next().await.unwrap(), 10);
1598    /// # }));
1599    /// # }
1600    /// ```
1601    pub fn resolve_future_blocking(
1602        self,
1603    ) -> Singleton<T::Output, L, <B as SingletonBound>::UnderlyingBound>
1604    where
1605        T: Future,
1606        B: IsBounded,
1607    {
1608        Singleton::new(
1609            self.location.clone(),
1610            HydroNode::ResolveFuturesBlocking {
1611                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1612                metadata: self
1613                    .location
1614                    .new_node_metadata(Singleton::<T::Output, L, B>::collection_kind()),
1615            },
1616        )
1617    }
1618}
1619
1620impl<'a, T, L> Singleton<T, Tick<L>, Bounded>
1621where
1622    L: Location<'a>,
1623{
1624    /// Asynchronously yields the value of this singleton outside the tick as an unbounded stream,
1625    /// which will stream the value computed in _each_ tick as a separate stream element.
1626    ///
1627    /// Unlike [`Singleton::latest`], the value computed in each tick is emitted separately,
1628    /// producing one element in the output for each tick. This is useful for batched computations,
1629    /// where the results from each tick must be combined together.
1630    ///
1631    /// # Example
1632    /// ```rust
1633    /// # #[cfg(feature = "deploy")] {
1634    /// # use hydro_lang::prelude::*;
1635    /// # use futures::StreamExt;
1636    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1637    /// let tick = process.tick();
1638    /// # // ticks are lazy by default, forces the second tick to run
1639    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1640    /// # let batch_first_tick = process
1641    /// #   .source_iter(q!(vec![1]))
1642    /// #   .batch(&tick, nondet!(/** test */));
1643    /// # let batch_second_tick = process
1644    /// #   .source_iter(q!(vec![1, 2, 3]))
1645    /// #   .batch(&tick, nondet!(/** test */))
1646    /// #   .defer_tick(); // appears on the second tick
1647    /// # let input_batch = batch_first_tick.chain(batch_second_tick);
1648    /// input_batch // first tick: [1], second tick: [1, 2, 3]
1649    ///     .count()
1650    ///     .all_ticks()
1651    /// # }, |mut stream| async move {
1652    /// // [1, 3]
1653    /// # for w in vec![1, 3] {
1654    /// #     assert_eq!(stream.next().await.unwrap(), w);
1655    /// # }
1656    /// # }));
1657    /// # }
1658    /// ```
1659    pub fn all_ticks(self) -> Stream<T, L, Unbounded, TotalOrder, ExactlyOnce> {
1660        self.into_stream().all_ticks()
1661    }
1662
1663    /// Synchronously yields the value of this singleton outside the tick as an unbounded stream,
1664    /// which will stream the value computed in _each_ tick as a separate stream element.
1665    ///
1666    /// Unlike [`Singleton::all_ticks`], this preserves synchronous execution, as the output stream
1667    /// is emitted in an [`Atomic`] context that will process elements synchronously with the input
1668    /// singleton's [`Tick`] context.
1669    pub fn all_ticks_atomic(self) -> Stream<T, Atomic<L>, Unbounded, TotalOrder, ExactlyOnce> {
1670        self.into_stream().all_ticks_atomic()
1671    }
1672
1673    /// Asynchronously yields this singleton outside the tick as an unbounded [`Optional`], which
1674    /// will be asynchronously updated with the latest value of the singleton inside the tick.
1675    ///
1676    /// The result is an [`Optional`] rather than a [`Singleton`] because the producing tick does
1677    /// not have to have run yet: before its first run there is no value, so the optional is null.
1678    /// Once the tick has run the optional becomes non-null and stays non-null (its value tracks
1679    /// the latest tick), hence the [`InitNone`] boundedness.
1680    ///
1681    /// This converts a bounded value _inside_ a tick into an asynchronous value outside the
1682    /// tick that tracks the inner value. This is useful for getting the value as of the
1683    /// "most recent" tick, but note that updates are propagated asynchronously outside the tick.
1684    ///
1685    /// # Example
1686    /// ```rust
1687    /// # #[cfg(feature = "deploy")] {
1688    /// # use hydro_lang::prelude::*;
1689    /// # use futures::StreamExt;
1690    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1691    /// let tick = process.tick();
1692    /// # // ticks are lazy by default, forces the second tick to run
1693    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1694    /// # let batch_first_tick = process
1695    /// #   .source_iter(q!(vec![1]))
1696    /// #   .batch(&tick, nondet!(/** test */));
1697    /// # let batch_second_tick = process
1698    /// #   .source_iter(q!(vec![1, 2, 3]))
1699    /// #   .batch(&tick, nondet!(/** test */))
1700    /// #   .defer_tick(); // appears on the second tick
1701    /// # let input_batch = batch_first_tick.chain(batch_second_tick);
1702    /// input_batch // first tick: [1], second tick: [1, 2, 3]
1703    ///     .count()
1704    ///     .latest()
1705    ///     .unwrap_or(process.singleton(q!(0usize)).into())
1706    /// # .sample_eager(nondet!(/** test */))
1707    /// # }, |mut stream| async move {
1708    /// // asynchronously changes from 1 ~> 3
1709    /// # for w in vec![1, 3] {
1710    /// #     assert_eq!(stream.next().await.unwrap(), w);
1711    /// # }
1712    /// # }));
1713    /// # }
1714    /// ```
1715    pub fn latest(self) -> Optional<T, L, InitNone> {
1716        Optional::new(
1717            self.location.parent_location().clone(),
1718            HydroNode::YieldConcat {
1719                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1720                metadata: self
1721                    .location
1722                    .parent_location()
1723                    .new_node_metadata(Optional::<T, L, InitNone>::collection_kind()),
1724            },
1725        )
1726    }
1727
1728    /// Synchronously yields this singleton outside the tick as an unbounded [`Optional`], which
1729    /// will be updated with the latest value of the singleton inside the tick.
1730    ///
1731    /// Unlike [`Singleton::latest`], this preserves synchronous execution, as the output optional
1732    /// is emitted in an [`Atomic`] context that will process elements synchronously with the input
1733    /// singleton's [`Tick`] context. As with [`Singleton::latest`], the result is an [`Optional`]
1734    /// ([`InitNone`]) because it is null until the producing tick first runs.
1735    pub fn latest_atomic(self) -> Optional<T, Atomic<L>, InitNone> {
1736        let out_location = Atomic {
1737            tick: self.location.clone(),
1738        };
1739        Optional::new(
1740            out_location.clone(),
1741            HydroNode::YieldConcat {
1742                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1743                metadata: out_location
1744                    .new_node_metadata(Optional::<T, Atomic<L>, InitNone>::collection_kind()),
1745            },
1746        )
1747    }
1748}
1749
1750#[doc(hidden)]
1751/// Helper trait that determines the output collection type for [`Singleton::zip`].
1752///
1753/// The output will be an [`Optional`] if the second input is an [`Optional`], otherwise it is a
1754/// [`Singleton`].
1755#[sealed::sealed]
1756pub trait ZipResult<'a, Other> {
1757    /// The output collection type.
1758    type Out;
1759    /// The type of the tupled output value.
1760    type ElementType;
1761    /// The type of the other collection's value.
1762    type OtherType;
1763    /// The location where the tupled result will be materialized.
1764    type Location: Location<'a>;
1765
1766    /// The location of the second input to the `zip`.
1767    fn other_location(other: &Other) -> Self::Location;
1768    /// The IR node of the second input to the `zip`.
1769    fn other_ir_node(other: Other) -> HydroNode;
1770
1771    /// Constructs the output live collection given an IR node containing the zip result.
1772    fn make(location: Self::Location, ir_node: HydroNode) -> Self::Out;
1773}
1774
1775#[sealed::sealed]
1776impl<'a, T, U, L, B: SingletonBound> ZipResult<'a, Singleton<U, L, B>> for Singleton<T, L, B>
1777where
1778    L: Location<'a>,
1779{
1780    type Out = Singleton<(T, U), L, B>;
1781    type ElementType = (T, U);
1782    type OtherType = U;
1783    type Location = L;
1784
1785    fn other_location(other: &Singleton<U, L, B>) -> L {
1786        other.location.clone()
1787    }
1788
1789    fn other_ir_node(other: Singleton<U, L, B>) -> HydroNode {
1790        other.ir_node.replace(HydroNode::Placeholder)
1791    }
1792
1793    fn make(location: L, ir_node: HydroNode) -> Self::Out {
1794        Singleton::new(
1795            location.clone(),
1796            HydroNode::Cast {
1797                inner: Box::new(ir_node),
1798                metadata: location.new_node_metadata(Self::Out::collection_kind()),
1799            },
1800        )
1801    }
1802}
1803
1804#[sealed::sealed]
1805impl<'a, T, U, L, B: SingletonBound> ZipResult<'a, Optional<U, L, B::UnderlyingBound>>
1806    for Singleton<T, L, B>
1807where
1808    L: Location<'a>,
1809{
1810    type Out = Optional<(T, U), L, B::UnderlyingBound>;
1811    type ElementType = (T, U);
1812    type OtherType = U;
1813    type Location = L;
1814
1815    fn other_location(other: &Optional<U, L, B::UnderlyingBound>) -> L {
1816        other.location.clone()
1817    }
1818
1819    fn other_ir_node(other: Optional<U, L, B::UnderlyingBound>) -> HydroNode {
1820        other.ir_node.replace(HydroNode::Placeholder)
1821    }
1822
1823    fn make(location: L, ir_node: HydroNode) -> Self::Out {
1824        // The zip lowering may hand us an `Unbounded` optional node (from `latest()`); cast
1825        // to this impl's output kind. At the root the representations differ (tombstoned
1826        // update feed vs. plain values), so the cast must be present for codegen to insert
1827        // the conversion.
1828        Optional::new(
1829            location.clone(),
1830            HydroNode::Cast {
1831                inner: Box::new(ir_node),
1832                metadata: location.new_node_metadata(Self::Out::collection_kind()),
1833            },
1834        )
1835    }
1836}
1837
1838#[cfg(test)]
1839mod tests {
1840    #[cfg(feature = "deploy")]
1841    use futures::{SinkExt, StreamExt};
1842    #[cfg(feature = "deploy")]
1843    use hydro_deploy::Deployment;
1844    #[cfg(any(feature = "deploy", feature = "sim"))]
1845    use stageleft::q;
1846
1847    #[cfg(any(feature = "deploy", feature = "sim"))]
1848    use crate::compile::builder::FlowBuilder;
1849    #[cfg(any(feature = "deploy", feature = "sim"))]
1850    use crate::live_collections::stream::ExactlyOnce;
1851    #[cfg(feature = "sim")]
1852    use crate::live_collections::stream::TotalOrder;
1853    #[cfg(any(feature = "deploy", feature = "sim"))]
1854    use crate::location::Location;
1855    #[cfg(any(feature = "deploy", feature = "sim"))]
1856    use crate::nondet::nondet;
1857
1858    #[cfg(feature = "deploy")]
1859    #[tokio::test]
1860    async fn tick_cycle_cardinality() {
1861        let mut deployment = Deployment::new();
1862
1863        let mut flow = FlowBuilder::new();
1864        let node = flow.process::<()>();
1865        let external = flow.external::<()>();
1866
1867        let (input_send, input) = node.source_external_bincode::<_, _, _, ExactlyOnce>(&external);
1868
1869        let node_tick = node.tick();
1870        let (complete_cycle, singleton) = node_tick.cycle_with_initial(node_tick.singleton(q!(0)));
1871        let counts = singleton
1872            .clone()
1873            .into_stream()
1874            .count()
1875            .filter_if(
1876                input
1877                    .batch(&node_tick, nondet!(/** testing */))
1878                    .first()
1879                    .is_some(),
1880            )
1881            .all_ticks()
1882            .send_bincode_external(&external);
1883        complete_cycle.complete_next_tick(singleton);
1884
1885        let nodes = flow
1886            .with_process(&node, deployment.Localhost())
1887            .with_external(&external, deployment.Localhost())
1888            .deploy(&mut deployment);
1889
1890        deployment.deploy().await.unwrap();
1891
1892        let mut tick_trigger = nodes.connect(input_send).await;
1893        let mut external_out = nodes.connect(counts).await;
1894
1895        deployment.start().await.unwrap();
1896
1897        tick_trigger.send(()).await.unwrap();
1898
1899        assert_eq!(external_out.next().await.unwrap(), 1);
1900
1901        tick_trigger.send(()).await.unwrap();
1902
1903        assert_eq!(external_out.next().await.unwrap(), 1);
1904    }
1905
1906    /// A top-level (unbounded) `fold` whose input never receives anything must still hold its
1907    /// initial value: its update feed has to carry the initial value even with no input. The
1908    /// snapshot is driven by a separate read input, so the tick fires regardless of whether
1909    /// snapshots trigger ticks.
1910    #[cfg(feature = "deploy")]
1911    #[tokio::test]
1912    async fn top_level_fold_without_input_has_initial_value() {
1913        let mut deployment = Deployment::new();
1914
1915        let mut flow = FlowBuilder::new();
1916        let node = flow.process::<()>();
1917        let external = flow.external::<()>();
1918
1919        let (values_send, values) = node.source_external_bincode::<_, _, _, ExactlyOnce>(&external);
1920        let (read_send, reads) = node.source_external_bincode::<_, _, _, ExactlyOnce>(&external);
1921
1922        let folded = values.fold(q!(|| 5), q!(|acc: &mut i32, v: i32| *acc += v));
1923
1924        let out = crate::live_collections::sliced::sliced! {
1925            let reads = use::batch(reads, nondet!(/** test */));
1926            let value = use::snapshot(folded, nondet!(/** test */));
1927            reads.cross_singleton(value).map(q!(|((), value)| value))
1928        }
1929        .send_bincode_external(&external);
1930
1931        let nodes = flow
1932            .with_process(&node, deployment.Localhost())
1933            .with_external(&external, deployment.Localhost())
1934            .deploy(&mut deployment);
1935
1936        deployment.deploy().await.unwrap();
1937
1938        // Connected but never written to: the fold never receives any input.
1939        let _values_send = nodes.connect(values_send).await;
1940        let mut read_send = nodes.connect(read_send).await;
1941        let mut out = nodes.connect(out).await;
1942
1943        deployment.start().await.unwrap();
1944
1945        read_send.send(()).await.unwrap();
1946        assert_eq!(out.next().await.unwrap(), 5);
1947
1948        read_send.send(()).await.unwrap();
1949        assert_eq!(out.next().await.unwrap(), 5);
1950    }
1951
1952    #[cfg(feature = "sim")]
1953    #[test]
1954    #[should_panic]
1955    fn sim_fold_intermediate_states() {
1956        let mut flow = FlowBuilder::new();
1957        let node = flow.process::<()>();
1958
1959        let source = node.source_stream(q!(tokio_stream::iter(vec![1, 2, 3, 4])));
1960        let folded = source.fold(q!(|| 0), q!(|a, b| *a += b));
1961
1962        // Snapshot ingress is lazy and never wakes the tick on its own, so an auxiliary
1963        // trigger stream drives the tick.
1964        let (trigger_port, trigger) = node.sim_input::<i32, TotalOrder, ExactlyOnce>();
1965
1966        let tick = node.tick();
1967        let batch = trigger
1968            .batch(&tick, nondet!(/** test */))
1969            .cross_singleton(folded.snapshot(&tick, nondet!(/** test */)))
1970            .map(q!(|(_, v)| v));
1971        let out_recv = batch.all_ticks().sim_output();
1972
1973        flow.sim().exhaustive(async || {
1974            trigger_port.send(1);
1975            assert_eq!(out_recv.next().await, 10);
1976        });
1977    }
1978
1979    #[cfg(feature = "sim")]
1980    #[test]
1981    fn sim_fold_intermediate_state_count() {
1982        let mut flow = FlowBuilder::new();
1983        let node = flow.process::<()>();
1984
1985        let source = node.source_stream(q!(tokio_stream::iter(vec![1, 2, 3, 4])));
1986        let folded = source.fold(q!(|| 0), q!(|a, b| *a += b));
1987
1988        // Snapshot ingress is lazy and never wakes the tick on its own, so an auxiliary
1989        // trigger stream drives the tick.
1990        let (trigger_port, trigger) = node.sim_input::<i32, TotalOrder, ExactlyOnce>();
1991
1992        let tick = node.tick();
1993        let batch = trigger
1994            .batch(&tick, nondet!(/** test */))
1995            .cross_singleton(folded.snapshot(&tick, nondet!(/** test */)))
1996            .map(q!(|(_, v)| v));
1997        let out_recv = batch.all_ticks().sim_output();
1998
1999        let mut observed = std::collections::HashSet::new();
2000
2001        let instance_count = flow.sim().exhaustive(async || {
2002            trigger_port.send(1);
2003            let out = out_recv.collect::<Vec<_>>().await;
2004            // The single trigger drives exactly one tick, which observes exactly one
2005            // intermediate state of the fold.
2006            assert_eq!(out.len(), 1);
2007            observed.insert(out[0]);
2008        });
2009
2010        assert_eq!(
2011            instance_count,
2012            5 // one instance per intermediate state (including the initial state)
2013        );
2014        // Every intermediate state (and only those) must be observable.
2015        assert_eq!(
2016            observed,
2017            [0, 1, 3, 6, 10]
2018                .into_iter()
2019                .collect::<std::collections::HashSet<_>>()
2020        );
2021    }
2022
2023    #[cfg(feature = "sim")]
2024    #[test]
2025    fn sim_fold_snapshot_alone_never_fires_tick() {
2026        // Snapshot ingress is lazy: a new fold version never wakes the tick on its own,
2027        // so a tick whose only ingress is a snapshot never fires and produces no output.
2028        // (Before snapshots were lazy, this program released the initial state and then
2029        // each new state exactly once, without repeats.)
2030
2031        let mut flow = FlowBuilder::new();
2032        let node = flow.process::<()>();
2033
2034        let (in_port, input) = node.sim_input();
2035        let folded = input.fold(q!(|| 0), q!(|a, b| *a += b));
2036
2037        let tick = node.tick();
2038        let batch = folded.snapshot(&tick, nondet!(/** test */));
2039        let out_recv = batch.all_ticks().sim_output();
2040
2041        flow.sim().exhaustive(async || {
2042            in_port.send(123);
2043
2044            assert_eq!(out_recv.collect::<Vec<_>>().await, Vec::<i32>::new());
2045        });
2046    }
2047
2048    #[cfg(feature = "sim")]
2049    #[test]
2050    #[should_panic]
2051    fn sim_fold_repeats_snapshots() {
2052        // when the tick is driven by a snapshot AND something else, the snapshot can
2053        // "stutter" and repeat the same state multiple times
2054
2055        let mut flow = FlowBuilder::new();
2056        let node = flow.process::<()>();
2057
2058        let source = node.source_stream(q!(tokio_stream::iter(vec![1, 2, 3, 4])));
2059        let folded = source.clone().fold(q!(|| 0), q!(|a, b| *a += b));
2060
2061        let tick = node.tick();
2062        let batch = source
2063            .batch(&tick, nondet!(/** test */))
2064            .cross_singleton(folded.snapshot(&tick, nondet!(/** test */)));
2065        let out_recv = batch.all_ticks().sim_output();
2066
2067        flow.sim().exhaustive(async || {
2068            assert!(
2069                !(out_recv.next().await == (1, 3) && out_recv.next().await == (2, 3)),
2070                "repeated snapshot"
2071            );
2072        });
2073    }
2074
2075    #[cfg(feature = "sim")]
2076    #[test]
2077    fn sim_fold_repeats_snapshots_count() {
2078        // check the number of instances
2079        let mut flow = FlowBuilder::new();
2080        let node = flow.process::<()>();
2081
2082        let source = node.source_stream(q!(tokio_stream::iter(vec![1, 2])));
2083        let folded = source.clone().fold(q!(|| 0), q!(|a, b| *a += b));
2084
2085        let tick = node.tick();
2086        let batch = source
2087            .batch(&tick, nondet!(/** test */))
2088            .cross_singleton(folded.snapshot(&tick, nondet!(/** test */)));
2089        let out_recv = batch.all_ticks().sim_output();
2090
2091        let count = flow.sim().exhaustive(async || {
2092            let _ = out_recv.collect::<Vec<_>>().await;
2093        });
2094
2095        // Snapshots are lazy (they never fire the tick on their own), so every tick is
2096        // driven by a non-empty batch of the source: the explored schedules are the ways
2097        // to split [1, 2] into non-empty batches, crossed with the snapshot's
2098        // keep/reveal choices at each firing.
2099        assert_eq!(count, 9);
2100    }
2101
2102    #[cfg(feature = "sim")]
2103    #[test]
2104    fn sim_top_level_singleton_exhaustive() {
2105        // ensures that top-level singletons have only one snapshot
2106        let mut flow = FlowBuilder::new();
2107        let node = flow.process::<()>();
2108
2109        let singleton = node.singleton(q!(1));
2110        let tick = node.tick();
2111        let batch = singleton.snapshot(&tick, nondet!(/** test */));
2112        let out_recv = batch.all_ticks().sim_output();
2113
2114        let count = flow.sim().exhaustive(async || {
2115            let _ = out_recv.collect::<Vec<_>>().await;
2116        });
2117
2118        assert_eq!(count, 1);
2119    }
2120
2121    #[cfg(feature = "sim")]
2122    #[test]
2123    fn sim_top_level_singleton_join_count() {
2124        // if a tick consumes a static snapshot and a stream batch, only the batch require space
2125        // exploration
2126
2127        let mut flow = FlowBuilder::new();
2128        let node = flow.process::<()>();
2129
2130        let source_iter = node.source_iter(q!(vec![1, 2, 3, 4]));
2131        let tick = node.tick();
2132        let batch = source_iter
2133            .batch(&tick, nondet!(/** test */))
2134            .cross_singleton(node.singleton(q!(123)).clone_into_tick(&tick));
2135        let out_recv = batch.all_ticks().sim_output();
2136
2137        let instance_count = flow.sim().exhaustive(async || {
2138            let _ = out_recv.collect::<Vec<_>>().await;
2139        });
2140
2141        assert_eq!(
2142            instance_count,
2143            8 /* 2^3 ways to split up into non-empty batches (the static snapshot is lazy,
2144               * so it never fires the tick with an empty batch) */
2145        )
2146    }
2147
2148    #[cfg(feature = "sim")]
2149    #[test]
2150    fn top_level_singleton_into_stream_no_replay() {
2151        let mut flow = FlowBuilder::new();
2152        let node = flow.process::<()>();
2153
2154        let source_iter = node.source_iter(q!(vec![1, 2, 3, 4]));
2155        let folded = source_iter.fold(q!(|| 0), q!(|a, b| *a += b));
2156
2157        let out_recv = folded.into_stream().sim_output();
2158
2159        flow.sim().exhaustive(async || {
2160            out_recv.assert_yields_only([10]).await;
2161        });
2162    }
2163
2164    #[cfg(feature = "sim")]
2165    #[test]
2166    fn inside_tick_singleton_zip() {
2167        use crate::live_collections::Stream;
2168        use crate::live_collections::sliced::sliced;
2169
2170        let mut flow = FlowBuilder::new();
2171        let node = flow.process::<()>();
2172
2173        let source_iter: Stream<_, _> = node.source_iter(q!(vec![1, 2])).into();
2174        let folded = source_iter.fold(q!(|| 0), q!(|a, b| *a += b));
2175
2176        // Snapshot ingress is lazy and never wakes the tick on its own, so an auxiliary
2177        // trigger stream drives the tick.
2178        let (trigger_port, trigger) = node.sim_input::<i32, TotalOrder, ExactlyOnce>();
2179
2180        let out_recv = sliced! {
2181            let t = use::batch(trigger, nondet!(/** test */));
2182            let v = use::snapshot(folded, nondet!(/** test */));
2183            t.cross_singleton(v.clone().zip(v)).map(q!(|(_, v)| v))
2184        }
2185        .sim_output();
2186
2187        let mut observed = std::collections::HashSet::new();
2188
2189        let count = flow.sim().exhaustive(async || {
2190            trigger_port.send(1);
2191            let out = out_recv.collect::<Vec<_>>().await;
2192            // The single trigger drives exactly one tick; both zipped uses of the
2193            // snapshot must observe the *same* version.
2194            assert_eq!(out.len(), 1);
2195            let (a, b) = out[0];
2196            assert_eq!(a, b);
2197            observed.insert(a);
2198        });
2199
2200        assert_eq!(count, 3); // one instance per intermediate state (0, 1, 3)
2201        assert_eq!(
2202            observed,
2203            [0, 1, 3]
2204                .into_iter()
2205                .collect::<std::collections::HashSet<_>>()
2206        );
2207    }
2208
2209    /// Reproducer for simulator hang when using `cross_singleton` on a top-level
2210    /// unbounded stream (not inside sliced!). The exhaustive simulator hangs
2211    /// after the first iteration.
2212    #[cfg(feature = "sim")]
2213    #[test]
2214    fn sim_cross_singleton_top_level_unbounded_hang() {
2215        let mut flow = FlowBuilder::new();
2216        let node = flow.process::<()>();
2217
2218        let (cmd_port, input) = node.sim_input::<String, _, _>();
2219
2220        let top_level_singleton = node.singleton(q!(123));
2221
2222        // cross_singleton on a top-level stream - bug trigger
2223        let crossed = input.cross_singleton(top_level_singleton);
2224
2225        // Output directly
2226        let resp_port = crossed.sim_output();
2227
2228        let count = flow.sim().exhaustive(async || {
2229            cmd_port.send("abc".to_owned());
2230
2231            let responses: Vec<_> = resp_port.collect().await;
2232            assert!(!responses.is_empty());
2233        });
2234
2235        assert_eq!(count, 1);
2236    }
2237
2238    #[cfg(feature = "sim")]
2239    #[test]
2240    fn sim_top_level_singleton_state_count() {
2241        let mut flow = FlowBuilder::new();
2242        let process = flow.process::<()>();
2243
2244        let (cmd_port, input) = process.sim_input();
2245        {
2246            // increases exhaustive inputs from 1 to 2 before we optimized `From`
2247            use super::Singleton;
2248            use crate::live_collections::boundedness::Unbounded;
2249            let _singleton: Singleton<_, _, Unbounded> = process.singleton(q!(false)).into();
2250        }
2251        let tick = process.tick();
2252        let batched_unbatched = input.batch(&tick, nondet!(/** */)).all_ticks();
2253        let resp_port = batched_unbatched.sim_output();
2254
2255        let count = flow.sim().exhaustive(async || {
2256            cmd_port.send(());
2257            let _responses: Vec<_> = resp_port.collect().await;
2258        });
2259
2260        assert_eq!(count, 1);
2261    }
2262
2263    /// Regression test for #2939: singleton mut access-group counter resets per root.
2264    /// Two sequential `by_mut` captures on the same singleton, consumed by separate
2265    /// `for_each` roots, should get distinct access groups and build successfully.
2266    #[cfg(feature = "sim")]
2267    #[test]
2268    #[expect(unused_mut, reason = "sliced! macro generates mut bindings for state")]
2269    fn sim_mut_access_group_across_roots() {
2270        use crate::live_collections::sliced::sliced;
2271
2272        let mut flow = FlowBuilder::new();
2273        let node = flow.process::<()>();
2274
2275        let source = node.source_iter(q!(vec![1i32, 2, 3]));
2276
2277        let (first, second) = sliced! {
2278            let batch = use::batch(source, nondet!(/** test */));
2279            let mut total = use::state(|l| l.singleton(q!(0i32)));
2280            let total_mut = total.by_mut();
2281
2282            let first = batch.clone().map(q!(|x| {
2283                *total_mut += x;
2284                *total_mut
2285            }));
2286            let second = batch.map(q!(|x| {
2287                *total_mut += x;
2288                *total_mut
2289            }));
2290            (first, second)
2291        };
2292
2293        let first_recv = first.sim_output();
2294        let second_recv = second.sim_output();
2295
2296        flow.sim().exhaustive(async || {
2297            // Both outputs should produce values without panicking.
2298            // The exact values depend on ordering, but the graph must build.
2299            let _first: Vec<i32> = first_recv.collect().await;
2300            let _second: Vec<i32> = second_recv.collect().await;
2301        });
2302    }
2303
2304    /// Regression test for #2940: access groups must follow code (staging) order,
2305    /// not IR traversal order. When `second.chain(first)` reverses the consumption
2306    /// order, the mutations must still execute in the order they were staged.
2307    #[cfg(feature = "sim")]
2308    #[test]
2309    #[expect(unused_mut, reason = "sliced! macro generates mut bindings for state")]
2310    fn sim_mut_access_groups_follow_code_order() {
2311        use crate::live_collections::sliced::sliced;
2312
2313        let mut flow = FlowBuilder::new();
2314        let node = flow.process::<()>();
2315
2316        let source = node.source_iter(q!(vec![3i32]));
2317
2318        let out_recv = sliced! {
2319            let batch = use::batch(source, nondet!(/** test */));
2320            let mut total = use::state(|l| l.singleton(q!(0i32)));
2321            let total_mut = total.by_mut();
2322
2323            // Defined FIRST in code: addition
2324            let first = batch.clone().map(q!(|x| {
2325                *total_mut += x;
2326                *total_mut
2327            }));
2328            // Defined SECOND in code: doubling
2329            let second = batch.map(q!(|_x| {
2330                *total_mut *= 2;
2331                *total_mut
2332            }));
2333            // Chain in OPPOSITE order of definition — must not affect mutation order.
2334            second.chain(first)
2335        }
2336        .sim_output();
2337
2338        flow.sim().exhaustive(async || {
2339            let results: Vec<i32> = out_recv.collect().await;
2340            // Code-order semantics: first runs (total = 0 + 3 = 3), then second
2341            // runs (total = 3 * 2 = 6). Output is second.chain(first) => [6, 3].
2342            assert_eq!(results, vec![6, 3]);
2343        });
2344    }
2345
2346    /// `threshold_greater_or_equal` of a root monotone singleton emits the threshold exactly
2347    /// once, however the singleton's versions are batched (including several crossing versions
2348    /// in one batch).
2349    #[cfg(feature = "sim")]
2350    #[test]
2351    fn sim_top_level_threshold_greater_or_equal() {
2352        let mut flow = FlowBuilder::new();
2353        let node = flow.process::<()>();
2354
2355        let (input_port, input) = node.sim_input::<u32, TotalOrder, ExactlyOnce>();
2356        let output = input
2357            .count()
2358            .threshold_greater_or_equal(node.singleton(q!(2usize)))
2359            .sim_output();
2360
2361        let count = flow.sim().exhaustive(async || {
2362            input_port.send(1);
2363            input_port.send(2);
2364            input_port.send(3);
2365
2366            assert_eq!(output.collect::<Vec<_>>().await, vec![2]);
2367        });
2368
2369        assert!(count > 1);
2370    }
2371
2372    /// `zip` of two root bounded singletons produces the pair once both sides are present.
2373    #[cfg(feature = "sim")]
2374    #[test]
2375    fn sim_top_level_singleton_zip() {
2376        let mut flow = FlowBuilder::new();
2377        let node = flow.process::<()>();
2378
2379        let (trigger_port, trigger) = node.sim_input::<(), TotalOrder, ExactlyOnce>();
2380
2381        let result = node.singleton(q!(1u32)).zip(node.singleton(q!(2u32)));
2382
2383        let tick = node.tick();
2384        let output = trigger
2385            .batch(&tick, nondet!(/** test */))
2386            .cross_singleton(result.snapshot(&tick, nondet!(/** test */)))
2387            .map(q!(|(_, result)| result))
2388            .all_ticks()
2389            .sim_output();
2390
2391        let mut observed = std::collections::HashSet::new();
2392        let instances = flow.sim().exhaustive(async || {
2393            trigger_port.send(());
2394
2395            observed.insert(output.collect::<Vec<_>>().await);
2396        });
2397        assert_eq!(instances, 8);
2398
2399        // The trigger may fire before the result has a value, in which case nothing is observed.
2400        assert_eq!(observed, [vec![], vec![(1, 2)]].into_iter().collect());
2401    }
2402
2403    /// `and` of two root bounded `bool` singletons (via the internal `zip_bounded`).
2404    #[cfg(feature = "sim")]
2405    #[test]
2406    fn sim_top_level_singleton_and() {
2407        let mut flow = FlowBuilder::new();
2408        let node = flow.process::<()>();
2409
2410        let (trigger_port, trigger) = node.sim_input::<(), TotalOrder, ExactlyOnce>();
2411
2412        let result = node.singleton(q!(true)).and(node.singleton(q!(false)));
2413
2414        let tick = node.tick();
2415        let output = trigger
2416            .batch(&tick, nondet!(/** test */))
2417            .cross_singleton(result.snapshot(&tick, nondet!(/** test */)))
2418            .map(q!(|(_, result)| result))
2419            .all_ticks()
2420            .sim_output();
2421
2422        let mut observed = std::collections::HashSet::new();
2423        let instances = flow.sim().exhaustive(async || {
2424            trigger_port.send(());
2425
2426            observed.insert(output.collect::<Vec<_>>().await);
2427        });
2428        assert_eq!(instances, 8);
2429
2430        // The trigger may fire before the result has a value, in which case nothing is observed.
2431        assert_eq!(observed, [vec![], vec![false]].into_iter().collect());
2432    }
2433
2434    /// `or` of two root bounded `bool` singletons (via the internal `zip_bounded`).
2435    #[cfg(feature = "sim")]
2436    #[test]
2437    fn sim_top_level_singleton_or() {
2438        let mut flow = FlowBuilder::new();
2439        let node = flow.process::<()>();
2440
2441        let (trigger_port, trigger) = node.sim_input::<(), TotalOrder, ExactlyOnce>();
2442
2443        let result = node.singleton(q!(true)).or(node.singleton(q!(false)));
2444
2445        let tick = node.tick();
2446        let output = trigger
2447            .batch(&tick, nondet!(/** test */))
2448            .cross_singleton(result.snapshot(&tick, nondet!(/** test */)))
2449            .map(q!(|(_, result)| result))
2450            .all_ticks()
2451            .sim_output();
2452
2453        let mut observed = std::collections::HashSet::new();
2454        let instances = flow.sim().exhaustive(async || {
2455            trigger_port.send(());
2456
2457            observed.insert(output.collect::<Vec<_>>().await);
2458        });
2459        assert_eq!(instances, 8);
2460
2461        // The trigger may fire before the result has a value, in which case nothing is observed.
2462        assert_eq!(observed, [vec![], vec![true]].into_iter().collect());
2463    }
2464}