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    /// # // ticks are lazy by default, forces the tick to run
757    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
758    /// let optional = tick.optional_first_tick(q!(1));
759    /// optional.map(q!(|v| v + 1)).all_ticks()
760    /// # }, |mut stream| async move {
761    /// // 2
762    /// # assert_eq!(stream.next().await.unwrap(), 2);
763    /// # }));
764    /// # }
765    /// ```
766    pub fn map<U, F>(
767        self,
768        f: impl IntoQuotedMut<'a, F, OperatorContext<L, B::UnderlyingBound>>,
769    ) -> Optional<U, L, B>
770    where
771        F: Fn(T) -> U + 'a,
772    {
773        let f = f
774            .splice_fn1_ctx(&OperatorContext::<L, B::UnderlyingBound>::new(
775                &self.location,
776            ))
777            .into();
778        Optional::new(
779            self.location.clone(),
780            HydroNode::Map {
781                f,
782                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
783                metadata: self
784                    .location
785                    .new_node_metadata(Optional::<U, L, B>::collection_kind()),
786            },
787        )
788    }
789
790    /// Transforms the optional value by applying a function `f` to it and then flattening
791    /// the result into a stream, preserving the order of elements.
792    ///
793    /// If the optional is empty, the output stream is also empty. If the optional contains
794    /// a value, `f` is applied to produce an iterator, and all items from that iterator
795    /// are emitted in the output stream in deterministic order.
796    ///
797    /// The implementation of [`Iterator`] for the output type `I` must produce items in a
798    /// **deterministic** order. For example, `I` could be a `Vec`, but not a `HashSet`.
799    /// If the order is not deterministic, use [`Optional::flat_map_unordered`] instead.
800    ///
801    /// # Example
802    /// ```rust
803    /// # #[cfg(feature = "deploy")] {
804    /// # use hydro_lang::prelude::*;
805    /// # use futures::StreamExt;
806    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
807    /// let tick = process.tick();
808    /// # // ticks are lazy by default, forces the tick to run
809    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
810    /// let optional = tick.optional_first_tick(q!(vec![1, 2, 3]));
811    /// optional.flat_map_ordered(q!(|v| v)).all_ticks()
812    /// # }, |mut stream| async move {
813    /// // 1, 2, 3
814    /// # for w in vec![1, 2, 3] {
815    /// #     assert_eq!(stream.next().await.unwrap(), w);
816    /// # }
817    /// # }));
818    /// # }
819    /// ```
820    pub fn flat_map_ordered<U, I, F, C, Idemp, const WAS_MUT: bool>(
821        self,
822        f: impl IntoQuotedMut<
823            'a,
824            F,
825            OperatorContext<L, Bounded>,
826            StreamMapFuncAlgebra<T, Bounded, C, Idemp, L::SimHookScope>,
827        >,
828    ) -> Stream<U, L, Bounded, TotalOrder, ExactlyOnce>
829    where
830        B: IsBounded,
831        I: IntoIterator<Item = U>,
832        F: FnMut(T) -> I + 'a,
833        C: ValidMutCommutativityFor<F, T, I, TotalOrder, WAS_MUT>,
834        Idemp: ValidMutIdempotenceFor<F, T, I, ExactlyOnce, WAS_MUT>,
835    {
836        self.into_stream().flat_map_ordered(f)
837    }
838
839    /// Like [`Optional::flat_map_ordered`], but allows the implementation of [`Iterator`]
840    /// for the output type `I` to produce items in any order.
841    ///
842    /// If the optional is empty, the output stream is also empty. If the optional contains
843    /// a value, `f` is applied to produce an iterator, and all items from that iterator
844    /// are emitted in the output stream in non-deterministic order.
845    ///
846    /// # Example
847    /// ```rust
848    /// # #[cfg(feature = "deploy")] {
849    /// # use hydro_lang::{prelude::*, live_collections::stream::{NoOrder, ExactlyOnce}};
850    /// # use futures::StreamExt;
851    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test::<_, _, _, NoOrder, ExactlyOnce>(|process| {
852    /// let tick = process.tick();
853    /// # // ticks are lazy by default, forces the tick to run
854    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
855    /// let optional = tick.optional_first_tick(q!(
856    ///     std::collections::HashSet::<i32>::from_iter(vec![1, 2, 3])
857    /// ));
858    /// optional.flat_map_unordered(q!(|v| v)).all_ticks()
859    /// # }, |mut stream| async move {
860    /// // 1, 2, 3, but in no particular order
861    /// # let mut results = Vec::new();
862    /// # for _ in 0..3 {
863    /// #     results.push(stream.next().await.unwrap());
864    /// # }
865    /// # results.sort();
866    /// # assert_eq!(results, vec![1, 2, 3]);
867    /// # }));
868    /// # }
869    /// ```
870    pub fn flat_map_unordered<U, I, F, C, Idemp, const WAS_MUT: bool>(
871        self,
872        f: impl IntoQuotedMut<
873            'a,
874            F,
875            OperatorContext<L, Bounded>,
876            StreamMapFuncAlgebra<T, Bounded, C, Idemp, L::SimHookScope>,
877        >,
878    ) -> Stream<U, L, Bounded, NoOrder, ExactlyOnce>
879    where
880        B: IsBounded,
881        I: IntoIterator<Item = U>,
882        F: FnMut(T) -> I + 'a,
883        C: ValidMutCommutativityFor<F, T, I, TotalOrder, WAS_MUT>,
884        Idemp: ValidMutIdempotenceFor<F, T, I, ExactlyOnce, WAS_MUT>,
885    {
886        self.into_stream().flat_map_unordered(f)
887    }
888
889    /// Flattens the optional value into a stream, preserving the order of elements.
890    ///
891    /// If the optional is empty, the output stream is also empty. If the optional contains
892    /// a value that implements [`IntoIterator`], all items from that iterator are emitted
893    /// in the output stream in deterministic order.
894    ///
895    /// The implementation of [`Iterator`] for the element type `T` must produce items in a
896    /// **deterministic** order. For example, `T` could be a `Vec`, but not a `HashSet`.
897    /// If the order is not deterministic, use [`Optional::flatten_unordered`] instead.
898    ///
899    /// # Example
900    /// ```rust
901    /// # #[cfg(feature = "deploy")] {
902    /// # use hydro_lang::prelude::*;
903    /// # use futures::StreamExt;
904    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
905    /// let tick = process.tick();
906    /// # // ticks are lazy by default, forces the tick to run
907    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
908    /// let optional = tick.optional_first_tick(q!(vec![1, 2, 3]));
909    /// optional.flatten_ordered().all_ticks()
910    /// # }, |mut stream| async move {
911    /// // 1, 2, 3
912    /// # for w in vec![1, 2, 3] {
913    /// #     assert_eq!(stream.next().await.unwrap(), w);
914    /// # }
915    /// # }));
916    /// # }
917    /// ```
918    pub fn flatten_ordered<U>(self) -> Stream<U, L, Bounded, TotalOrder, ExactlyOnce>
919    where
920        B: IsBounded,
921        T: IntoIterator<Item = U>,
922    {
923        self.flat_map_ordered(q!(|v| v))
924    }
925
926    /// Like [`Optional::flatten_ordered`], but allows the implementation of [`Iterator`]
927    /// for the element type `T` to produce items in any order.
928    ///
929    /// If the optional is empty, the output stream is also empty. If the optional contains
930    /// a value that implements [`IntoIterator`], all items from that iterator are emitted
931    /// in the output stream in non-deterministic order.
932    ///
933    /// # Example
934    /// ```rust
935    /// # #[cfg(feature = "deploy")] {
936    /// # use hydro_lang::{prelude::*, live_collections::stream::{NoOrder, ExactlyOnce}};
937    /// # use futures::StreamExt;
938    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test::<_, _, _, NoOrder, ExactlyOnce>(|process| {
939    /// let tick = process.tick();
940    /// # // ticks are lazy by default, forces the tick to run
941    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
942    /// let optional = tick.optional_first_tick(q!(
943    ///     std::collections::HashSet::<i32>::from_iter(vec![1, 2, 3])
944    /// ));
945    /// optional.flatten_unordered().all_ticks()
946    /// # }, |mut stream| async move {
947    /// // 1, 2, 3, but in no particular order
948    /// # let mut results = Vec::new();
949    /// # for _ in 0..3 {
950    /// #     results.push(stream.next().await.unwrap());
951    /// # }
952    /// # results.sort();
953    /// # assert_eq!(results, vec![1, 2, 3]);
954    /// # }));
955    /// # }
956    /// ```
957    pub fn flatten_unordered<U>(self) -> Stream<U, L, Bounded, NoOrder, ExactlyOnce>
958    where
959        B: IsBounded,
960        T: IntoIterator<Item = U>,
961    {
962        self.flat_map_unordered(q!(|v| v))
963    }
964
965    /// Creates an optional containing only the value if it satisfies a predicate `f`.
966    ///
967    /// If the optional is empty, the output optional is also empty. If the optional contains
968    /// a value and the predicate returns `true`, the output optional contains the same value.
969    /// If the predicate returns `false`, the output optional is empty.
970    ///
971    /// The closure `f` receives a reference `&T` rather than an owned value `T` because filtering does
972    /// not modify or take ownership of the value. If you need to modify the value while filtering
973    /// use [`Optional::filter_map`] instead.
974    ///
975    /// # Example
976    /// ```rust
977    /// # #[cfg(feature = "deploy")] {
978    /// # use hydro_lang::prelude::*;
979    /// # use futures::StreamExt;
980    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
981    /// let tick = process.tick();
982    /// # // ticks are lazy by default, forces the tick to run
983    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
984    /// let optional = tick.optional_first_tick(q!(5));
985    /// optional.filter(q!(|&x| x > 3)).all_ticks()
986    /// # }, |mut stream| async move {
987    /// // 5
988    /// # assert_eq!(stream.next().await.unwrap(), 5);
989    /// # }));
990    /// # }
991    /// ```
992    pub fn filter<F>(
993        self,
994        f: impl IntoQuotedMut<'a, F, OperatorContext<L, B::UnderlyingBound>>,
995    ) -> Optional<T, L, B::UnderlyingBound>
996    where
997        F: Fn(&T) -> bool + 'a,
998    {
999        let f = f
1000            .splice_fn1_borrow_ctx(&OperatorContext::<L, B::UnderlyingBound>::new(
1001                &self.location,
1002            ))
1003            .into();
1004        Optional::new(
1005            self.location.clone(),
1006            HydroNode::Filter {
1007                f,
1008                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1009                metadata: self
1010                    .location
1011                    .new_node_metadata(Optional::<T, L, B::UnderlyingBound>::collection_kind()),
1012            },
1013        )
1014    }
1015
1016    /// An operator that both filters and maps. It yields only the value if the supplied
1017    /// closure `f` returns `Some(value)`.
1018    ///
1019    /// If the optional is empty, the output optional is also empty. If the optional contains
1020    /// a value and the closure returns `Some(new_value)`, the output optional contains `new_value`.
1021    /// If the closure returns `None`, the output optional is empty.
1022    ///
1023    /// # Example
1024    /// ```rust
1025    /// # #[cfg(feature = "deploy")] {
1026    /// # use hydro_lang::prelude::*;
1027    /// # use futures::StreamExt;
1028    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1029    /// let tick = process.tick();
1030    /// # // ticks are lazy by default, forces the tick to run
1031    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1032    /// let optional = tick.optional_first_tick(q!("42"));
1033    /// optional
1034    ///     .filter_map(q!(|s| s.parse::<i32>().ok()))
1035    ///     .all_ticks()
1036    /// # }, |mut stream| async move {
1037    /// // 42
1038    /// # assert_eq!(stream.next().await.unwrap(), 42);
1039    /// # }));
1040    /// # }
1041    /// ```
1042    pub fn filter_map<U, F>(
1043        self,
1044        f: impl IntoQuotedMut<'a, F, OperatorContext<L, B::UnderlyingBound>>,
1045    ) -> Optional<U, L, B::UnderlyingBound>
1046    where
1047        F: Fn(T) -> Option<U> + 'a,
1048    {
1049        let f = f
1050            .splice_fn1_ctx(&OperatorContext::<L, B::UnderlyingBound>::new(
1051                &self.location,
1052            ))
1053            .into();
1054        Optional::new(
1055            self.location.clone(),
1056            HydroNode::FilterMap {
1057                f,
1058                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1059                metadata: self
1060                    .location
1061                    .new_node_metadata(Optional::<U, L, B::UnderlyingBound>::collection_kind()),
1062            },
1063        )
1064    }
1065
1066    /// Combines this singleton with another [`Singleton`] or [`Optional`] by tupling their values.
1067    ///
1068    /// If the other value is a [`Optional`], the output will be non-null only if the argument is
1069    /// non-null. This is useful for combining several pieces of state together.
1070    ///
1071    /// # Example
1072    /// ```rust
1073    /// # #[cfg(feature = "deploy")] {
1074    /// # use hydro_lang::prelude::*;
1075    /// # use futures::StreamExt;
1076    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1077    /// let tick = process.tick();
1078    /// let numbers = process
1079    ///   .source_iter(q!(vec![123, 456, 789]))
1080    ///   .batch(&tick, nondet!(/** test */));
1081    /// let min = numbers.clone().min(); // Optional
1082    /// let max = numbers.max(); // Optional
1083    /// min.zip(max).all_ticks()
1084    /// # }, |mut stream| async move {
1085    /// // [(123, 789)]
1086    /// # for w in vec![(123, 789)] {
1087    /// #     assert_eq!(stream.next().await.unwrap(), w);
1088    /// # }
1089    /// # }));
1090    /// # }
1091    /// ```
1092    pub fn zip<O>(self, other: impl Into<Optional<O, L, B>>) -> Optional<(T, O), L, B>
1093    where
1094        B: IsBounded,
1095    {
1096        let other: Optional<O, L, B> = other.into();
1097        check_matching_location(&self.location, &other.location);
1098
1099        let location = self.location.clone();
1100        let me: Optional<T, L, Bounded> = Optional::new(
1101            location.clone(),
1102            self.ir_node.replace(HydroNode::Placeholder),
1103        );
1104        let other: Optional<O, L, Bounded> = Optional::new(
1105            other.location.clone(),
1106            other.ir_node.replace(HydroNode::Placeholder),
1107        );
1108        let out = zip_bounded(me, other);
1109        Optional::new(location, out.ir_node.replace(HydroNode::Placeholder))
1110    }
1111
1112    /// Passes through `self` when it has a value, otherwise passes through `other`.
1113    ///
1114    /// Like [`Option::or`], this is helpful for defining a fallback for an [`Optional`], when the
1115    /// fallback itself is an [`Optional`]. If the fallback is a [`Singleton`], you can use
1116    /// [`Optional::unwrap_or`] to ensure that the output is always non-null.
1117    ///
1118    /// If the inputs are [`Unbounded`], the output will be asynchronously updated as the contents
1119    /// of the inputs change (including to/from null states).
1120    ///
1121    /// # Example
1122    /// ```rust
1123    /// # #[cfg(feature = "deploy")] {
1124    /// # use hydro_lang::prelude::*;
1125    /// # use futures::StreamExt;
1126    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1127    /// let tick = process.tick();
1128    /// // ticks are lazy by default, forces the second tick to run
1129    /// tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1130    ///
1131    /// let some_first_tick = tick.optional_first_tick(q!(123));
1132    /// let some_second_tick = tick.optional_first_tick(q!(456)).defer_tick();
1133    /// some_first_tick.or(some_second_tick).all_ticks()
1134    /// # }, |mut stream| async move {
1135    /// // [123 /* first tick */, 456 /* second tick */]
1136    /// # for w in vec![123, 456] {
1137    /// #     assert_eq!(stream.next().await.unwrap(), w);
1138    /// # }
1139    /// # }));
1140    /// # }
1141    /// ```
1142    pub fn or(self, other: Optional<T, L, B::UnderlyingBound>) -> Optional<T, L, B::UnderlyingBound>
1143    where
1144        T: OrAt<'a, L>,
1145    {
1146        let me = self.ignore_init_none();
1147        check_matching_location(&me.location, &other.location);
1148
1149        if <B::UnderlyingBound as Boundedness>::BOUNDED {
1150            Optional::new(
1151                me.location.clone(),
1152                HydroNode::ChainFirst {
1153                    first: Box::new(me.ir_node.replace(HydroNode::Placeholder)),
1154                    second: Box::new(other.ir_node.replace(HydroNode::Placeholder)),
1155                    metadata: me
1156                        .location
1157                        .new_node_metadata(Optional::<T, L, B::UnderlyingBound>::collection_kind()),
1158                },
1159            )
1160        } else {
1161            let location = me.location.clone();
1162            let me: Optional<T, L, Unbounded> =
1163                Optional::new(location.clone(), me.ir_node.replace(HydroNode::Placeholder));
1164            let other: Optional<T, L, Unbounded> = Optional::new(
1165                other.location.clone(),
1166                other.ir_node.replace(HydroNode::Placeholder),
1167            );
1168            let out = T::or_unbounded(me, other);
1169            Optional::new(location, out.ir_node.replace(HydroNode::Placeholder))
1170        }
1171    }
1172
1173    /// [`Optional::or`] for a `T: Clone`, dispatching on the location at build time instead of
1174    /// through [`OrAt`]. Used by internal combinators whose element type is always `Clone`
1175    /// (e.g. `()`), so that they do not need an [`OrAt`] bound for a generic location.
1176    pub(crate) fn or_cloned(
1177        self,
1178        other: Optional<T, L, B::UnderlyingBound>,
1179    ) -> Optional<T, L, B::UnderlyingBound>
1180    where
1181        T: Clone + 'a,
1182    {
1183        let me = self.ignore_init_none();
1184        check_matching_location(&me.location, &other.location);
1185
1186        if <B::UnderlyingBound as Boundedness>::BOUNDED || !L::is_top_level() {
1187            Optional::new(
1188                me.location.clone(),
1189                HydroNode::ChainFirst {
1190                    first: Box::new(me.ir_node.replace(HydroNode::Placeholder)),
1191                    second: Box::new(other.ir_node.replace(HydroNode::Placeholder)),
1192                    metadata: me
1193                        .location
1194                        .new_node_metadata(Optional::<T, L, B::UnderlyingBound>::collection_kind()),
1195                },
1196            )
1197        } else {
1198            let location = me.location.clone();
1199            let me: Optional<T, L, Unbounded> =
1200                Optional::new(location.clone(), me.ir_node.replace(HydroNode::Placeholder));
1201            let other: Optional<T, L, Unbounded> = Optional::new(
1202                other.location.clone(),
1203                other.ir_node.replace(HydroNode::Placeholder),
1204            );
1205            let out = if location.id().is_root() {
1206                let out = or_at_root(me, other);
1207                Optional::new(
1208                    location.clone(),
1209                    out.ir_node.replace(HydroNode::Placeholder),
1210                )
1211            } else {
1212                // An atomic region is fused into its tick's loop: snapshot both sides into
1213                // that tick.
1214                let tick = location.try_tick().unwrap();
1215                let out = or_inside_tick(
1216                    me.snapshot(&tick, nondet!(/** eventually stabilizes */)),
1217                    other.snapshot(&tick, nondet!(/** eventually stabilizes */)),
1218                )
1219                .latest();
1220                Optional::<T, L, Unbounded>::new(
1221                    location.clone(),
1222                    out.ir_node.replace(HydroNode::Placeholder),
1223                )
1224            };
1225            Optional::new(location, out.ir_node.replace(HydroNode::Placeholder))
1226        }
1227    }
1228
1229    /// [`Optional::into_singleton`] for a `T: Clone`, via [`Optional::or_cloned`].
1230    pub(crate) fn into_singleton_cloned(self) -> Singleton<Option<T>, L, B::UnderlyingBound>
1231    where
1232        T: Clone + 'a,
1233    {
1234        if self.location.id().is_root() && !<B::UnderlyingBound as Boundedness>::BOUNDED {
1235            // At the root, the singleton's versions are exactly the optional's updates (as
1236            // `Option<T>`, with a tombstone becoming `None`), starting from `None`: hold the
1237            // latest update.
1238            let location = self.location.clone();
1239            let ir_node = self.ir_node.replace(HydroNode::Placeholder);
1240            let updates: Stream<Option<T>, L::DropConsistency, Unbounded, TotalOrder, ExactlyOnce> =
1241                if <B as OptionalBound>::bound_kind() == OptionalBoundKind::Unbounded {
1242                    let me: Optional<T, L, Unbounded> = Optional::new(location.clone(), ir_node);
1243                    me.into_update_stream(nondet!(
1244                        /// The singleton holds the latest update, so stuttering re-sets the same
1245                        /// value and skipping only skips intermediate versions.
1246                    ))
1247                } else {
1248                    let me: Optional<T, L, InitNone> = Optional::new(location.clone(), ir_node);
1249                    me.into_update_stream(nondet!(
1250                        /// The singleton holds the latest update, so stuttering re-sets the same
1251                        /// value and skipping only skips intermediate versions.
1252                    ))
1253                    .map(q!(|v| Some(v)))
1254                };
1255            let singleton: Singleton<Option<T>, _, Unbounded> =
1256                updates.fold(q!(|| None), q!(|current, update| *current = update));
1257            return Singleton::new(location, singleton.ir_node.replace(HydroNode::Placeholder));
1258        }
1259
1260        let none: syn::Expr = parse_quote!(::std::option::Option::None);
1261        let none_singleton: Singleton<Option<T>, L, B::UnderlyingBound> = Singleton::new(
1262            self.location.clone(),
1263            HydroNode::SingletonSource {
1264                value: none.into(),
1265                first_tick_only: false,
1266                metadata: self.location.new_node_metadata(Singleton::<
1267                    Option<T>,
1268                    L,
1269                    B::UnderlyingBound,
1270                >::collection_kind()),
1271            },
1272        );
1273        let res_option = self.map(q!(|v| Some(v))).or_cloned(none_singleton.into());
1274        Singleton::new(
1275            res_option.location.clone(),
1276            HydroNode::Cast {
1277                inner: Box::new(res_option.ir_node.replace(HydroNode::Placeholder)),
1278                metadata: res_option.location.new_node_metadata(Singleton::<
1279                    Option<T>,
1280                    L,
1281                    B::UnderlyingBound,
1282                >::collection_kind(
1283                )),
1284            },
1285        )
1286    }
1287
1288    /// Gets the contents of `self` when it has a value, otherwise passes through `other`.
1289    ///
1290    /// Like [`Option::unwrap_or`], this is helpful for defining a fallback for an [`Optional`].
1291    /// If the fallback is not always defined (an [`Optional`]), you can use [`Optional::or`].
1292    ///
1293    /// If the inputs are [`Unbounded`], the output will be asynchronously updated as the contents
1294    /// of the inputs change (including to/from null states).
1295    ///
1296    /// # Example
1297    /// ```rust
1298    /// # #[cfg(feature = "deploy")] {
1299    /// # use hydro_lang::prelude::*;
1300    /// # use futures::StreamExt;
1301    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1302    /// let tick = process.tick();
1303    /// // ticks are lazy by default, forces the later ticks to run
1304    /// tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1305    ///
1306    /// let some_first_tick = tick.optional_first_tick(q!(123));
1307    /// some_first_tick
1308    ///     .unwrap_or(tick.singleton(q!(456)))
1309    ///     .all_ticks()
1310    /// # }, |mut stream| async move {
1311    /// // [123 /* first tick */, 456 /* second tick */, 456 /* third tick */, 456, ...]
1312    /// # for w in vec![123, 456, 456, 456] {
1313    /// #     assert_eq!(stream.next().await.unwrap(), w);
1314    /// # }
1315    /// # }));
1316    /// # }
1317    /// ```
1318    pub fn unwrap_or(
1319        self,
1320        other: Singleton<T, L, B::UnderlyingBound>,
1321    ) -> Singleton<T, L, B::UnderlyingBound>
1322    where
1323        T: OrAt<'a, L>,
1324    {
1325        let res_option = self.or(other.into());
1326        Singleton::new(
1327            res_option.location.clone(),
1328            HydroNode::Cast {
1329                inner: Box::new(res_option.ir_node.replace(HydroNode::Placeholder)),
1330                metadata: res_option.location.new_node_metadata(Singleton::<
1331                    T,
1332                    L,
1333                    B::UnderlyingBound,
1334                >::collection_kind(
1335                )),
1336            },
1337        )
1338    }
1339
1340    /// Gets the contents of `self` when it has a value, otherwise returns the default value of `T`.
1341    ///
1342    /// Like [`Option::unwrap_or_default`], this is helpful for defining a fallback for an
1343    /// [`Optional`] when the default value of the type is a suitable fallback.
1344    ///
1345    /// # Example
1346    /// ```rust
1347    /// # #[cfg(feature = "deploy")] {
1348    /// # use hydro_lang::prelude::*;
1349    /// # use futures::StreamExt;
1350    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1351    /// let tick = process.tick();
1352    /// // ticks are lazy by default, forces the later ticks to run
1353    /// tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1354    ///
1355    /// let some_first_tick = tick.optional_first_tick(q!(123i32));
1356    /// some_first_tick.unwrap_or_default().all_ticks()
1357    /// # }, |mut stream| async move {
1358    /// // [123 /* first tick */, 0 /* second tick */, 0 /* third tick */, 0, ...]
1359    /// # for w in vec![123, 0, 0, 0] {
1360    /// #     assert_eq!(stream.next().await.unwrap(), w);
1361    /// # }
1362    /// # }));
1363    /// # }
1364    /// ```
1365    pub fn unwrap_or_default(self) -> Singleton<T, L, B::UnderlyingBound>
1366    where
1367        T: Default + Clone + 'a,
1368    {
1369        self.into_singleton().map(q!(|v| v.unwrap_or_default()))
1370    }
1371
1372    /// Converts this optional into a [`Singleton`] with a Rust [`Option`] as its contents.
1373    ///
1374    /// Useful for writing custom Rust code that needs to interact with both the null and non-null
1375    /// states of the [`Optional`]. When possible, you should use the native APIs on [`Optional`]
1376    /// so that Hydro can skip any computation on null values.
1377    ///
1378    /// # Example
1379    /// ```rust
1380    /// # #[cfg(feature = "deploy")] {
1381    /// # use hydro_lang::prelude::*;
1382    /// # use futures::StreamExt;
1383    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1384    /// let tick = process.tick();
1385    /// // ticks are lazy by default, forces the later ticks to run
1386    /// tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1387    ///
1388    /// let some_first_tick = tick.optional_first_tick(q!(123));
1389    /// some_first_tick.into_singleton().all_ticks()
1390    /// # }, |mut stream| async move {
1391    /// // [Some(123) /* first tick */, None /* second tick */, None /* third tick */, None, ...]
1392    /// # for w in vec![Some(123), None, None, None] {
1393    /// #     assert_eq!(stream.next().await.unwrap(), w);
1394    /// # }
1395    /// # }));
1396    /// # }
1397    /// ```
1398    pub fn into_singleton(self) -> Singleton<Option<T>, L, B::UnderlyingBound>
1399    where
1400        T: Clone + 'a,
1401    {
1402        self.into_singleton_cloned()
1403    }
1404
1405    /// Returns a [`Singleton`] containing `true` if this optional has a value, `false` otherwise.
1406    ///
1407    /// # Example
1408    /// ```rust
1409    /// # #[cfg(feature = "deploy")] {
1410    /// # use hydro_lang::prelude::*;
1411    /// # use futures::StreamExt;
1412    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1413    /// let tick = process.tick();
1414    /// // ticks are lazy by default, forces the second tick to run
1415    /// tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1416    ///
1417    /// let some_first_tick = tick.optional_first_tick(q!(42));
1418    /// some_first_tick.is_some().all_ticks()
1419    /// # }, |mut stream| async move {
1420    /// // [true /* first tick */, false /* second tick */, ...]
1421    /// # for w in vec![true, false] {
1422    /// #     assert_eq!(stream.next().await.unwrap(), w);
1423    /// # }
1424    /// # }));
1425    /// # }
1426    /// ```
1427    #[expect(clippy::wrong_self_convention, reason = "Stream naming")]
1428    pub fn is_some(self) -> Singleton<bool, L, B::UnderlyingBound> {
1429        self.map(q!(|_| ()))
1430            .into_singleton_cloned()
1431            .map(q!(|o| o.is_some()))
1432    }
1433
1434    /// Returns a [`Singleton`] containing `true` if this optional is null, `false` otherwise.
1435    ///
1436    /// # Example
1437    /// ```rust
1438    /// # #[cfg(feature = "deploy")] {
1439    /// # use hydro_lang::prelude::*;
1440    /// # use futures::StreamExt;
1441    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1442    /// let tick = process.tick();
1443    /// // ticks are lazy by default, forces the second tick to run
1444    /// tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1445    ///
1446    /// let some_first_tick = tick.optional_first_tick(q!(42));
1447    /// some_first_tick.is_none().all_ticks()
1448    /// # }, |mut stream| async move {
1449    /// // [false /* first tick */, true /* second tick */, ...]
1450    /// # for w in vec![false, true] {
1451    /// #     assert_eq!(stream.next().await.unwrap(), w);
1452    /// # }
1453    /// # }));
1454    /// # }
1455    /// ```
1456    #[expect(clippy::wrong_self_convention, reason = "Stream naming")]
1457    pub fn is_none(self) -> Singleton<bool, L, B::UnderlyingBound> {
1458        self.map(q!(|_| ()))
1459            .into_singleton_cloned()
1460            .map(q!(|o| o.is_none()))
1461    }
1462
1463    /// Returns a [`Singleton`] containing `true` if both optionals are non-null and their
1464    /// values are equal, `false` otherwise (including when either is null).
1465    ///
1466    /// # Example
1467    /// ```rust
1468    /// # #[cfg(feature = "deploy")] {
1469    /// # use hydro_lang::prelude::*;
1470    /// # use futures::StreamExt;
1471    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1472    /// let tick = process.tick();
1473    /// // ticks are lazy by default, forces the second tick to run
1474    /// tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1475    ///
1476    /// let a = tick.optional_first_tick(q!(5)); // Some(5), None
1477    /// let b = tick.optional_first_tick(q!(5)); // Some(5), None
1478    /// a.is_some_and_equals(b).all_ticks()
1479    /// # }, |mut stream| async move {
1480    /// // [true, false]
1481    /// # for w in vec![true, false] {
1482    /// #     assert_eq!(stream.next().await.unwrap(), w);
1483    /// # }
1484    /// # }));
1485    /// # }
1486    /// ```
1487    #[expect(clippy::wrong_self_convention, reason = "Stream naming")]
1488    pub fn is_some_and_equals(self, other: Optional<T, L, B>) -> Singleton<bool, L, B>
1489    where
1490        T: PartialEq + Clone + 'a,
1491        B: IsBounded,
1492    {
1493        self.into_singleton()
1494            .zip(other.into_singleton())
1495            .map(q!(|(a, b)| a.is_some() && a == b))
1496    }
1497
1498    /// An operator which allows you to "name" a `HydroNode`.
1499    /// This is only used for testing, to correlate certain `HydroNode`s with IDs.
1500    pub fn ir_node_named(self, name: &str) -> Optional<T, L, B> {
1501        {
1502            let mut node = self.ir_node.borrow_mut();
1503            let metadata = node.metadata_mut();
1504            metadata.tag = Some(name.to_owned());
1505        }
1506        self
1507    }
1508
1509    /// Drops the [`InitNone`] guarantee of the [`Optional`], erasing it to its
1510    /// [`OptionalBound::UnderlyingBound`] (i.e. [`Unbounded`] for [`InitNone`]).
1511    pub fn ignore_init_none(self) -> Optional<T, L, B::UnderlyingBound> {
1512        if <B as OptionalBound>::bound_kind() == <B::UnderlyingBound as OptionalBound>::bound_kind()
1513        {
1514            Optional::new(
1515                self.location.clone(),
1516                self.ir_node.replace(HydroNode::Placeholder),
1517            )
1518        } else {
1519            Optional::new(
1520                self.location.clone(),
1521                HydroNode::Cast {
1522                    inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1523                    metadata: self
1524                        .location
1525                        .new_node_metadata(Optional::<T, L, B::UnderlyingBound>::collection_kind()),
1526                },
1527            )
1528        }
1529    }
1530
1531    /// Strengthens the boundedness guarantee to `Bounded`, given that `B: IsBounded`, which
1532    /// implies that `B == Bounded`.
1533    pub fn make_bounded(self) -> Optional<T, L, Bounded>
1534    where
1535        B: IsBounded,
1536    {
1537        Optional::new(
1538            self.location.clone(),
1539            self.ir_node.replace(HydroNode::Placeholder),
1540        )
1541    }
1542
1543    /// Clones this bounded optional into a tick, returning a optional that has the
1544    /// same value as the outer optional. Because the outer optional is bounded, this
1545    /// is deterministic because there is only a single immutable version.
1546    pub fn clone_into_tick(self, tick: &Tick<L>) -> Optional<T, Tick<L>, Bounded>
1547    where
1548        B: IsBounded,
1549        T: Clone,
1550    {
1551        // TODO(shadaj): avoid printing simulator logs for this snapshot
1552        let inner = self.snapshot(
1553            tick,
1554            nondet!(/** bounded top-level optional so deterministic */),
1555        );
1556        Optional::new(tick.clone(), inner.ir_node.replace(HydroNode::Placeholder))
1557    }
1558
1559    /// Converts this optional into a [`Stream`] containing a single element, the value, if it is
1560    /// non-null. Otherwise, the stream is empty.
1561    ///
1562    /// # Example
1563    /// ```rust
1564    /// # #[cfg(feature = "deploy")] {
1565    /// # use hydro_lang::prelude::*;
1566    /// # use futures::StreamExt;
1567    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1568    /// # let tick = process.tick();
1569    /// # // ticks are lazy by default, forces the second tick to run
1570    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1571    /// # let batch_first_tick = process
1572    /// #   .source_iter(q!(vec![]))
1573    /// #   .batch(&tick, nondet!(/** test */));
1574    /// # let batch_second_tick = process
1575    /// #   .source_iter(q!(vec![123, 456]))
1576    /// #   .batch(&tick, nondet!(/** test */))
1577    /// #   .defer_tick(); // appears on the second tick
1578    /// # let input_batch = batch_first_tick.chain(batch_second_tick);
1579    /// input_batch // first tick: [], second tick: [123, 456]
1580    ///     .clone()
1581    ///     .max()
1582    ///     .into_stream()
1583    ///     .chain(input_batch)
1584    ///     .all_ticks()
1585    /// # }, |mut stream| async move {
1586    /// // [456, 123, 456]
1587    /// # for w in vec![456, 123, 456] {
1588    /// #     assert_eq!(stream.next().await.unwrap(), w);
1589    /// # }
1590    /// # }));
1591    /// # }
1592    /// ```
1593    pub fn into_stream(self) -> Stream<T, L, Bounded, TotalOrder, ExactlyOnce>
1594    where
1595        B: IsBounded,
1596    {
1597        Stream::new(
1598            self.location.clone(),
1599            HydroNode::Cast {
1600                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1601                metadata: self.location.new_node_metadata(Stream::<
1602                    T,
1603                    Tick<L>,
1604                    Bounded,
1605                    TotalOrder,
1606                    ExactlyOnce,
1607                >::collection_kind()),
1608            },
1609        )
1610    }
1611
1612    /// Filters this optional, passing through the value if the boolean signal is `true`,
1613    /// otherwise the output is null.
1614    ///
1615    /// # Example
1616    /// ```rust
1617    /// # #[cfg(feature = "deploy")] {
1618    /// # use hydro_lang::prelude::*;
1619    /// # use futures::StreamExt;
1620    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1621    /// let tick = process.tick();
1622    /// // ticks are lazy by default, forces the second tick to run
1623    /// tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1624    ///
1625    /// let some_first_tick = tick.optional_first_tick(q!(()));
1626    /// let signal = some_first_tick.is_some(); // true on first tick, false on second
1627    /// let batch_first_tick = process
1628    ///   .source_iter(q!(vec![456]))
1629    ///   .batch(&tick, nondet!(/** test */));
1630    /// let batch_second_tick = process
1631    ///   .source_iter(q!(vec![789]))
1632    ///   .batch(&tick, nondet!(/** test */))
1633    ///   .defer_tick();
1634    /// batch_first_tick.chain(batch_second_tick).first()
1635    ///   .filter_if(signal)
1636    ///   .unwrap_or(tick.singleton(q!(0)))
1637    ///   .all_ticks()
1638    /// # }, |mut stream| async move {
1639    /// // [456, 0]
1640    /// # for w in vec![456, 0] {
1641    /// #     assert_eq!(stream.next().await.unwrap(), w);
1642    /// # }
1643    /// # }));
1644    /// # }
1645    /// ```
1646    pub fn filter_if(self, signal: Singleton<bool, L, B>) -> Optional<T, L, B>
1647    where
1648        B: IsBounded,
1649    {
1650        self.zip(signal.filter(q!(|b| *b))).map(q!(|(d, _)| d))
1651    }
1652
1653    /// Filters this optional, passing through the optional value if it is non-null **and** the
1654    /// argument (a [`Bounded`] [`Optional`]) is non-null, otherwise the output is null.
1655    ///
1656    /// Useful for conditionally processing, such as only emitting an optional's value outside
1657    /// a tick if some other condition is satisfied.
1658    ///
1659    /// # Example
1660    /// ```rust
1661    /// # #[cfg(feature = "deploy")] {
1662    /// # use hydro_lang::prelude::*;
1663    /// # use futures::StreamExt;
1664    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1665    /// let tick = process.tick();
1666    /// // ticks are lazy by default, forces the second tick to run
1667    /// tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1668    ///
1669    /// let batch_first_tick = process
1670    ///   .source_iter(q!(vec![]))
1671    ///   .batch(&tick, nondet!(/** test */));
1672    /// let batch_second_tick = process
1673    ///   .source_iter(q!(vec![456]))
1674    ///   .batch(&tick, nondet!(/** test */))
1675    ///   .defer_tick(); // appears on the second tick
1676    /// let some_on_first_tick = tick.optional_first_tick(q!(()));
1677    /// batch_first_tick.chain(batch_second_tick).first()
1678    ///   .filter_if_some(some_on_first_tick)
1679    ///   .unwrap_or(tick.singleton(q!(789)))
1680    ///   .all_ticks()
1681    /// # }, |mut stream| async move {
1682    /// // [789, 789]
1683    /// # for w in vec![789, 789] {
1684    /// #     assert_eq!(stream.next().await.unwrap(), w);
1685    /// # }
1686    /// # }));
1687    /// # }
1688    /// ```
1689    #[deprecated(note = "use `filter_if` with `Optional::is_some()` instead")]
1690    pub fn filter_if_some<U>(self, signal: Optional<U, L, B>) -> Optional<T, L, B>
1691    where
1692        B: IsBounded,
1693    {
1694        self.filter_if(signal.is_some())
1695    }
1696
1697    /// Filters this optional, passing through the optional value if it is non-null **and** the
1698    /// argument (a [`Bounded`] [`Optional`]) is _null_, otherwise the output is null.
1699    ///
1700    /// Useful for conditionally processing, such as only emitting an optional's value outside
1701    /// a tick if some other condition is satisfied.
1702    ///
1703    /// # Example
1704    /// ```rust
1705    /// # #[cfg(feature = "deploy")] {
1706    /// # use hydro_lang::prelude::*;
1707    /// # use futures::StreamExt;
1708    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1709    /// let tick = process.tick();
1710    /// // ticks are lazy by default, forces the second tick to run
1711    /// tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1712    ///
1713    /// let batch_first_tick = process
1714    ///   .source_iter(q!(vec![]))
1715    ///   .batch(&tick, nondet!(/** test */));
1716    /// let batch_second_tick = process
1717    ///   .source_iter(q!(vec![456]))
1718    ///   .batch(&tick, nondet!(/** test */))
1719    ///   .defer_tick(); // appears on the second tick
1720    /// let some_on_first_tick = tick.optional_first_tick(q!(()));
1721    /// batch_first_tick.chain(batch_second_tick).first()
1722    ///   .filter_if_none(some_on_first_tick)
1723    ///   .unwrap_or(tick.singleton(q!(789)))
1724    ///   .all_ticks()
1725    /// # }, |mut stream| async move {
1726    /// // [789, 789]
1727    /// # for w in vec![789, 456] {
1728    /// #     assert_eq!(stream.next().await.unwrap(), w);
1729    /// # }
1730    /// # }));
1731    /// # }
1732    /// ```
1733    #[deprecated(note = "use `filter_if` with `!Optional::is_some()` instead")]
1734    pub fn filter_if_none<U>(self, other: Optional<U, L, B>) -> Optional<T, L, B>
1735    where
1736        B: IsBounded,
1737    {
1738        self.filter_if(other.is_none())
1739    }
1740
1741    /// If `self` is null, emits a null optional, but if it non-null, emits `value`.
1742    ///
1743    /// Useful for gating the release of a [`Singleton`] on a condition of the [`Optional`]
1744    /// having a value, such as only releasing a piece of state if the node is the leader.
1745    ///
1746    /// # Example
1747    /// ```rust
1748    /// # #[cfg(feature = "deploy")] {
1749    /// # use hydro_lang::prelude::*;
1750    /// # use futures::StreamExt;
1751    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1752    /// let tick = process.tick();
1753    /// // ticks are lazy by default, forces the second tick to run
1754    /// tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1755    ///
1756    /// let some_on_first_tick = tick.optional_first_tick(q!(()));
1757    /// some_on_first_tick
1758    ///     .if_some_then(tick.singleton(q!(456)))
1759    ///     .unwrap_or(tick.singleton(q!(123)))
1760    /// # .all_ticks()
1761    /// # }, |mut stream| async move {
1762    /// // 456 (first tick) ~> 123 (second tick onwards)
1763    /// # for w in vec![456, 123, 123] {
1764    /// #     assert_eq!(stream.next().await.unwrap(), w);
1765    /// # }
1766    /// # }));
1767    /// # }
1768    /// ```
1769    #[deprecated(note = "use `filter_if` with `Optional::is_some()` instead")]
1770    pub fn if_some_then<U>(self, value: Singleton<U, L, B>) -> Optional<U, L, B>
1771    where
1772        B: IsBounded,
1773    {
1774        value.filter_if(self.is_some())
1775    }
1776}
1777
1778impl<'a, K, V, L, B: OptionalBound> Optional<(K, V), L, B>
1779where
1780    L: Location<'a>,
1781{
1782    /// Converts this optional into a [`KeyedSingleton`] containing a single entry with the
1783    /// key-value pair of this [`Optional`].
1784    ///
1785    /// If this [`Optional`] is [`Bounded`], the [`KeyedSingleton`] will be [`Bounded`] as well
1786    /// if it is [`Unbounded`], the [`KeyedSingleton`] will be [`Unbounded`], which means that
1787    /// the entry will be updated and appear / disappear according to the state of the
1788    /// [`Optional`].
1789    ///
1790    /// The `K: Clone + PartialEq` bounds are needed because when the optional is [`Unbounded`]
1791    /// at a top-level location, the compiled representation tracks the previously emitted key
1792    /// so the entry can be removed when the optional becomes null or moves to a different key.
1793    pub fn into_keyed_singleton(self) -> KeyedSingleton<K, V, L, B::UnderlyingBound>
1794    where
1795        K: Clone + PartialEq,
1796    {
1797        KeyedSingleton::new(
1798            self.location.clone(),
1799            HydroNode::Cast {
1800                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1801                metadata: self.location.new_node_metadata(KeyedSingleton::<
1802                    K,
1803                    V,
1804                    L,
1805                    B::UnderlyingBound,
1806                >::collection_kind()),
1807            },
1808        )
1809    }
1810}
1811
1812impl<'a, T, L, B: OptionalBound> Optional<T, Atomic<L>, B>
1813where
1814    L: Location<'a>,
1815{
1816    /// Returns an optional value corresponding to the latest snapshot of the optional
1817    /// being atomically processed. The snapshot at tick `t + 1` is guaranteed to include
1818    /// at least all relevant data that contributed to the snapshot at tick `t`. Furthermore,
1819    /// all snapshots of this optional into the atomic-associated tick will observe the
1820    /// same value each tick.
1821    ///
1822    /// # Non-Determinism
1823    /// Because this picks a snapshot of a optional whose value is continuously changing,
1824    /// the output optional has a non-deterministic value since the snapshot can be at an
1825    /// arbitrary point in time.
1826    pub fn snapshot_atomic<L2: Location<'a, DropConsistency = L::DropConsistency>>(
1827        self,
1828        tick: &Tick<L2>,
1829        _nondet: NonDet,
1830    ) -> Optional<T, Tick<L::DropConsistency>, Bounded> {
1831        assert_eq!(
1832            Location::id(tick.parent_location()),
1833            Location::id(self.location.tick.parent_location())
1834        );
1835        Optional::new(
1836            tick.drop_consistency(),
1837            HydroNode::Snapshot {
1838                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1839                metadata: tick
1840                    .new_node_metadata(Optional::<T, Tick<L>, Bounded>::collection_kind()),
1841            },
1842        )
1843    }
1844}
1845
1846impl<'a, T, L, B: OptionalBound> Optional<T, L, B>
1847where
1848    L: Location<'a>,
1849{
1850    /// Given a tick, returns a optional value corresponding to a snapshot of the optional
1851    /// as of that tick. The snapshot at tick `t + 1` is guaranteed to include at least all
1852    /// relevant data that contributed to the snapshot at tick `t`.
1853    ///
1854    /// # Non-Determinism
1855    /// Because this picks a snapshot of a optional whose value is continuously changing,
1856    /// the output optional has a non-deterministic value since the snapshot can be at an
1857    /// arbitrary point in time.
1858    pub fn snapshot<L2: Location<'a, DropConsistency = L::DropConsistency>>(
1859        self,
1860        tick: &Tick<L2>,
1861        _nondet: NonDet,
1862    ) -> Optional<T, Tick<L::DropConsistency>, Bounded> {
1863        assert_eq!(
1864            Location::id(tick.parent_location()),
1865            Location::id(&self.location)
1866        );
1867        Optional::new(
1868            tick.drop_consistency(),
1869            HydroNode::Snapshot {
1870                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1871                metadata: tick
1872                    .new_node_metadata(Optional::<T, Tick<L>, Bounded>::collection_kind()),
1873            },
1874        )
1875    }
1876
1877    /// Eagerly samples the optional as fast as possible, returning a stream of snapshots
1878    /// with order corresponding to increasing prefixes of data contributing to the optional.
1879    ///
1880    /// This requires the optional to be null-only-initially ([`IsInitNone`]): a general
1881    /// [`Unbounded`] optional can *become null again*, which a `Stream<T>` of samples cannot
1882    /// represent (dropping the null transitions would leave stale values observable). To
1883    /// sample an [`Unbounded`] optional, use [`Optional::into_singleton`] first to observe
1884    /// `Option<T>` snapshots (including `None`).
1885    ///
1886    /// # Non-Determinism
1887    /// At runtime, the optional will be arbitrarily sampled as fast as possible, but due
1888    /// to non-deterministic batching and arrival of inputs, the output stream is
1889    /// non-deterministic.
1890    pub fn sample_eager(
1891        self,
1892        nondet: NonDet,
1893    ) -> Stream<T, L::DropConsistency, Unbounded, TotalOrder, AtLeastOnce>
1894    where
1895        B: IsInitNone,
1896    {
1897        if self.location.id().is_root() {
1898            let me: Optional<T, L, InitNone> = Optional::new(
1899                self.location.clone(),
1900                self.ir_node.replace(HydroNode::Placeholder),
1901            );
1902            let updates = me.into_update_stream(nondet);
1903            // Sample the latest version in each batch of updates. Batching (explored by the
1904            // simulator) determines which versions are skipped.
1905            sliced! {
1906                let batch = use::batch(updates, nondet!(
1907                    /// which versions are sampled is captured by the caller's guard
1908                ));
1909                batch.last().into_stream()
1910            }
1911            .weaken_retries()
1912        } else {
1913            let tick = self.location.tick();
1914            self.snapshot(&tick, nondet).all_ticks().weaken_retries()
1915        }
1916    }
1917
1918    /// Given a time interval, returns a stream corresponding to snapshots of the optional
1919    /// value taken at various points in time. Because the input optional may be
1920    /// [`Unbounded`], there are no guarantees on what these snapshots are other than they
1921    /// represent the value of the optional given some prefix of the streams leading up to
1922    /// it.
1923    ///
1924    /// # Non-Determinism
1925    /// The output stream is non-deterministic in which elements are sampled, since this
1926    /// is controlled by a clock.
1927    #[cfg(feature = "tokio")]
1928    pub fn sample_every(
1929        self,
1930        interval: impl QuotedWithContext<'a, std::time::Duration, L> + Copy + 'a,
1931        nondet: NonDet,
1932    ) -> Stream<T, L::DropConsistency, Unbounded, TotalOrder, AtLeastOnce>
1933    where
1934        L: TopLevel<'a>,
1935    {
1936        let samples = self.location.source_interval(interval);
1937        let tick = self.location.tick();
1938
1939        self.snapshot(&tick, nondet)
1940            .filter_if(
1941                samples
1942                    .batch(
1943                        &tick,
1944                        nondet!(
1945                            /// sample timing is captured by the caller's guard
1946                            nondet
1947                        ),
1948                    )
1949                    .first()
1950                    .is_some(),
1951            )
1952            .all_ticks()
1953            .weaken_retries()
1954    }
1955}
1956
1957impl<'a, T, L> Optional<T, Tick<L>, Bounded>
1958where
1959    L: Location<'a>,
1960{
1961    /// Asynchronously yields the value of this singleton outside the tick as an unbounded stream,
1962    /// which will stream the value computed in _each_ tick as a separate stream element (skipping
1963    /// null values).
1964    ///
1965    /// Unlike [`Optional::latest`], the value computed in each tick is emitted separately,
1966    /// producing one element in the output for each (non-null) tick. This is useful for batched
1967    /// computations, where the results from each tick must be combined together.
1968    ///
1969    /// # Example
1970    /// ```rust
1971    /// # #[cfg(feature = "deploy")] {
1972    /// # use hydro_lang::prelude::*;
1973    /// # use futures::StreamExt;
1974    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1975    /// # let tick = process.tick();
1976    /// # // ticks are lazy by default, forces the second tick to run
1977    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1978    /// # let batch_first_tick = process
1979    /// #   .source_iter(q!(vec![]))
1980    /// #   .batch(&tick, nondet!(/** test */));
1981    /// # let batch_second_tick = process
1982    /// #   .source_iter(q!(vec![1, 2, 3]))
1983    /// #   .batch(&tick, nondet!(/** test */))
1984    /// #   .defer_tick(); // appears on the second tick
1985    /// # let input_batch = batch_first_tick.chain(batch_second_tick);
1986    /// input_batch // first tick: [], second tick: [1, 2, 3]
1987    ///     .max()
1988    ///     .all_ticks()
1989    /// # }, |mut stream| async move {
1990    /// // [3]
1991    /// # for w in vec![3] {
1992    /// #     assert_eq!(stream.next().await.unwrap(), w);
1993    /// # }
1994    /// # }));
1995    /// # }
1996    /// ```
1997    pub fn all_ticks(self) -> Stream<T, L, Unbounded, TotalOrder, ExactlyOnce> {
1998        self.into_stream().all_ticks()
1999    }
2000
2001    /// Synchronously yields the value of this optional outside the tick as an unbounded stream,
2002    /// which will stream the value computed in _each_ tick as a separate stream element.
2003    ///
2004    /// Unlike [`Optional::all_ticks`], this preserves synchronous execution, as the output stream
2005    /// is emitted in an [`Atomic`] context that will process elements synchronously with the input
2006    /// optional's [`Tick`] context.
2007    pub fn all_ticks_atomic(self) -> Stream<T, Atomic<L>, Unbounded, TotalOrder, ExactlyOnce> {
2008        self.into_stream().all_ticks_atomic()
2009    }
2010
2011    /// Asynchronously yields this optional outside the tick as an unbounded optional, which will
2012    /// be asynchronously updated with the latest value of the optional inside the tick, including
2013    /// whether the optional is null or not.
2014    ///
2015    /// This converts a bounded value _inside_ a tick into an asynchronous value outside the
2016    /// tick that tracks the inner value. This is useful for getting the value as of the
2017    /// "most recent" tick, but note that updates are propagated asynchronously outside the tick.
2018    ///
2019    /// # Example
2020    /// ```rust
2021    /// # #[cfg(feature = "deploy")] {
2022    /// # use hydro_lang::prelude::*;
2023    /// # use futures::StreamExt;
2024    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
2025    /// # let tick = process.tick();
2026    /// # // ticks are lazy by default, forces the second tick to run
2027    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
2028    /// # let batch_first_tick = process
2029    /// #   .source_iter(q!(vec![]))
2030    /// #   .batch(&tick, nondet!(/** test */));
2031    /// # let batch_second_tick = process
2032    /// #   .source_iter(q!(vec![1, 2, 3]))
2033    /// #   .batch(&tick, nondet!(/** test */))
2034    /// #   .defer_tick(); // appears on the second tick
2035    /// # let input_batch = batch_first_tick.chain(batch_second_tick);
2036    /// input_batch // first tick: [], second tick: [1, 2, 3]
2037    ///     .max()
2038    ///     .latest()
2039    /// # .into_singleton()
2040    /// # .sample_eager(nondet!(/** test */))
2041    /// # }, |mut stream| async move {
2042    /// // asynchronously changes from None ~> 3
2043    /// # for w in vec![None, Some(3)] {
2044    /// #     assert_eq!(stream.next().await.unwrap(), w);
2045    /// # }
2046    /// # }));
2047    /// # }
2048    /// ```
2049    pub fn latest(self) -> Optional<T, L, Unbounded> {
2050        Optional::new(
2051            self.location.parent_location().clone(),
2052            HydroNode::YieldConcat {
2053                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2054                metadata: self
2055                    .location
2056                    .parent_location()
2057                    .new_node_metadata(Optional::<T, L, Unbounded>::collection_kind()),
2058            },
2059        )
2060    }
2061
2062    /// Synchronously yields this optional outside the tick as an unbounded optional, which will
2063    /// be updated with the latest value of the optional inside the tick.
2064    ///
2065    /// Unlike [`Optional::latest`], this preserves synchronous execution, as the output optional
2066    /// is emitted in an [`Atomic`] context that will process elements synchronously with the input
2067    /// optional's [`Tick`] context.
2068    pub fn latest_atomic(self) -> Optional<T, Atomic<L>, Unbounded> {
2069        let out_location = Atomic {
2070            tick: self.location.clone(),
2071        };
2072
2073        Optional::new(
2074            out_location.clone(),
2075            HydroNode::YieldConcat {
2076                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2077                metadata: out_location
2078                    .new_node_metadata(Optional::<T, Atomic<L>, Unbounded>::collection_kind()),
2079            },
2080        )
2081    }
2082
2083    /// Shifts the state in `self` to the **next tick**, so that the returned optional at tick `T`
2084    /// always has the state of `self` at tick `T - 1`.
2085    ///
2086    /// At tick `0`, the output optional is null, since there is no previous tick.
2087    ///
2088    /// This operator enables stateful iterative processing with ticks, by sending data from one
2089    /// tick to the next. For example, you can use it to compare state across consecutive batches.
2090    ///
2091    /// # Example
2092    /// ```rust
2093    /// # #[cfg(feature = "deploy")] {
2094    /// # use hydro_lang::prelude::*;
2095    /// # use futures::StreamExt;
2096    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
2097    /// let tick = process.tick();
2098    /// // ticks are lazy by default, forces the second tick to run
2099    /// tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
2100    ///
2101    /// let batch_first_tick = process
2102    ///   .source_iter(q!(vec![1, 2]))
2103    ///   .batch(&tick, nondet!(/** test */));
2104    /// let batch_second_tick = process
2105    ///   .source_iter(q!(vec![3, 4]))
2106    ///   .batch(&tick, nondet!(/** test */))
2107    ///   .defer_tick(); // appears on the second tick
2108    /// let current_tick_sum = batch_first_tick.chain(batch_second_tick)
2109    ///   .reduce(q!(|state, v| *state += v));
2110    ///
2111    /// current_tick_sum.clone().into_singleton().zip(
2112    ///   current_tick_sum.defer_tick().into_singleton() // state from previous tick
2113    /// ).all_ticks()
2114    /// # }, |mut stream| async move {
2115    /// // [(Some(3), None) /* first tick */, (Some(7), Some(3)) /* second tick */]
2116    /// # for w in vec![(Some(3), None), (Some(7), Some(3))] {
2117    /// #     assert_eq!(stream.next().await.unwrap(), w);
2118    /// # }
2119    /// # }));
2120    /// # }
2121    /// ```
2122    pub fn defer_tick(self) -> Optional<T, Tick<L>, Bounded> {
2123        Optional::new(
2124            self.location.clone(),
2125            HydroNode::DeferTick {
2126                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2127                metadata: self.location.new_node_metadata(Self::collection_kind()),
2128            },
2129        )
2130    }
2131}
2132
2133#[cfg(test)]
2134mod tests {
2135    #[cfg(feature = "deploy")]
2136    use futures::StreamExt;
2137    #[cfg(feature = "deploy")]
2138    use hydro_deploy::Deployment;
2139    #[cfg(any(feature = "deploy", feature = "sim"))]
2140    use stageleft::q;
2141
2142    #[cfg(any(feature = "deploy", feature = "sim"))]
2143    use super::Optional;
2144    #[cfg(any(feature = "deploy", feature = "sim"))]
2145    use crate::compile::builder::FlowBuilder;
2146    #[cfg(any(feature = "deploy", feature = "sim"))]
2147    use crate::location::Location;
2148    #[cfg(feature = "deploy")]
2149    use crate::nondet::nondet;
2150
2151    #[cfg(feature = "deploy")]
2152    #[tokio::test]
2153    async fn optional_or_cardinality() {
2154        let mut deployment = Deployment::new();
2155
2156        let mut flow = FlowBuilder::new();
2157        let node = flow.process::<()>();
2158        let external = flow.external::<()>();
2159
2160        let node_tick = node.tick();
2161        // Tick-located constants are lazy and never fire the tick on their own, so a spinning
2162        // batch drives `node_tick`.
2163        node_tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
2164        let tick_singleton = node_tick.singleton(q!(123));
2165        let tick_optional_inhabited: Optional<_, _, _> = tick_singleton.into();
2166        let counts = tick_optional_inhabited
2167            .clone()
2168            .or(tick_optional_inhabited)
2169            .into_stream()
2170            .count()
2171            .all_ticks()
2172            .send_bincode_external(&external);
2173
2174        let nodes = flow
2175            .with_process(&node, deployment.Localhost())
2176            .with_external(&external, deployment.Localhost())
2177            .deploy(&mut deployment);
2178
2179        deployment.deploy().await.unwrap();
2180
2181        let mut external_out = nodes.connect(counts).await;
2182
2183        deployment.start().await.unwrap();
2184
2185        assert_eq!(external_out.next().await.unwrap(), 1);
2186    }
2187
2188    #[cfg(feature = "deploy")]
2189    #[tokio::test]
2190    async fn into_singleton_top_level_none_cardinality() {
2191        let mut deployment = Deployment::new();
2192
2193        let mut flow = FlowBuilder::new();
2194        let node = flow.process::<()>();
2195        let external = flow.external::<()>();
2196
2197        let node_tick = node.tick();
2198        let top_level_none = node.singleton(q!(123)).filter(q!(|_| false));
2199        let into_singleton = top_level_none.into_singleton();
2200
2201        let tick_driver = node.spin();
2202
2203        let counts = into_singleton
2204            .snapshot(&node_tick, nondet!(/** test */))
2205            .into_stream()
2206            .count()
2207            .zip(tick_driver.batch(&node_tick, nondet!(/** test */)).count())
2208            .map(q!(|(c, _)| c))
2209            .all_ticks()
2210            .send_bincode_external(&external);
2211
2212        let nodes = flow
2213            .with_process(&node, deployment.Localhost())
2214            .with_external(&external, deployment.Localhost())
2215            .deploy(&mut deployment);
2216
2217        deployment.deploy().await.unwrap();
2218
2219        let mut external_out = nodes.connect(counts).await;
2220
2221        deployment.start().await.unwrap();
2222
2223        assert_eq!(external_out.next().await.unwrap(), 1);
2224        assert_eq!(external_out.next().await.unwrap(), 1);
2225        assert_eq!(external_out.next().await.unwrap(), 1);
2226    }
2227
2228    #[cfg(feature = "deploy")]
2229    #[tokio::test]
2230    async fn into_singleton_unbounded_top_level_none_cardinality() {
2231        let mut deployment = Deployment::new();
2232
2233        let mut flow = FlowBuilder::new();
2234        let node = flow.process::<()>();
2235        let external = flow.external::<()>();
2236
2237        let none_tick = node.tick();
2238        // Tick-located constants are lazy and never fire the tick on their own, so a spinning
2239        // batch drives `none_tick`.
2240        none_tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
2241        let top_level_none = none_tick.singleton(q!(123)).latest().filter(q!(|_| false));
2242        let into_singleton = top_level_none.into_singleton();
2243
2244        let tick_driver = node.spin();
2245
2246        let tick_later = node.tick();
2247        let counts = into_singleton
2248            .snapshot(&tick_later, nondet!(/** test */))
2249            .into_stream()
2250            .count()
2251            .zip(tick_driver.batch(&tick_later, nondet!(/** test */)).count())
2252            .map(q!(|(c, _)| c))
2253            .all_ticks()
2254            .send_bincode_external(&external);
2255
2256        let nodes = flow
2257            .with_process(&node, deployment.Localhost())
2258            .with_external(&external, deployment.Localhost())
2259            .deploy(&mut deployment);
2260
2261        deployment.deploy().await.unwrap();
2262
2263        let mut external_out = nodes.connect(counts).await;
2264
2265        deployment.start().await.unwrap();
2266
2267        assert_eq!(external_out.next().await.unwrap(), 1);
2268        assert_eq!(external_out.next().await.unwrap(), 1);
2269        assert_eq!(external_out.next().await.unwrap(), 1);
2270    }
2271
2272    #[cfg(feature = "sim")]
2273    #[test]
2274    fn top_level_optional_some_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_some = folded.filter(q!(|_| true));
2281
2282        let out_recv = filtered_some.into_stream().sim_output();
2283
2284        flow.sim().exhaustive(async || {
2285            out_recv.assert_yields_only([10]).await;
2286        });
2287    }
2288
2289    #[cfg(feature = "sim")]
2290    #[test]
2291    fn top_level_optional_none_into_stream_no_replay() {
2292        let mut flow = FlowBuilder::new();
2293        let node = flow.process::<()>();
2294
2295        let source_iter = node.source_iter(q!(vec![1, 2, 3, 4]));
2296        let folded = source_iter.fold(q!(|| 0), q!(|a, b| *a += b));
2297        let filtered_none = folded.filter(q!(|_| false));
2298
2299        let out_recv = filtered_none.into_stream().sim_output();
2300
2301        flow.sim().exhaustive(async || {
2302            out_recv.assert_yields_only([] as [i32; 0]).await;
2303        });
2304    }
2305
2306    #[cfg(feature = "deploy")]
2307    #[tokio::test]
2308    async fn test_optional_ref() {
2309        let mut deployment = Deployment::new();
2310
2311        let mut flow = FlowBuilder::new();
2312        let external = flow.external::<()>();
2313        let p1 = flow.process::<()>();
2314
2315        // Create an optional: reduce 0..5 => Some(10) (sum via reduce)
2316        let my_opt = p1.source_iter(q!(0..5i32)).reduce(q!(|a, b| *a += b));
2317
2318        let opt_ref = my_opt.by_ref();
2319
2320        // Use the optional ref in a map: unwrap_or(0) + x
2321        let out_port = p1
2322            .source_iter(q!(1..=3i32))
2323            .map(q!(|x| x + opt_ref.unwrap_or(0)))
2324            .send_bincode_external(&external);
2325
2326        let nodes = flow
2327            .with_default_optimize()
2328            .with_process(&p1, deployment.Localhost())
2329            .with_external(&external, deployment.Localhost())
2330            .deploy(&mut deployment);
2331
2332        deployment.deploy().await.unwrap();
2333
2334        let mut out_recv = nodes.connect(out_port).await;
2335
2336        deployment.start().await.unwrap();
2337
2338        let mut results = Vec::new();
2339        for _ in 0..3 {
2340            results.push(out_recv.next().await.unwrap());
2341        }
2342        results.sort();
2343        // reduce(0..5) = 10, so results should be 11, 12, 13
2344        assert_eq!(results, vec![11, 12, 13]);
2345    }
2346
2347    #[cfg(feature = "deploy")]
2348    #[tokio::test]
2349    async fn test_optional_ref_none() {
2350        let mut deployment = Deployment::new();
2351
2352        let mut flow = FlowBuilder::new();
2353        let external = flow.external::<()>();
2354        let p1 = flow.process::<()>();
2355
2356        // Create an optional from an empty source => None
2357        let my_opt = p1
2358            .source_iter(q!(std::iter::empty::<i32>()))
2359            .reduce(q!(|a, b| *a += b));
2360
2361        let opt_ref = my_opt.by_ref();
2362
2363        // Use the optional ref: should be None, so unwrap_or(99)
2364        let out_port = p1
2365            .source_iter(q!(1..=2i32))
2366            .map(q!(|x| x + opt_ref.unwrap_or(99)))
2367            .send_bincode_external(&external);
2368
2369        let nodes = flow
2370            .with_default_optimize()
2371            .with_process(&p1, deployment.Localhost())
2372            .with_external(&external, deployment.Localhost())
2373            .deploy(&mut deployment);
2374
2375        deployment.deploy().await.unwrap();
2376
2377        let mut out_recv = nodes.connect(out_port).await;
2378
2379        deployment.start().await.unwrap();
2380
2381        let mut results = Vec::new();
2382        for _ in 0..2 {
2383            results.push(out_recv.next().await.unwrap());
2384        }
2385        results.sort();
2386        // optional is None, so unwrap_or(99) => 100, 101
2387        assert_eq!(results, vec![100, 101]);
2388    }
2389
2390    #[cfg(feature = "deploy")]
2391    #[tokio::test]
2392    async fn test_optional_ref_and_consume() {
2393        let mut deployment = Deployment::new();
2394
2395        let mut flow = FlowBuilder::new();
2396        let external = flow.external::<()>();
2397        let p1 = flow.process::<()>();
2398
2399        // Use reduce to produce an Optional
2400        let my_opt = p1.source_iter(q!(0..5i32)).reduce(q!(|a, b| *a += b));
2401
2402        let opt_ref = my_opt.by_ref();
2403
2404        // Reference path
2405        let out_port_ref = p1
2406            .source_iter(q!(1..=2i32))
2407            .map(q!(|x| x + opt_ref.unwrap_or(0)))
2408            .send_bincode_external(&external);
2409
2410        let nodes = flow
2411            .with_default_optimize()
2412            .with_process(&p1, deployment.Localhost())
2413            .with_external(&external, deployment.Localhost())
2414            .deploy(&mut deployment);
2415
2416        deployment.deploy().await.unwrap();
2417
2418        let mut out_recv_ref = nodes.connect(out_port_ref).await;
2419
2420        deployment.start().await.unwrap();
2421
2422        let mut ref_results = Vec::new();
2423        for _ in 0..2 {
2424            ref_results.push(out_recv_ref.next().await.unwrap());
2425        }
2426        ref_results.sort();
2427        // reduce(0..5) = 10, so 1+10=11, 2+10=12
2428        assert_eq!(ref_results, vec![11, 12]);
2429    }
2430
2431    /// A root `Unbounded` optional (a tombstoned update feed) that holds the latest value sent
2432    /// on `input`, where `None` makes it null again. Built from a `sliced!` state singleton so
2433    /// that it can be simulated.
2434    #[cfg(feature = "sim")]
2435    pub(crate) fn sim_unbounded_optional<'a>(
2436        node: &crate::location::Process<'a>,
2437        input: crate::live_collections::Stream<
2438            Option<u32>,
2439            crate::location::Process<'a>,
2440            crate::live_collections::boundedness::Unbounded,
2441        >,
2442    ) -> Optional<u32, crate::location::Process<'a>, crate::live_collections::boundedness::Unbounded>
2443    {
2444        use crate::live_collections::sliced::sliced;
2445        use crate::nondet::nondet;
2446
2447        let _ = node;
2448        sliced! {
2449            let batch = use::batch(input, nondet!(/** test */));
2450            let mut latest = use::state(|l| l.singleton(q!(None)));
2451            latest = batch.last().unwrap_or(latest);
2452            latest.clone()
2453        }
2454        .filter_map(q!(|v| v))
2455    }
2456
2457    /// `or` of two root `Unbounded` optionals switches to the fallback once the left side becomes
2458    /// null again, and both sides' values are observable.
2459    #[cfg(feature = "sim")]
2460    #[test]
2461    fn sim_top_level_or_unbounded() {
2462        use crate::live_collections::stream::{ExactlyOnce, TotalOrder};
2463        use crate::nondet::nondet;
2464
2465        let mut flow = FlowBuilder::new();
2466        let node = flow.process::<()>();
2467
2468        let (left_port, left_input) = node.sim_input::<Option<u32>, TotalOrder, ExactlyOnce>();
2469        let (right_port, right_input) = node.sim_input::<Option<u32>, TotalOrder, ExactlyOnce>();
2470        let (trigger_port, trigger) = node.sim_input::<(), TotalOrder, ExactlyOnce>();
2471
2472        let left = sim_unbounded_optional(&node, left_input);
2473        let right = sim_unbounded_optional(&node, right_input);
2474        let result = left.or(right).into_singleton();
2475
2476        let tick = node.tick();
2477        let output = trigger
2478            .batch(&tick, nondet!(/** test */))
2479            .cross_singleton(result.snapshot(&tick, nondet!(/** test */)))
2480            .map(q!(|(_, v)| v))
2481            .all_ticks()
2482            .sim_output();
2483
2484        let mut observed = std::collections::HashSet::new();
2485        let instances = flow.sim().exhaustive(async || {
2486            left_port.send(Some(1));
2487            left_port.send(None);
2488            right_port.send(Some(2));
2489            trigger_port.send(());
2490            trigger_port.send(());
2491
2492            observed.insert(output.collect::<Vec<_>>().await);
2493        });
2494        assert_eq!(instances, 5157);
2495
2496        // Every trajectory production allows. The left side goes null -> 1 -> null (covering
2497        // both the override and the fallback), the right side null -> 2, independently, so the
2498        // result moves along a monotone path through the (left, right) version grid. The two
2499        // trigger firings observe the result at two points `p <= q` along that path (equal if
2500        // they fire together). So e.g. `[Some(2), Some(1)]` (left overrides) and
2501        // `[Some(1), Some(2)]` (fallback) are possible, but `[Some(2), None]` is not.
2502        let left_versions = [None, Some(1), None];
2503        let right_versions = [None, Some(2)];
2504        let points = (0..left_versions.len())
2505            .flat_map(|l| (0..right_versions.len()).map(move |r| (l, r)))
2506            .collect::<Vec<_>>();
2507        let value = |(l, r): (usize, usize)| left_versions[l].or(right_versions[r]);
2508        let mut expected = std::collections::HashSet::new();
2509        for &p in &points {
2510            for &q in &points {
2511                if p.0 <= q.0 && p.1 <= q.1 {
2512                    expected.insert(vec![value(p), value(q)]);
2513                }
2514            }
2515        }
2516        assert_eq!(observed, expected);
2517    }
2518
2519    /// `zip` of two root bounded optionals produces the pair once both are present (never a
2520    /// partial pair), and `is_some` of a root `Unbounded` optional tracks presence, including
2521    /// becoming null again.
2522    #[cfg(feature = "sim")]
2523    #[test]
2524    fn sim_top_level_zip_bounded_and_is_some() {
2525        use crate::live_collections::stream::{ExactlyOnce, TotalOrder};
2526        use crate::nondet::nondet;
2527
2528        let mut flow = FlowBuilder::new();
2529        let node = flow.process::<()>();
2530
2531        let (input_port, input) = node.sim_input::<Option<u32>, TotalOrder, ExactlyOnce>();
2532        let (trigger_port, trigger) = node.sim_input::<(), TotalOrder, ExactlyOnce>();
2533
2534        let zipped = node
2535            .source_iter(q!([1u32]))
2536            .first()
2537            .zip(node.source_iter(q!([2u32])).first())
2538            .into_singleton();
2539        let present = sim_unbounded_optional(&node, input).is_some();
2540
2541        let tick = node.tick();
2542        let output = trigger
2543            .batch(&tick, nondet!(/** test */))
2544            .cross_singleton(zipped.snapshot(&tick, nondet!(/** test */)))
2545            .cross_singleton(present.snapshot(&tick, nondet!(/** test */)))
2546            .map(q!(|((_, zipped), present)| (zipped, present)))
2547            .all_ticks()
2548            .sim_output();
2549
2550        let mut observed = std::collections::HashSet::new();
2551        let instances = flow.sim().exhaustive(async || {
2552            input_port.send(Some(7));
2553            input_port.send(None);
2554            trigger_port.send(());
2555            trigger_port.send(());
2556
2557            observed.insert(output.collect::<Vec<_>>().await);
2558        });
2559        assert_eq!(instances, 1823);
2560
2561        // Every trajectory production allows. `zipped` goes null -> (1, 2) and `present` goes
2562        // false -> true -> false, independently; the two trigger firings observe both at two
2563        // points `p <= q` of the (zipped, present) version grid. In particular the pair is
2564        // never retracted.
2565        let zipped_versions = [None, Some((1, 2))];
2566        let present_versions = [false, true, false];
2567        let points = (0..zipped_versions.len())
2568            .flat_map(|z| (0..present_versions.len()).map(move |p| (z, p)))
2569            .collect::<Vec<_>>();
2570        let value = |(z, p): (usize, usize)| (zipped_versions[z], present_versions[p]);
2571        let mut expected = std::collections::HashSet::new();
2572        for &p in &points {
2573            for &q in &points {
2574                if p.0 <= q.0 && p.1 <= q.1 {
2575                    expected.insert(vec![value(p), value(q)]);
2576                }
2577            }
2578        }
2579        assert_eq!(observed, expected);
2580    }
2581
2582    /// `sample_eager` of a root `InitNone` optional samples versions in order: every run's
2583    /// samples (ignoring stutters) are an increasing subsequence of the possible versions ending
2584    /// with the final one, and the simulator explores skipping intermediate versions.
2585    #[cfg(feature = "sim")]
2586    #[test]
2587    fn sim_top_level_optional_sample_eager() {
2588        use crate::live_collections::sliced::sliced;
2589        use crate::live_collections::stream::{ExactlyOnce, TotalOrder};
2590        use crate::nondet::nondet;
2591
2592        let mut flow = FlowBuilder::new();
2593        let node = flow.process::<()>();
2594
2595        let (input_port, input) = node.sim_input::<u32, TotalOrder, ExactlyOnce>();
2596        // A running sum, null until the first input arrives.
2597        let sum = sliced! {
2598            let batch = use::batch(input, nondet!(/** test */));
2599            let mut sum = use::state(|l| l.singleton(q!(0u32)));
2600            sum = sum.zip(batch.fold(q!(|| 0u32), q!(|acc, v| *acc += v)))
2601                .map(q!(|(sum, batch)| sum + batch));
2602            sum.clone()
2603        };
2604        let output = sum
2605            .sample_eager(nondet!(/** test */))
2606            // Samples may repeat (stutter); the samples are strictly increasing versions, so
2607            // dropping repeats is exactly de-duplication.
2608            .unique()
2609            .sim_output();
2610
2611        let mut observed = std::collections::BTreeSet::new();
2612        flow.sim().exhaustive(async || {
2613            input_port.send(1);
2614            input_port.send(2);
2615            input_port.send(3);
2616
2617            let samples = output.collect::<Vec<_>>().await;
2618            assert!(
2619                samples.windows(2).all(|w| w[0] < w[1]),
2620                "samples are not increasing: {samples:?}"
2621            );
2622            assert!(samples.iter().all(|v| [0, 1, 3, 6].contains(v)));
2623            assert_eq!(samples.last(), Some(&6));
2624            observed.insert(samples);
2625        });
2626
2627        // Skipping intermediate versions is explored.
2628        assert!(observed.iter().any(|samples| samples.len() > 1));
2629        assert!(observed.contains(&vec![6]));
2630    }
2631}