Skip to main content

hydro_lang/live_collections/
optional.rs

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