Skip to main content

hydro_lang/live_collections/stream/
mod.rs

1//! Definitions for the [`Stream`] live collection.
2
3use std::cell::RefCell;
4use std::future::Future;
5use std::hash::Hash;
6use std::marker::PhantomData;
7use std::ops::Deref;
8use std::rc::Rc;
9
10use stageleft::{IntoQuotedMut, QuotedWithContext, QuotedWithContextWithProps, q, quote_type};
11
12use super::OperatorContext;
13use super::boundedness::{Bounded, Boundedness, IsBounded, Unbounded};
14use super::keyed_singleton::KeyedSingleton;
15use super::keyed_stream::{Generate, KeyedStream};
16use super::optional::Optional;
17use super::singleton::Singleton;
18#[cfg(feature = "tokio")]
19use super::sliced::sliced;
20use crate::compile::builder::{CycleId, FlowState};
21use crate::compile::ir::{
22    CollectionKind, HydroIrOpMetadata, HydroNode, HydroRoot, SharedNode, StreamOrder, StreamRetry,
23};
24#[cfg(stageleft_runtime)]
25use crate::forward_handle::{CycleCollection, CycleCollectionWithInitial, ReceiverComplete};
26use crate::forward_handle::{ForwardRef, TickCycle};
27use crate::live_collections::batch_atomic::BatchAtomic;
28use crate::live_collections::singleton::SingletonBound;
29#[cfg(stageleft_runtime)]
30use crate::location::dynamic::{DynLocation, LocationId};
31use crate::location::tick::{Atomic, DeferTick};
32use crate::location::{Location, Tick, TopLevel, check_matching_location};
33use crate::manual_expr::ManualExpr;
34use crate::nondet::{NonDet, nondet};
35use crate::prelude::manual_proof;
36use crate::properties::{
37    AggFuncAlgebra, ApplyMonotoneStream, NotProved, StreamMapFuncAlgebra, ValidCommutativityFor,
38    ValidIdempotenceFor, ValidMutBorrowCommutativityFor, ValidMutBorrowIdempotenceFor,
39    ValidMutCommutativityFor, ValidMutIdempotenceFor,
40};
41
42pub mod networking;
43
44/// A trait implemented by valid ordering markers ([`TotalOrder`] and [`NoOrder`]).
45#[sealed::sealed]
46pub trait Ordering:
47    MinOrder<Self, Min = Self> + MinOrder<TotalOrder, Min = Self> + MinOrder<NoOrder, Min = NoOrder>
48{
49    /// The [`StreamOrder`] corresponding to this type.
50    const ORDERING_KIND: StreamOrder;
51}
52
53/// Marks the stream as being totally ordered, which means that there are
54/// no sources of non-determinism (other than intentional ones) that will
55/// affect the order of elements.
56pub enum TotalOrder {}
57
58#[sealed::sealed]
59impl Ordering for TotalOrder {
60    const ORDERING_KIND: StreamOrder = StreamOrder::TotalOrder;
61}
62
63/// Marks the stream as having no order, which means that the order of
64/// elements may be affected by non-determinism.
65///
66/// This restricts certain operators, such as `fold` and `reduce`, to only
67/// be used with commutative aggregation functions.
68pub enum NoOrder {}
69
70#[sealed::sealed]
71impl Ordering for NoOrder {
72    const ORDERING_KIND: StreamOrder = StreamOrder::NoOrder;
73}
74
75/// Marker trait for an [`Ordering`] that is available when `Self` is a weaker guarantee than
76/// `Other`, which means that a stream with `Other` guarantees can be safely converted to
77/// have `Self` guarantees instead.
78#[sealed::sealed]
79pub trait WeakerOrderingThan<Other: ?Sized>: Ordering {}
80#[sealed::sealed]
81impl<O, O2: Ordering> WeakerOrderingThan<O2> for O where O: Ordering + MinOrder<O2, Min = O> {}
82
83/// Helper trait for determining the weakest of two orderings.
84#[sealed::sealed]
85pub trait MinOrder<Other: ?Sized> {
86    /// The weaker of the two orderings.
87    type Min: Ordering;
88}
89
90#[sealed::sealed]
91impl<O: Ordering> MinOrder<O> for TotalOrder {
92    type Min = O;
93}
94
95#[sealed::sealed]
96impl<O: Ordering> MinOrder<O> for NoOrder {
97    type Min = NoOrder;
98}
99
100/// A trait implemented by valid retries markers ([`ExactlyOnce`] and [`AtLeastOnce`]).
101#[sealed::sealed]
102pub trait Retries:
103    MinRetries<Self, Min = Self>
104    + MinRetries<ExactlyOnce, Min = Self>
105    + MinRetries<AtLeastOnce, Min = AtLeastOnce>
106{
107    /// The [`StreamRetry`] corresponding to this type.
108    const RETRIES_KIND: StreamRetry;
109}
110
111/// Marks the stream as having deterministic message cardinality, with no
112/// possibility of duplicates.
113pub enum ExactlyOnce {}
114
115#[sealed::sealed]
116impl Retries for ExactlyOnce {
117    const RETRIES_KIND: StreamRetry = StreamRetry::ExactlyOnce;
118}
119
120/// Marks the stream as having non-deterministic message cardinality, which
121/// means that duplicates may occur, but messages will not be dropped.
122pub enum AtLeastOnce {}
123
124#[sealed::sealed]
125impl Retries for AtLeastOnce {
126    const RETRIES_KIND: StreamRetry = StreamRetry::AtLeastOnce;
127}
128
129/// Marker trait for a [`Retries`] that is available when `Self` is a weaker guarantee than
130/// `Other`, which means that a stream with `Other` guarantees can be safely converted to
131/// have `Self` guarantees instead.
132#[sealed::sealed]
133pub trait WeakerRetryThan<Other: ?Sized>: Retries {}
134#[sealed::sealed]
135impl<R, R2: Retries> WeakerRetryThan<R2> for R where R: Retries + MinRetries<R2, Min = R> {}
136
137/// Helper trait for determining the weakest of two retry guarantees.
138#[sealed::sealed]
139pub trait MinRetries<Other: ?Sized> {
140    /// The weaker of the two retry guarantees.
141    type Min: Retries + WeakerRetryThan<Self> + WeakerRetryThan<Other>;
142}
143
144#[sealed::sealed]
145impl<R: Retries> MinRetries<R> for ExactlyOnce {
146    type Min = R;
147}
148
149#[sealed::sealed]
150impl<R: Retries> MinRetries<R> for AtLeastOnce {
151    type Min = AtLeastOnce;
152}
153
154#[sealed::sealed]
155#[diagnostic::on_unimplemented(
156    message = "the input stream must be totally ordered (`TotalOrder`), but has order `{Self}`",
157    label = "required here",
158    note = "strengthen the order upstream, or consider a different API",
159    note = "to intentionally process the stream by observing a non-deterministic (shuffled) order of elements, use `.assume_ordering`; this introduces non-determinism, so avoid it unless necessary"
160)]
161/// Marker trait that is implemented for the [`TotalOrder`] ordering guarantee.
162pub trait IsOrdered: Ordering {}
163
164#[sealed::sealed]
165#[diagnostic::do_not_recommend]
166impl IsOrdered for TotalOrder {}
167
168#[sealed::sealed]
169#[diagnostic::on_unimplemented(
170    message = "the input stream must be exactly-once (`ExactlyOnce`), but has retries `{Self}`",
171    label = "required here",
172    note = "strengthen the retries guarantee upstream, or consider a different API",
173    note = "to intentionally process the stream by observing non-deterministic (randomly duplicated) retries, use `.assume_retries`; this introduces non-determinism, so avoid it unless necessary"
174)]
175/// Marker trait that is implemented for the [`ExactlyOnce`] retries guarantee.
176pub trait IsExactlyOnce: Retries {}
177
178#[sealed::sealed]
179#[diagnostic::do_not_recommend]
180impl IsExactlyOnce for ExactlyOnce {}
181
182/// Streaming sequence of elements with type `Type`.
183///
184/// This live collection represents a growing sequence of elements, with new elements being
185/// asynchronously appended to the end of the sequence. This can be used to model the arrival
186/// of network input, such as API requests, or streaming ingestion.
187///
188/// By default, all streams have deterministic ordering and each element is materialized exactly
189/// once. But streams can also capture non-determinism via the `Order` and `Retries` type
190/// parameters. When the ordering / retries guarantee is relaxed, fewer APIs will be available
191/// on the stream. For example, if the stream is unordered, you cannot invoke [`Stream::first`].
192///
193/// Type Parameters:
194/// - `Type`: the type of elements in the stream
195/// - `Loc`: the location where the stream is being materialized
196/// - `Bound`: the boundedness of the stream, which is either [`Bounded`] or [`Unbounded`]
197/// - `Order`: the ordering of the stream, which is either [`TotalOrder`] or [`NoOrder`]
198///   (default is [`TotalOrder`])
199/// - `Retries`: the retry guarantee of the stream, which is either [`ExactlyOnce`] or
200///   [`AtLeastOnce`] (default is [`ExactlyOnce`])
201pub struct Stream<
202    Type,
203    Loc,
204    Bound: Boundedness = Unbounded,
205    Order: Ordering = TotalOrder,
206    Retry: Retries = ExactlyOnce,
207> {
208    pub(crate) location: Loc,
209    pub(crate) ir_node: Rc<RefCell<HydroNode>>,
210    pub(crate) flow_state: FlowState,
211
212    _phantom: PhantomData<(Type, Loc, Bound, Order, Retry)>,
213}
214
215impl<T, L, B: Boundedness, O: Ordering, R: Retries> Drop for Stream<T, L, B, O, R> {
216    fn drop(&mut self) {
217        let ir_node = self.ir_node.replace(HydroNode::Placeholder);
218        if !matches!(ir_node, HydroNode::Placeholder) && !ir_node.is_shared_with_others() {
219            self.flow_state.borrow_mut().try_push_root(HydroRoot::Null {
220                input: Box::new(ir_node),
221                op_metadata: HydroIrOpMetadata::new(),
222            });
223        }
224    }
225}
226
227impl<'a, T, L, O: Ordering, R: Retries> From<Stream<T, L, Bounded, O, R>>
228    for Stream<T, L, Unbounded, O, R>
229where
230    L: Location<'a>,
231{
232    fn from(stream: Stream<T, L, Bounded, O, R>) -> Stream<T, L, Unbounded, O, R> {
233        let new_meta = stream
234            .location
235            .new_node_metadata(Stream::<T, L, Unbounded, O, R>::collection_kind());
236
237        let flow_state = stream.flow_state.clone();
238        Stream {
239            location: stream.location.clone(),
240            ir_node: super::tracked_ir_node(
241                &flow_state,
242                HydroNode::Cast {
243                    inner: Box::new(stream.ir_node.replace(HydroNode::Placeholder)),
244                    metadata: new_meta,
245                },
246            ),
247            flow_state,
248            _phantom: PhantomData,
249        }
250    }
251}
252
253impl<'a, T, L, B: Boundedness, R: Retries> From<Stream<T, L, B, TotalOrder, R>>
254    for Stream<T, L, B, NoOrder, R>
255where
256    L: Location<'a>,
257{
258    fn from(stream: Stream<T, L, B, TotalOrder, R>) -> Stream<T, L, B, NoOrder, R> {
259        stream.weaken_ordering()
260    }
261}
262
263impl<'a, T, L, B: Boundedness, O: Ordering> From<Stream<T, L, B, O, ExactlyOnce>>
264    for Stream<T, L, B, O, AtLeastOnce>
265where
266    L: Location<'a>,
267{
268    fn from(stream: Stream<T, L, B, O, ExactlyOnce>) -> Stream<T, L, B, O, AtLeastOnce> {
269        stream.weaken_retries()
270    }
271}
272
273impl<'a, T, L, O: Ordering, R: Retries> DeferTick for Stream<T, Tick<L>, Bounded, O, R>
274where
275    L: Location<'a>,
276{
277    fn defer_tick(self) -> Self {
278        Stream::<T, Tick<L>, Bounded, O, R>::defer_tick(self)
279    }
280}
281
282impl<'a, T, L, O: Ordering, R: Retries> CycleCollection<'a, TickCycle>
283    for Stream<T, Tick<L>, Bounded, O, R>
284where
285    L: Location<'a>,
286{
287    type Location = Tick<L>;
288
289    fn create_source(cycle_id: CycleId, location: Tick<L>) -> Self {
290        Stream::new(
291            location.clone(),
292            HydroNode::CycleSource {
293                cycle_id,
294                metadata: location.new_node_metadata(Self::collection_kind()),
295            },
296        )
297    }
298}
299
300impl<'a, T, L, O: Ordering, R: Retries> CycleCollectionWithInitial<'a, TickCycle>
301    for Stream<T, Tick<L>, Bounded, O, R>
302where
303    L: Location<'a>,
304{
305    type Location = Tick<L>;
306
307    fn location(&self) -> &Self::Location {
308        self.location()
309    }
310
311    fn create_source_with_initial(cycle_id: CycleId, initial: Self, location: Tick<L>) -> Self {
312        let from_previous_tick: Stream<T, Tick<L>, Bounded, O, R> = Stream::new(
313            location.clone(),
314            HydroNode::DeferTick {
315                input: Box::new(HydroNode::CycleSource {
316                    cycle_id,
317                    metadata: location.new_node_metadata(Self::collection_kind()),
318                }),
319                metadata: location.new_node_metadata(Self::collection_kind()),
320            },
321        );
322
323        from_previous_tick.chain(initial.filter_if(location.optional_first_tick(q!(())).is_some()))
324    }
325}
326
327impl<'a, T, L, O: Ordering, R: Retries> ReceiverComplete<'a, TickCycle>
328    for Stream<T, Tick<L>, Bounded, O, R>
329where
330    L: Location<'a>,
331{
332    fn complete(self, cycle_id: CycleId, expected_location: LocationId) {
333        assert_eq!(
334            Location::id(&self.location),
335            expected_location,
336            "locations do not match"
337        );
338        self.location
339            .flow_state()
340            .borrow_mut()
341            .push_root(HydroRoot::CycleSink {
342                cycle_id,
343                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
344                op_metadata: HydroIrOpMetadata::new(),
345            });
346    }
347}
348
349impl<'a, T, L, B: Boundedness, O: Ordering, R: Retries> CycleCollection<'a, ForwardRef>
350    for Stream<T, L, B, O, R>
351where
352    L: Location<'a>,
353{
354    type Location = L;
355
356    fn create_source(cycle_id: CycleId, location: L) -> Self {
357        Stream::new(
358            location.clone(),
359            HydroNode::CycleSource {
360                cycle_id,
361                metadata: location.new_node_metadata(Self::collection_kind()),
362            },
363        )
364    }
365}
366
367impl<'a, T, L, B: Boundedness, O: Ordering, R: Retries> ReceiverComplete<'a, ForwardRef>
368    for Stream<T, L, B, O, R>
369where
370    L: Location<'a>,
371{
372    fn complete(self, cycle_id: CycleId, expected_location: LocationId) {
373        assert_eq!(
374            Location::id(&self.location),
375            expected_location,
376            "locations do not match"
377        );
378        self.location
379            .flow_state()
380            .borrow_mut()
381            .push_root(HydroRoot::CycleSink {
382                cycle_id,
383                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
384                op_metadata: HydroIrOpMetadata::new(),
385            });
386    }
387}
388
389impl<'a, T, L, B: Boundedness, O: Ordering, R: Retries> Clone for Stream<T, L, B, O, R>
390where
391    T: Clone,
392    L: Location<'a>,
393{
394    fn clone(&self) -> Self {
395        if !matches!(self.ir_node.borrow().deref(), HydroNode::Tee { .. }) {
396            let orig_ir_node = self.ir_node.replace(HydroNode::Placeholder);
397            *self.ir_node.borrow_mut() = HydroNode::Tee {
398                inner: SharedNode(Rc::new(RefCell::new(orig_ir_node))),
399                metadata: self.location.new_node_metadata(Self::collection_kind()),
400            };
401        }
402
403        let HydroNode::Tee { inner, metadata } = &*self.ir_node.borrow() else {
404            unreachable!()
405        };
406        Stream {
407            location: self.location.clone(),
408            flow_state: self.flow_state.clone(),
409            ir_node: super::tracked_ir_node(
410                &self.flow_state,
411                HydroNode::Tee {
412                    inner: SharedNode(inner.0.clone()),
413                    metadata: metadata.clone(),
414                },
415            ),
416            _phantom: PhantomData,
417        }
418    }
419}
420
421impl<'a, T, L, B: Boundedness, O: Ordering, R: Retries> Stream<T, L, B, O, R>
422where
423    L: Location<'a>,
424{
425    pub(crate) fn new(location: L, ir_node: HydroNode) -> Self {
426        debug_assert_eq!(ir_node.metadata().location_id, Location::id(&location));
427        debug_assert_eq!(ir_node.metadata().collection_kind, Self::collection_kind());
428
429        let flow_state = location.flow_state().clone();
430        let ir_node = super::tracked_ir_node(&flow_state, ir_node);
431        Stream {
432            location,
433            flow_state,
434            ir_node,
435            _phantom: PhantomData,
436        }
437    }
438
439    /// Returns the [`Location`] where this stream is being materialized.
440    pub fn location(&self) -> &L {
441        &self.location
442    }
443
444    /// Creates a shared reference handle to this stream's handoff buffer that can be captured
445    /// inside `q!()` closures. The handle resolves to `&Vec<T>` at runtime.
446    ///
447    /// The stream must be bounded, otherwise reading it would be non-deterministic.
448    pub fn by_ref(&self) -> crate::handoff_ref::StreamRef<'a, '_, T, L, B>
449    where
450        B: IsBounded,
451    {
452        crate::handoff_ref::StreamRef::new(&self.ir_node)
453    }
454
455    /// Returns a mutable reference handle to this stream's handoff buffer that can be captured
456    /// inside `q!()` closures. The handle resolves to `&mut Vec<T>` at runtime.
457    pub fn by_mut(&self) -> crate::handoff_ref::StreamMut<'a, '_, T, L, B>
458    where
459        B: IsBounded,
460    {
461        crate::handoff_ref::StreamMut::new(&self.ir_node)
462    }
463
464    /// Weakens the consistency of this live collection to not guarantee any consistency across
465    /// cluster members (if this collection is on a cluster).
466    pub fn weaken_consistency(self) -> Stream<T, L::DropConsistency, B, O, R>
467    where
468        L: Location<'a>,
469    {
470        if L::consistency()
471            .is_none_or(|c| c == crate::location::dynamic::ClusterConsistency::NoConsistency)
472        {
473            // already no consistency
474            Stream::new(
475                self.location.drop_consistency(),
476                self.ir_node.replace(HydroNode::Placeholder),
477            )
478        } else {
479            Stream::new(
480                self.location.drop_consistency(),
481                HydroNode::Cast {
482                    inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
483                    metadata: self.location.drop_consistency().new_node_metadata(Stream::<
484                        T,
485                        L::DropConsistency,
486                        B,
487                        O,
488                        R,
489                    >::collection_kind(
490                    )),
491                },
492            )
493        }
494    }
495
496    /// Casts this live collection to have the consistency guarantees specified in the given
497    /// location type parameter. The developer must ensure that the strengthened consistency
498    /// is actually guaranteed, via the proof field (see [`crate::prelude::manual_proof`]).
499    pub fn assert_has_consistency_of<L2: Location<'a, DropConsistency = L::DropConsistency>>(
500        self,
501        _proof: impl crate::properties::ConsistencyProof,
502    ) -> Stream<T, L2, B, O, R>
503    where
504        L: Location<'a>,
505    {
506        if L::consistency() == L2::consistency() {
507            Stream::new(
508                self.location.with_consistency_of(),
509                self.ir_node.replace(HydroNode::Placeholder),
510            )
511        } else {
512            Stream::new(
513                self.location.with_consistency_of(),
514                HydroNode::AssertIsConsistent {
515                    inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
516                    trusted: false,
517                    metadata: self
518                        .location
519                        .clone()
520                        .with_consistency_of::<L2>()
521                        .new_node_metadata(Stream::<T, L2, B, O, R>::collection_kind()),
522                },
523            )
524        }
525    }
526
527    pub(crate) fn assert_has_consistency_of_trusted<
528        L2: Location<'a, DropConsistency = L::DropConsistency>,
529    >(
530        self,
531        _proof: impl crate::properties::ConsistencyProof,
532    ) -> Stream<T, L2, B, O, R>
533    where
534        L: Location<'a>,
535    {
536        if L::consistency() == L2::consistency() {
537            Stream::new(
538                self.location.with_consistency_of(),
539                self.ir_node.replace(HydroNode::Placeholder),
540            )
541        } else {
542            Stream::new(
543                self.location.with_consistency_of(),
544                HydroNode::AssertIsConsistent {
545                    inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
546                    trusted: true,
547                    metadata: self
548                        .location
549                        .clone()
550                        .with_consistency_of::<L2>()
551                        .new_node_metadata(Stream::<T, L2, B, O, R>::collection_kind()),
552                },
553            )
554        }
555    }
556
557    pub(crate) fn collection_kind() -> CollectionKind {
558        CollectionKind::Stream {
559            bound: B::BOUND_KIND,
560            order: O::ORDERING_KIND,
561            retry: R::RETRIES_KIND,
562            element_type: quote_type::<T>().into(),
563        }
564    }
565
566    /// Produces a stream based on invoking `f` on each element.
567    /// If you do not want to modify the stream and instead only want to view
568    /// each item use [`Stream::inspect`] instead.
569    ///
570    /// If the input stream is unordered **and** `f` mutably captures state (such as a
571    /// [`Singleton::by_mut`](crate::live_collections::singleton::Singleton::by_mut)
572    /// reference), `f` must be proven **commutative**: processing any two elements in
573    /// either order must leave the mutably-captured state in the same final value *and*
574    /// produce the same multiset of outputs. In particular, outputs must not expose the
575    /// processing order (e.g. emitting a running total is not commutative even though
576    /// addition is).
577    ///
578    /// Similarly, if the input stream has retries (`AtLeastOnce`) **and** `f` mutably
579    /// captures state, `f` must be proven **idempotent**: processing an element twice in
580    /// a row must leave the mutably-captured state in the same final value as processing
581    /// it once *and* return the same output both times. In particular, outputs must not
582    /// expose whether an element is a retry (e.g. emitting "is this a new maximum?" is not
583    /// idempotent even though `max` is).
584    ///
585    /// # Example
586    /// ```rust
587    /// # #[cfg(feature = "deploy")] {
588    /// # use hydro_lang::prelude::*;
589    /// # use futures::StreamExt;
590    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
591    /// let words = process.source_iter(q!(vec!["hello", "world"]));
592    /// words.map(q!(|x| x.to_uppercase()))
593    /// # }, |mut stream| async move {
594    /// # for w in vec!["HELLO", "WORLD"] {
595    /// #     assert_eq!(stream.next().await.unwrap(), w);
596    /// # }
597    /// # }));
598    /// # }
599    /// ```
600    pub fn map<U, F, C, I, const WAS_MUT: bool>(
601        self,
602        f: impl IntoQuotedMut<
603            'a,
604            F,
605            OperatorContext<L, B>,
606            StreamMapFuncAlgebra<T, B, C, I, L::SimHookScope>,
607        >,
608    ) -> Stream<U, L, B, O, R>
609    where
610        F: FnMut(T) -> U + 'a,
611        C: ValidMutCommutativityFor<F, T, U, O, WAS_MUT>,
612        I: ValidMutIdempotenceFor<F, T, U, R, WAS_MUT>,
613    {
614        let f = crate::handoff_ref::with_ref_capture(|| {
615            let (expr, proof) =
616                f.splice_fnmut1_ctx_props(&OperatorContext::<L, B>::new(&self.location));
617            proof.register_proof(&expr);
618            expr.into()
619        });
620        Stream::new(
621            self.location.clone(),
622            HydroNode::Map {
623                f,
624                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
625                metadata: self
626                    .location
627                    .new_node_metadata(Stream::<U, L, B, O, R>::collection_kind()),
628            },
629        )
630    }
631
632    /// For each item `i` in the input stream, transform `i` using `f` and then treat the
633    /// result as an [`Iterator`] to produce items one by one. The implementation for [`Iterator`]
634    /// for the output type `U` must produce items in a **deterministic** order.
635    ///
636    /// For example, `U` could be a `Vec`, but not a `HashSet`. If the order of the items in `U` is
637    /// not deterministic, use [`Stream::flat_map_unordered`] instead.
638    ///
639    /// # Example
640    /// ```rust
641    /// # #[cfg(feature = "deploy")] {
642    /// # use hydro_lang::prelude::*;
643    /// # use futures::StreamExt;
644    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
645    /// process
646    ///     .source_iter(q!(vec![vec![1, 2], vec![3, 4]]))
647    ///     .flat_map_ordered(q!(|x| x))
648    /// # }, |mut stream| async move {
649    /// // 1, 2, 3, 4
650    /// # for w in (1..5) {
651    /// #     assert_eq!(stream.next().await.unwrap(), w);
652    /// # }
653    /// # }));
654    /// # }
655    /// ```
656    pub fn flat_map_ordered<U, I, F, C, Idemp, const WAS_MUT: bool>(
657        self,
658        f: impl IntoQuotedMut<
659            'a,
660            F,
661            OperatorContext<L, B>,
662            StreamMapFuncAlgebra<T, B, C, Idemp, L::SimHookScope>,
663        >,
664    ) -> Stream<U, L, B, O, R>
665    where
666        I: IntoIterator<Item = U>,
667        F: FnMut(T) -> I + 'a,
668        C: ValidMutCommutativityFor<F, T, I, O, WAS_MUT>,
669        Idemp: ValidMutIdempotenceFor<F, T, I, R, WAS_MUT>,
670    {
671        let f = crate::handoff_ref::with_ref_capture(|| {
672            let (expr, proof) =
673                f.splice_fnmut1_ctx_props(&OperatorContext::<L, B>::new(&self.location));
674            proof.register_proof(&expr);
675            expr.into()
676        });
677        Stream::new(
678            self.location.clone(),
679            HydroNode::FlatMap {
680                f,
681                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
682                metadata: self
683                    .location
684                    .new_node_metadata(Stream::<U, L, B, O, R>::collection_kind()),
685            },
686        )
687    }
688
689    /// Like [`Stream::flat_map_ordered`], but allows the implementation of [`Iterator`]
690    /// for the output type `U` to produce items in any order.
691    ///
692    /// # Example
693    /// ```rust
694    /// # #[cfg(feature = "deploy")] {
695    /// # use hydro_lang::{prelude::*, live_collections::stream::{NoOrder, ExactlyOnce}};
696    /// # use futures::StreamExt;
697    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test::<_, _, _, NoOrder, ExactlyOnce>(|process| {
698    /// process
699    ///     .source_iter(q!(vec![
700    ///         std::collections::HashSet::<i32>::from_iter(vec![1, 2]),
701    ///         std::collections::HashSet::from_iter(vec![3, 4]),
702    ///     ]))
703    ///     .flat_map_unordered(q!(|x| x))
704    /// # }, |mut stream| async move {
705    /// // 1, 2, 3, 4, but in no particular order
706    /// # let mut results = Vec::new();
707    /// # for w in (1..5) {
708    /// #     results.push(stream.next().await.unwrap());
709    /// # }
710    /// # results.sort();
711    /// # assert_eq!(results, vec![1, 2, 3, 4]);
712    /// # }));
713    /// # }
714    /// ```
715    pub fn flat_map_unordered<U, I, F, C, Idemp, const WAS_MUT: bool>(
716        self,
717        f: impl IntoQuotedMut<
718            'a,
719            F,
720            OperatorContext<L, B>,
721            StreamMapFuncAlgebra<T, B, C, Idemp, L::SimHookScope>,
722        >,
723    ) -> Stream<U, L, B, NoOrder, R>
724    where
725        I: IntoIterator<Item = U>,
726        F: FnMut(T) -> I + 'a,
727        C: ValidMutCommutativityFor<F, T, I, O, WAS_MUT>,
728        Idemp: ValidMutIdempotenceFor<F, T, I, R, WAS_MUT>,
729    {
730        let f = crate::handoff_ref::with_ref_capture(|| {
731            let (expr, proof) =
732                f.splice_fnmut1_ctx_props(&OperatorContext::<L, B>::new(&self.location));
733            proof.register_proof(&expr);
734            expr.into()
735        });
736        Stream::new(
737            self.location.clone(),
738            HydroNode::FlatMap {
739                f,
740                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
741                metadata: self
742                    .location
743                    .new_node_metadata(Stream::<U, L, B, NoOrder, R>::collection_kind()),
744            },
745        )
746    }
747
748    /// For each item `i` in the input stream, treat `i` as an [`Iterator`] and produce its items one by one.
749    /// The implementation for [`Iterator`] for the element type `T` must produce items in a **deterministic** order.
750    ///
751    /// For example, `T` could be a `Vec`, but not a `HashSet`. If the order of the items in `T` is
752    /// not deterministic, use [`Stream::flatten_unordered`] instead.
753    ///
754    /// ```rust
755    /// # #[cfg(feature = "deploy")] {
756    /// # use hydro_lang::prelude::*;
757    /// # use futures::StreamExt;
758    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
759    /// process
760    ///     .source_iter(q!(vec![vec![1, 2], vec![3, 4]]))
761    ///     .flatten_ordered()
762    /// # }, |mut stream| async move {
763    /// // 1, 2, 3, 4
764    /// # for w in (1..5) {
765    /// #     assert_eq!(stream.next().await.unwrap(), w);
766    /// # }
767    /// # }));
768    /// # }
769    /// ```
770    pub fn flatten_ordered<U>(self) -> Stream<U, L, B, O, R>
771    where
772        T: IntoIterator<Item = U>,
773    {
774        self.flat_map_ordered(q!(|d| d))
775    }
776
777    /// Like [`Stream::flatten_ordered`], but allows the implementation of [`Iterator`]
778    /// for the element type `T` to produce items in any order.
779    ///
780    /// # Example
781    /// ```rust
782    /// # #[cfg(feature = "deploy")] {
783    /// # use hydro_lang::{prelude::*, live_collections::stream::{NoOrder, ExactlyOnce}};
784    /// # use futures::StreamExt;
785    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test::<_, _, _, NoOrder, ExactlyOnce>(|process| {
786    /// process
787    ///     .source_iter(q!(vec![
788    ///         std::collections::HashSet::<i32>::from_iter(vec![1, 2]),
789    ///         std::collections::HashSet::from_iter(vec![3, 4]),
790    ///     ]))
791    ///     .flatten_unordered()
792    /// # }, |mut stream| async move {
793    /// // 1, 2, 3, 4, but in no particular order
794    /// # let mut results = Vec::new();
795    /// # for w in (1..5) {
796    /// #     results.push(stream.next().await.unwrap());
797    /// # }
798    /// # results.sort();
799    /// # assert_eq!(results, vec![1, 2, 3, 4]);
800    /// # }));
801    /// # }
802    /// ```
803    pub fn flatten_unordered<U>(self) -> Stream<U, L, B, NoOrder, R>
804    where
805        T: IntoIterator<Item = U>,
806    {
807        self.flat_map_unordered(q!(|d| d))
808    }
809
810    /// For each item in the input stream, apply `f` to produce a [`futures::stream::Stream`],
811    /// then emit the elements of that stream one by one. When the inner stream yields
812    /// `Pending`, this operator yields as well.
813    pub fn flat_map_stream_blocking<U, S, F, C, Idemp, const WAS_MUT: bool>(
814        self,
815        f: impl IntoQuotedMut<
816            'a,
817            F,
818            OperatorContext<L, B>,
819            StreamMapFuncAlgebra<T, B, C, Idemp, L::SimHookScope>,
820        >,
821    ) -> Stream<U, L, B, O, R>
822    where
823        S: futures::Stream<Item = U>,
824        F: FnMut(T) -> S + 'a,
825        C: ValidMutCommutativityFor<F, T, S, O, WAS_MUT>,
826        Idemp: ValidMutIdempotenceFor<F, T, S, R, WAS_MUT>,
827    {
828        let f = crate::handoff_ref::with_ref_capture(|| {
829            let (expr, proof) =
830                f.splice_fnmut1_ctx_props(&OperatorContext::<L, B>::new(&self.location));
831            proof.register_proof(&expr);
832            expr.into()
833        });
834        Stream::new(
835            self.location.clone(),
836            HydroNode::FlatMapStreamBlocking {
837                f,
838                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
839                metadata: self
840                    .location
841                    .new_node_metadata(Stream::<U, L, B, O, R>::collection_kind()),
842            },
843        )
844    }
845
846    /// For each item in the input stream, treat it as a [`futures::stream::Stream`] and
847    /// emit its elements one by one. When the inner stream yields `Pending`, this operator
848    /// yields as well.
849    pub fn flatten_stream_blocking<U>(self) -> Stream<U, L, B, O, R>
850    where
851        T: futures::Stream<Item = U>,
852    {
853        self.flat_map_stream_blocking(q!(|d| d))
854    }
855
856    /// Creates a stream containing only the elements of the input stream that satisfy a predicate
857    /// `f`, preserving the order of the elements.
858    ///
859    /// The closure `f` receives a reference `&T` rather than an owned value `T` because filtering does
860    /// not modify or take ownership of the values. If you need to modify the values while filtering
861    /// use [`Stream::filter_map`] instead.
862    ///
863    /// If the input stream is unordered **and** `f` mutably captures state, `f` must be
864    /// proven **commutative**: processing any two elements in either order must leave
865    /// the mutably-captured state in the same final value *and* retain the same multiset
866    /// of elements. In particular, the decision for each element must not depend on the
867    /// processing order: a stateful predicate like a rate limiter is not commutative —
868    /// its budget converges either way, but *which* element passes depends on the order.
869    ///
870    /// Similarly, if the input stream has retries (`AtLeastOnce`) **and** `f` mutably
871    /// captures state, `f` must be proven **idempotent**: processing an element twice in
872    /// a row must leave the mutably-captured state in the same final value as processing
873    /// it once *and* make the same decision both times. In particular, the decision must
874    /// not depend on whether the element was seen before.
875    ///
876    /// # Example
877    /// ```rust
878    /// # #[cfg(feature = "deploy")] {
879    /// # use hydro_lang::prelude::*;
880    /// # use futures::StreamExt;
881    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
882    /// process
883    ///     .source_iter(q!(vec![1, 2, 3, 4]))
884    ///     .filter(q!(|&x| x > 2))
885    /// # }, |mut stream| async move {
886    /// // 3, 4
887    /// # for w in (3..5) {
888    /// #     assert_eq!(stream.next().await.unwrap(), w);
889    /// # }
890    /// # }));
891    /// # }
892    /// ```
893    pub fn filter<F, C, Idemp, const WAS_MUT: bool>(
894        self,
895        f: impl IntoQuotedMut<
896            'a,
897            F,
898            OperatorContext<L, B>,
899            StreamMapFuncAlgebra<T, B, C, Idemp, L::SimHookScope>,
900        >,
901    ) -> Self
902    where
903        F: FnMut(&T) -> bool + 'a,
904        C: ValidMutBorrowCommutativityFor<F, T, bool, O, WAS_MUT>,
905        Idemp: ValidMutBorrowIdempotenceFor<F, T, bool, R, WAS_MUT>,
906    {
907        let f = crate::handoff_ref::with_ref_capture(|| {
908            let (expr, proof) =
909                f.splice_fnmut1_borrow_ctx_props(&OperatorContext::<L, B>::new(&self.location));
910            proof.register_proof(&expr);
911            expr.into()
912        });
913        Stream::new(
914            self.location.clone(),
915            HydroNode::Filter {
916                f,
917                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
918                metadata: self.location.new_node_metadata(Self::collection_kind()),
919            },
920        )
921    }
922
923    /// Splits the stream into two streams based on a predicate, without cloning elements.
924    ///
925    /// Elements for which `f` returns `true` are sent to the first output stream,
926    /// and elements for which `f` returns `false` are sent to the second output stream.
927    ///
928    /// Unlike using `filter` twice, this only evaluates the predicate once per element
929    /// and does not require `T: Clone`.
930    ///
931    /// The closure `f` receives a reference `&T` rather than an owned value `T` because
932    /// the predicate is only used for routing; the element itself is moved to the
933    /// appropriate output stream.
934    ///
935    /// If the input stream has retries (`AtLeastOnce`) **and** `f` mutably captures
936    /// state, `f` must be proven **idempotent**: processing an element twice in a row
937    /// must leave the mutably-captured state in the same final value as processing it
938    /// once *and* make the same decision both times (otherwise a retried element would
939    /// appear in the *other* output).
940    ///
941    /// # Example
942    /// ```rust
943    /// # #[cfg(feature = "deploy")] {
944    /// # use hydro_lang::prelude::*;
945    /// # use hydro_lang::live_collections::stream::{NoOrder, ExactlyOnce};
946    /// # use futures::StreamExt;
947    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test::<_, _, _, NoOrder, ExactlyOnce>(|process| {
948    /// let numbers: Stream<_, _, Unbounded> = process.source_iter(q!(vec![1, 2, 3, 4, 5, 6])).into();
949    /// let (evens, odds) = numbers.partition(q!(|&x| x % 2 == 0));
950    /// // evens: 2, 4, 6 tagged with true; odds: 1, 3, 5 tagged with false
951    /// evens.map(q!(|x| (x, true)))
952    ///     .merge_unordered(odds.map(q!(|x| (x, false))))
953    /// # }, |mut stream| async move {
954    /// # let mut results = Vec::new();
955    /// # for _ in 0..6 {
956    /// #     results.push(stream.next().await.unwrap());
957    /// # }
958    /// # results.sort();
959    /// # assert_eq!(results, vec![(1, false), (2, true), (3, false), (4, true), (5, false), (6, true)]);
960    /// # }));
961    /// # }
962    /// ```
963    pub fn partition<F, C, Idemp, const WAS_MUT: bool>(
964        self,
965        f: impl IntoQuotedMut<
966            'a,
967            F,
968            OperatorContext<L, B>,
969            StreamMapFuncAlgebra<T, B, C, Idemp, L::SimHookScope>,
970        >,
971    ) -> (Stream<T, L, B, O, R>, Stream<T, L, B, O, R>)
972    where
973        F: FnMut(&T) -> bool + 'a,
974        C: ValidMutBorrowCommutativityFor<F, T, bool, O, WAS_MUT>,
975        Idemp: ValidMutBorrowIdempotenceFor<F, T, bool, R, WAS_MUT>,
976    {
977        let f = crate::handoff_ref::with_ref_capture(|| {
978            let (expr, proof) =
979                f.splice_fnmut1_borrow_ctx_props(&OperatorContext::<L, B>::new(&self.location));
980            proof.register_proof(&expr);
981            expr.into()
982        });
983        let shared = Rc::new(RefCell::new(HydroNode::PartitionShared {
984            input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
985            f,
986            metadata: self.location.new_node_metadata(Self::collection_kind()),
987        }));
988
989        let true_stream = Stream::new(
990            self.location.clone(),
991            HydroNode::PartitionSide {
992                inner: SharedNode(Rc::clone(&shared)),
993                is_true: true,
994                metadata: self.location.new_node_metadata(Self::collection_kind()),
995            },
996        );
997
998        let false_stream = Stream::new(
999            self.location.clone(),
1000            HydroNode::PartitionSide {
1001                inner: SharedNode(shared),
1002                is_true: false,
1003                metadata: self.location.new_node_metadata(Self::collection_kind()),
1004            },
1005        );
1006
1007        (true_stream, false_stream)
1008    }
1009
1010    /// An operator that both filters and maps. It yields only the items for which the supplied closure `f` returns `Some(value)`.
1011    ///
1012    /// # Example
1013    /// ```rust
1014    /// # #[cfg(feature = "deploy")] {
1015    /// # use hydro_lang::prelude::*;
1016    /// # use futures::StreamExt;
1017    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1018    /// process
1019    ///     .source_iter(q!(vec!["1", "hello", "world", "2"]))
1020    ///     .filter_map(q!(|s| s.parse::<usize>().ok()))
1021    /// # }, |mut stream| async move {
1022    /// // 1, 2
1023    /// # for w in (1..3) {
1024    /// #     assert_eq!(stream.next().await.unwrap(), w);
1025    /// # }
1026    /// # }));
1027    /// # }
1028    /// ```
1029    pub fn filter_map<U, F, C, Idemp, const WAS_MUT: bool>(
1030        self,
1031        f: impl IntoQuotedMut<
1032            'a,
1033            F,
1034            OperatorContext<L, B>,
1035            StreamMapFuncAlgebra<T, B, C, Idemp, L::SimHookScope>,
1036        >,
1037    ) -> Stream<U, L, B, O, R>
1038    where
1039        F: FnMut(T) -> Option<U> + 'a,
1040        C: ValidMutCommutativityFor<F, T, Option<U>, O, WAS_MUT>,
1041        Idemp: ValidMutIdempotenceFor<F, T, Option<U>, R, WAS_MUT>,
1042    {
1043        let f = crate::handoff_ref::with_ref_capture(|| {
1044            let (expr, proof) =
1045                f.splice_fnmut1_ctx_props(&OperatorContext::<L, B>::new(&self.location));
1046            proof.register_proof(&expr);
1047            expr.into()
1048        });
1049        Stream::new(
1050            self.location.clone(),
1051            HydroNode::FilterMap {
1052                f,
1053                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1054                metadata: self
1055                    .location
1056                    .new_node_metadata(Stream::<U, L, B, O, R>::collection_kind()),
1057            },
1058        )
1059    }
1060
1061    /// Generates a stream that maps each input element `i` to a tuple `(i, x)`,
1062    /// where `x` is the final value of `other`, a bounded [`Singleton`] or [`Optional`].
1063    /// If `other` is an empty [`Optional`], no values will be produced.
1064    ///
1065    /// # Example
1066    /// ```rust
1067    /// # #[cfg(feature = "deploy")] {
1068    /// # use hydro_lang::prelude::*;
1069    /// # use futures::StreamExt;
1070    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1071    /// let tick = process.tick();
1072    /// let batch = process
1073    ///   .source_iter(q!(vec![1, 2, 3, 4]))
1074    ///   .batch(&tick, nondet!(/** test */));
1075    /// let count = batch.clone().count(); // `count()` returns a singleton
1076    /// batch.cross_singleton(count).all_ticks()
1077    /// # }, |mut stream| async move {
1078    /// // (1, 4), (2, 4), (3, 4), (4, 4)
1079    /// # for w in vec![(1, 4), (2, 4), (3, 4), (4, 4)] {
1080    /// #     assert_eq!(stream.next().await.unwrap(), w);
1081    /// # }
1082    /// # }));
1083    /// # }
1084    /// ```
1085    pub fn cross_singleton<O2>(
1086        self,
1087        other: impl Into<Optional<O2, L, Bounded>>,
1088    ) -> Stream<(T, O2), L, B, O, R>
1089    where
1090        O2: Clone,
1091    {
1092        let other: Optional<O2, L, Bounded> = other.into();
1093        check_matching_location(&self.location, &other.location);
1094
1095        Stream::new(
1096            self.location.clone(),
1097            HydroNode::CrossSingleton {
1098                left: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1099                right: Box::new(other.ir_node.replace(HydroNode::Placeholder)),
1100                metadata: self
1101                    .location
1102                    .new_node_metadata(Stream::<(T, O2), L, B, O, R>::collection_kind()),
1103            },
1104        )
1105    }
1106
1107    /// Passes this stream through if the boolean signal is `true`, otherwise the output is empty.
1108    ///
1109    /// # Example
1110    /// ```rust
1111    /// # #[cfg(feature = "deploy")] {
1112    /// # use hydro_lang::prelude::*;
1113    /// # use futures::StreamExt;
1114    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1115    /// let tick = process.tick();
1116    /// // ticks are lazy by default, forces the second tick to run
1117    /// tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1118    ///
1119    /// let signal = tick.optional_first_tick(q!(())).is_some(); // true on tick 1, false on tick 2
1120    /// let batch_first_tick = process
1121    ///   .source_iter(q!(vec![1, 2, 3, 4]))
1122    ///   .batch(&tick, nondet!(/** test */));
1123    /// let batch_second_tick = process
1124    ///   .source_iter(q!(vec![5, 6, 7, 8]))
1125    ///   .batch(&tick, nondet!(/** test */))
1126    ///   .defer_tick();
1127    /// batch_first_tick.chain(batch_second_tick)
1128    ///   .filter_if(signal)
1129    ///   .all_ticks()
1130    /// # }, |mut stream| async move {
1131    /// // [1, 2, 3, 4]
1132    /// # for w in vec![1, 2, 3, 4] {
1133    /// #     assert_eq!(stream.next().await.unwrap(), w);
1134    /// # }
1135    /// # }));
1136    /// # }
1137    /// ```
1138    pub fn filter_if(self, signal: Singleton<bool, L, Bounded>) -> Stream<T, L, B, O, R> {
1139        self.cross_singleton(signal.filter(q!(|b| *b)))
1140            .map(q!(|(d, _)| d))
1141    }
1142
1143    /// Passes this stream through if the argument (a [`Bounded`] [`Optional`]) is non-null, otherwise the output is empty.
1144    ///
1145    /// Useful for gating the release of elements based on a condition, such as only processing requests if you are the
1146    /// leader of a cluster.
1147    ///
1148    /// # Example
1149    /// ```rust
1150    /// # #[cfg(feature = "deploy")] {
1151    /// # use hydro_lang::prelude::*;
1152    /// # use futures::StreamExt;
1153    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1154    /// let tick = process.tick();
1155    /// // ticks are lazy by default, forces the second tick to run
1156    /// tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1157    ///
1158    /// let batch_first_tick = process
1159    ///   .source_iter(q!(vec![1, 2, 3, 4]))
1160    ///   .batch(&tick, nondet!(/** test */));
1161    /// let batch_second_tick = process
1162    ///   .source_iter(q!(vec![5, 6, 7, 8]))
1163    ///   .batch(&tick, nondet!(/** test */))
1164    ///   .defer_tick(); // appears on the second tick
1165    /// let some_on_first_tick = tick.optional_first_tick(q!(()));
1166    /// batch_first_tick.chain(batch_second_tick)
1167    ///   .filter_if_some(some_on_first_tick)
1168    ///   .all_ticks()
1169    /// # }, |mut stream| async move {
1170    /// // [1, 2, 3, 4]
1171    /// # for w in vec![1, 2, 3, 4] {
1172    /// #     assert_eq!(stream.next().await.unwrap(), w);
1173    /// # }
1174    /// # }));
1175    /// # }
1176    /// ```
1177    #[deprecated(note = "use `filter_if` with `Optional::is_some()` instead")]
1178    pub fn filter_if_some<U>(self, signal: Optional<U, L, Bounded>) -> Stream<T, L, B, O, R> {
1179        self.filter_if(signal.is_some())
1180    }
1181
1182    /// Passes this stream through if the argument (a [`Bounded`] [`Optional`]) is null, otherwise the output is empty.
1183    ///
1184    /// Useful for gating the release of elements based on a condition, such as triggering a protocol if you are missing
1185    /// some local state.
1186    ///
1187    /// # Example
1188    /// ```rust
1189    /// # #[cfg(feature = "deploy")] {
1190    /// # use hydro_lang::prelude::*;
1191    /// # use futures::StreamExt;
1192    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1193    /// let tick = process.tick();
1194    /// // ticks are lazy by default, forces the second tick to run
1195    /// tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1196    ///
1197    /// let batch_first_tick = process
1198    ///   .source_iter(q!(vec![1, 2, 3, 4]))
1199    ///   .batch(&tick, nondet!(/** test */));
1200    /// let batch_second_tick = process
1201    ///   .source_iter(q!(vec![5, 6, 7, 8]))
1202    ///   .batch(&tick, nondet!(/** test */))
1203    ///   .defer_tick(); // appears on the second tick
1204    /// let some_on_first_tick = tick.optional_first_tick(q!(()));
1205    /// batch_first_tick.chain(batch_second_tick)
1206    ///   .filter_if_none(some_on_first_tick)
1207    ///   .all_ticks()
1208    /// # }, |mut stream| async move {
1209    /// // [5, 6, 7, 8]
1210    /// # for w in vec![5, 6, 7, 8] {
1211    /// #     assert_eq!(stream.next().await.unwrap(), w);
1212    /// # }
1213    /// # }));
1214    /// # }
1215    /// ```
1216    #[deprecated(note = "use `filter_if` with `!Optional::is_some()` instead")]
1217    pub fn filter_if_none<U>(self, other: Optional<U, L, Bounded>) -> Stream<T, L, B, O, R> {
1218        self.filter_if(other.is_none())
1219    }
1220
1221    /// Forms the cross-product (Cartesian product, cross-join) of the items in the 2 input streams,
1222    /// returning all tupled pairs.
1223    ///
1224    /// When the right side is [`Bounded`], it is accumulated first and the left side streams
1225    /// through, preserving the left side's ordering. When both sides are [`Unbounded`], a
1226    /// symmetric hash join is used and ordering is [`NoOrder`].
1227    ///
1228    /// # Example
1229    /// ```rust
1230    /// # #[cfg(feature = "deploy")] {
1231    /// # use hydro_lang::prelude::*;
1232    /// # use std::collections::HashSet;
1233    /// # use futures::StreamExt;
1234    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1235    /// let tick = process.tick();
1236    /// let stream1 = process.source_iter(q!(vec![1, 2]));
1237    /// let stream2 = process.source_iter(q!(vec!['a', 'b']));
1238    /// stream1.cross_product(stream2)
1239    /// # }, |mut stream| async move {
1240    /// // (1, 'a'), (1, 'b'), (2, 'a'), (2, 'b') in any order
1241    /// # let expected = HashSet::from([(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]);
1242    /// # stream.map(|i| assert!(expected.contains(&i)));
1243    /// # }));
1244    /// # }
1245    pub fn cross_product<T2, B2: Boundedness, O2: Ordering, R2: Retries>(
1246        self,
1247        other: Stream<T2, L, B2, O2, R2>,
1248    ) -> Stream<(T, T2), L, B, B2::PreserveOrderIfBounded<O>, <R as MinRetries<R2>>::Min>
1249    where
1250        T: Clone,
1251        T2: Clone,
1252        R: MinRetries<R2>,
1253    {
1254        self.map(q!(|v| ((), v)))
1255            .join(other.map(q!(|v| ((), v))))
1256            .map(q!(|((), (v1, v2))| (v1, v2)))
1257    }
1258
1259    /// Takes one stream as input and filters out any duplicate occurrences. The output
1260    /// contains all unique values from the input.
1261    ///
1262    /// # Example
1263    /// ```rust
1264    /// # #[cfg(feature = "deploy")] {
1265    /// # use hydro_lang::prelude::*;
1266    /// # use futures::StreamExt;
1267    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1268    /// let tick = process.tick();
1269    /// process.source_iter(q!(vec![1, 2, 3, 2, 1, 4])).unique()
1270    /// # }, |mut stream| async move {
1271    /// # for w in vec![1, 2, 3, 4] {
1272    /// #     assert_eq!(stream.next().await.unwrap(), w);
1273    /// # }
1274    /// # }));
1275    /// # }
1276    /// ```
1277    pub fn unique(self) -> Stream<T, L, B, O, ExactlyOnce>
1278    where
1279        T: Eq + Hash,
1280    {
1281        Stream::new(
1282            self.location.clone(),
1283            HydroNode::Unique {
1284                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1285                metadata: self
1286                    .location
1287                    .new_node_metadata(Stream::<T, L, B, O, ExactlyOnce>::collection_kind()),
1288            },
1289        )
1290    }
1291
1292    /// Outputs everything in this stream that is *not* contained in the `other` stream.
1293    ///
1294    /// The `other` stream must be [`Bounded`], since this function will wait until
1295    /// all its elements are available before producing any output.
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    /// let stream = process
1304    ///   .source_iter(q!(vec![ 1, 2, 3, 4 ]))
1305    ///   .batch(&tick, nondet!(/** test */));
1306    /// let batch = process
1307    ///   .source_iter(q!(vec![1, 2]))
1308    ///   .batch(&tick, nondet!(/** test */));
1309    /// stream.filter_not_in(batch).all_ticks()
1310    /// # }, |mut stream| async move {
1311    /// # for w in vec![3, 4] {
1312    /// #     assert_eq!(stream.next().await.unwrap(), w);
1313    /// # }
1314    /// # }));
1315    /// # }
1316    /// ```
1317    pub fn filter_not_in<O2: Ordering, B2>(self, other: Stream<T, L, B2, O2, R>) -> Self
1318    where
1319        T: Eq + Hash,
1320        B2: IsBounded,
1321    {
1322        check_matching_location(&self.location, &other.location);
1323
1324        Stream::new(
1325            self.location.clone(),
1326            HydroNode::Difference {
1327                pos: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1328                neg: Box::new(other.ir_node.replace(HydroNode::Placeholder)),
1329                metadata: self
1330                    .location
1331                    .new_node_metadata(Stream::<T, L, Bounded, O, R>::collection_kind()),
1332            },
1333        )
1334    }
1335
1336    /// An operator which allows you to "inspect" each element of a stream without
1337    /// modifying it. The closure `f` is called on a reference to each item. This is
1338    /// mainly useful for debugging, and should not be used to generate side-effects.
1339    ///
1340    /// If the input stream is unordered **and** `f` mutably captures state, `f` must be
1341    /// proven **commutative**: executing it on any two elements in either order must
1342    /// leave the mutably-captured state in the same final value. (The elements
1343    /// themselves pass through unchanged.) Similarly, if the input stream has retries
1344    /// (`AtLeastOnce`), `f` must be proven **idempotent**: executing it on an element
1345    /// twice in a row must leave the mutably-captured state in the same final value as
1346    /// executing it once.
1347    ///
1348    /// # Example
1349    /// ```rust
1350    /// # #[cfg(feature = "deploy")] {
1351    /// # use hydro_lang::prelude::*;
1352    /// # use futures::StreamExt;
1353    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1354    /// let nums = process.source_iter(q!(vec![1, 2]));
1355    /// // prints "1 * 10 = 10" and "2 * 10 = 20"
1356    /// nums.inspect(q!(|x| println!("{} * 10 = {}", x, x * 10)))
1357    /// # }, |mut stream| async move {
1358    /// # for w in vec![1, 2] {
1359    /// #     assert_eq!(stream.next().await.unwrap(), w);
1360    /// # }
1361    /// # }));
1362    /// # }
1363    /// ```
1364    pub fn inspect<F, C, Idemp, const WAS_MUT: bool>(
1365        self,
1366        f: impl IntoQuotedMut<
1367            'a,
1368            F,
1369            OperatorContext<L::DropConsistency, B>,
1370            StreamMapFuncAlgebra<T, B, C, Idemp, L::SimHookScope>,
1371        >,
1372    ) -> Self
1373    where
1374        F: FnMut(&T) + 'a,
1375        C: ValidMutBorrowCommutativityFor<F, T, (), O, WAS_MUT>,
1376        Idemp: ValidMutBorrowIdempotenceFor<F, T, (), R, WAS_MUT>,
1377    {
1378        let f = crate::handoff_ref::with_ref_capture(|| {
1379            let (expr, proof) =
1380                f.splice_fnmut1_borrow_ctx_props(&OperatorContext::<L::DropConsistency, B>::new(
1381                    &self.location.drop_consistency(),
1382                ));
1383            proof.register_proof(&expr);
1384            expr.into()
1385        });
1386
1387        Stream::new(
1388            self.location.clone(),
1389            HydroNode::Inspect {
1390                f,
1391                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1392                metadata: self.location.new_node_metadata(Self::collection_kind()),
1393            },
1394        )
1395    }
1396
1397    /// Executes the provided closure for every element in this stream.
1398    ///
1399    /// If the stream is unordered or has retries, the closure must demonstrate commutativity
1400    /// and/or idempotence via annotations:
1401    /// ```rust,ignore
1402    /// stream.for_each(q!(
1403    ///     |x| *flag_mut |= x,
1404    ///     commutative = manual_proof!(/** boolean OR is commutative */),
1405    ///     idempotent = manual_proof!(/** boolean OR is idempotent */)
1406    /// ));
1407    /// ```
1408    ///
1409    /// **Commutative** here means that executing the closure on any two elements in
1410    /// either order must leave its side effects (e.g. mutably-captured state) in the
1411    /// same final value. **Idempotent** here means that executing the closure on an
1412    /// element twice in a row must leave its side effects in the same final value as
1413    /// executing it once.
1414    ///
1415    /// On a `TotalOrder + ExactlyOnce` stream, no annotations are needed.
1416    ///
1417    /// The closure may capture singletons via `by_ref()` or `by_mut()`, as long as the
1418    /// referenced collection lives at the same location and has the same boundedness as this
1419    /// stream.
1420    pub fn for_each<F: FnMut(T) + 'a, C, I>(
1421        self,
1422        f: impl IntoQuotedMut<
1423            'a,
1424            F,
1425            OperatorContext<L, B>,
1426            AggFuncAlgebra<T, B, C, I, NotProved, L::SimHookScope>,
1427        >,
1428    ) where
1429        C: ValidCommutativityFor<O>,
1430        I: ValidIdempotenceFor<R>,
1431    {
1432        let f = crate::handoff_ref::with_ref_capture(|| {
1433            let (f, proof) =
1434                f.splice_fnmut1_ctx_props(&OperatorContext::<L, B>::new(&self.location));
1435            proof.register_proof(&f);
1436            f.into()
1437        });
1438        self.location
1439            .flow_state()
1440            .borrow_mut()
1441            .push_root(HydroRoot::ForEach {
1442                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1443                f,
1444                op_metadata: HydroIrOpMetadata::new(),
1445            });
1446    }
1447
1448    /// Sends all elements of this stream to a provided [`futures::Sink`], such as an external
1449    /// TCP socket to some other server. You should _not_ use this API for interacting with
1450    /// external clients, instead see [`Location::bidi_external_many_bytes`] and
1451    /// [`Location::bidi_external_many_bincode`]. This should be used for custom, low-level
1452    /// interaction with asynchronous sinks.
1453    pub fn dest_sink<S>(self, sink: impl QuotedWithContext<'a, S, L>)
1454    where
1455        O: IsOrdered,
1456        R: IsExactlyOnce,
1457        S: 'a + futures::Sink<T> + Unpin,
1458    {
1459        self.location
1460            .flow_state()
1461            .borrow_mut()
1462            .push_root(HydroRoot::DestSink {
1463                sink: sink.splice_typed_ctx(&self.location).into(),
1464                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1465                op_metadata: HydroIrOpMetadata::new(),
1466            });
1467    }
1468
1469    /// Maps each element `x` of the stream to `(i, x)`, where `i` is the index of the element.
1470    ///
1471    /// # Example
1472    /// ```rust
1473    /// # #[cfg(feature = "deploy")] {
1474    /// # use hydro_lang::{prelude::*, live_collections::stream::{TotalOrder, ExactlyOnce}};
1475    /// # use futures::StreamExt;
1476    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test::<_, _, _, TotalOrder, ExactlyOnce>(|process| {
1477    /// let tick = process.tick();
1478    /// let numbers = process.source_iter(q!(vec![1, 2, 3, 4]));
1479    /// numbers.enumerate()
1480    /// # }, |mut stream| async move {
1481    /// // (0, 1), (1, 2), (2, 3), (3, 4)
1482    /// # for w in vec![(0, 1), (1, 2), (2, 3), (3, 4)] {
1483    /// #     assert_eq!(stream.next().await.unwrap(), w);
1484    /// # }
1485    /// # }));
1486    /// # }
1487    /// ```
1488    pub fn enumerate(self) -> Stream<(usize, T), L, B, O, R>
1489    where
1490        O: IsOrdered,
1491        R: IsExactlyOnce,
1492    {
1493        Stream::new(
1494            self.location.clone(),
1495            HydroNode::Enumerate {
1496                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1497                metadata: self.location.new_node_metadata(Stream::<
1498                    (usize, T),
1499                    L,
1500                    B,
1501                    TotalOrder,
1502                    ExactlyOnce,
1503                >::collection_kind()),
1504            },
1505        )
1506    }
1507
1508    /// Combines elements of the stream into a [`Singleton`], by starting with an intitial value,
1509    /// generated by the `init` closure, and then applying the `comb` closure to each element in the stream.
1510    /// Unlike iterators, `comb` takes the accumulator by `&mut` reference, so that it can be modified in place.
1511    ///
1512    /// Depending on the input stream guarantees, the closure may need to be commutative
1513    /// (for unordered streams) or idempotent (for streams with non-deterministic duplicates).
1514    ///
1515    /// # Example
1516    /// ```rust
1517    /// # #[cfg(feature = "deploy")] {
1518    /// # use hydro_lang::prelude::*;
1519    /// # use futures::StreamExt;
1520    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1521    /// let words = process.source_iter(q!(vec!["HELLO", "WORLD"]));
1522    /// words
1523    ///     .fold(q!(|| String::new()), q!(|acc, x| acc.push_str(x)))
1524    ///     .into_stream()
1525    /// # }, |mut stream| async move {
1526    /// // "HELLOWORLD"
1527    /// # assert_eq!(stream.next().await.unwrap(), "HELLOWORLD");
1528    /// # }));
1529    /// # }
1530    /// ```
1531    pub fn fold<A, I, F, C, Idemp, M, B2: SingletonBound>(
1532        self,
1533        init: impl IntoQuotedMut<'a, I, OperatorContext<L, B>>,
1534        comb: impl IntoQuotedMut<
1535            'a,
1536            F,
1537            OperatorContext<L, B>,
1538            AggFuncAlgebra<T, B, C, Idemp, M, L::SimHookScope>,
1539        >,
1540    ) -> Singleton<A, L, B2>
1541    where
1542        I: Fn() -> A + 'a,
1543        F: 'a + Fn(&mut A, T),
1544        C: ValidCommutativityFor<O>,
1545        Idemp: ValidIdempotenceFor<R>,
1546        B: ApplyMonotoneStream<M, B2>,
1547    {
1548        let init = init
1549            .splice_fn0_ctx(&OperatorContext::<L, B>::new(&self.location))
1550            .into();
1551        let (comb, proof) =
1552            comb.splice_fn2_borrow_mut_ctx_props(&OperatorContext::<L, B>::new(&self.location));
1553        let ordering_hook = proof.register_proof(&comb);
1554
1555        // Only assume_retries (for idempotence), not assume_ordering.
1556        // The fold hook in the simulator handles ordering non-determinism directly, so an
1557        // ordering hook on the commutativity proof binds to the fold operator itself.
1558        let nondet = nondet!(/** the combinator function is commutative and idempotent */);
1559        let retried: Stream<T, L::DropConsistency, B, O, ExactlyOnce> = self.assume_retries(nondet);
1560
1561        let mut metadata = retried
1562            .location
1563            .new_node_metadata(Singleton::<A, L::DropConsistency, B2>::collection_kind());
1564        metadata.op.sim_hook_id = ordering_hook.map(|hook| hook.id);
1565
1566        let core = HydroNode::Fold {
1567            init,
1568            acc: comb.into(),
1569            input: Box::new(retried.ir_node.replace(HydroNode::Placeholder)),
1570            metadata,
1571            // we do not guarantee consistency at this point because if the algebraic properties
1572            // do not hold in practice, replica consistency may fail to be maintained, so we
1573            // would like the simulator to assert consistency; in the future, this will be dynamic
1574            // based on the proof mechanism
1575        };
1576
1577        Singleton::new(retried.location.clone(), core)
1578            .assert_has_consistency_of(manual_proof!(/** algebraic properties */))
1579    }
1580
1581    /// Combines elements of the stream into an [`Optional`], by starting with the first element in the stream,
1582    /// and then applying the `comb` closure to each element in the stream. The [`Optional`] will be empty
1583    /// until the first element in the input arrives. Unlike iterators, `comb` takes the accumulator by `&mut`
1584    /// reference, so that it can be modified in place.
1585    ///
1586    /// Depending on the input stream guarantees, the closure may need to be commutative
1587    /// (for unordered streams) or idempotent (for streams with non-deterministic duplicates).
1588    ///
1589    /// # Example
1590    /// ```rust
1591    /// # #[cfg(feature = "deploy")] {
1592    /// # use hydro_lang::prelude::*;
1593    /// # use futures::StreamExt;
1594    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1595    /// let bools = process.source_iter(q!(vec![false, true, false]));
1596    /// bools.reduce(q!(|acc, x| *acc |= x)).into_stream()
1597    /// # }, |mut stream| async move {
1598    /// // true
1599    /// # assert_eq!(stream.next().await.unwrap(), true);
1600    /// # }));
1601    /// # }
1602    /// ```
1603    pub fn reduce<F, C, Idemp>(
1604        self,
1605        comb: impl IntoQuotedMut<
1606            'a,
1607            F,
1608            OperatorContext<L, B>,
1609            AggFuncAlgebra<T, B, C, Idemp, NotProved, L::SimHookScope>,
1610        >,
1611    ) -> Optional<T, L, B::AggregatedOptional>
1612    where
1613        F: Fn(&mut T, T) + 'a,
1614        C: ValidCommutativityFor<O>,
1615        Idemp: ValidIdempotenceFor<R>,
1616    {
1617        let (f, proof) =
1618            comb.splice_fn2_borrow_mut_ctx_props(&OperatorContext::<L, B>::new(&self.location));
1619        let ordering_hook = proof.register_proof(&f);
1620
1621        let nondet_retries = nondet!(/** the combinator function is commutative and idempotent */);
1622        let ordered_etc: Stream<T, L::DropConsistency, B> =
1623            self.assume_retries(nondet_retries).assume_ordering(nondet!(
1624                /// the combinator function is commutative; the simulator still explores
1625                /// (or scripts, via the proof's hook) the ordering
1626                hook = ordering_hook
1627            ));
1628
1629        let core = HydroNode::Reduce {
1630            f: f.into(),
1631            input: Box::new(ordered_etc.ir_node.replace(HydroNode::Placeholder)),
1632            metadata: ordered_etc.location.new_node_metadata(Optional::<
1633                T,
1634                L::DropConsistency,
1635                B::AggregatedOptional,
1636            >::collection_kind()),
1637        };
1638
1639        Optional::new(ordered_etc.location.clone(), core)
1640            .assert_has_consistency_of(manual_proof!(/** algebraic properties */))
1641    }
1642
1643    /// Computes the maximum element in the stream as an [`Optional`], which
1644    /// will be empty until the first element in the input arrives.
1645    ///
1646    /// # Example
1647    /// ```rust
1648    /// # #[cfg(feature = "deploy")] {
1649    /// # use hydro_lang::prelude::*;
1650    /// # use futures::StreamExt;
1651    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1652    /// let tick = process.tick();
1653    /// let numbers = process.source_iter(q!(vec![1, 2, 3, 4]));
1654    /// let batch = numbers.batch(&tick, nondet!(/** test */));
1655    /// batch.max().all_ticks()
1656    /// # }, |mut stream| async move {
1657    /// // 4
1658    /// # assert_eq!(stream.next().await.unwrap(), 4);
1659    /// # }));
1660    /// # }
1661    /// ```
1662    pub fn max(self) -> Optional<T, L, B::AggregatedOptional>
1663    where
1664        T: Ord,
1665    {
1666        self.assume_retries_trusted::<ExactlyOnce>(nondet!(/** max is idempotent */))
1667            .assume_ordering_trusted_bounded::<TotalOrder>(
1668                nondet!(/** max is commutative, but order affects intermediates */),
1669            )
1670            .reduce(q!(|curr, new| {
1671                if new > *curr {
1672                    *curr = new;
1673                }
1674            }))
1675    }
1676
1677    /// Computes the minimum element in the stream as an [`Optional`], which
1678    /// will be empty until the first element in the input arrives.
1679    ///
1680    /// # Example
1681    /// ```rust
1682    /// # #[cfg(feature = "deploy")] {
1683    /// # use hydro_lang::prelude::*;
1684    /// # use futures::StreamExt;
1685    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1686    /// let tick = process.tick();
1687    /// let numbers = process.source_iter(q!(vec![1, 2, 3, 4]));
1688    /// let batch = numbers.batch(&tick, nondet!(/** test */));
1689    /// batch.min().all_ticks()
1690    /// # }, |mut stream| async move {
1691    /// // 1
1692    /// # assert_eq!(stream.next().await.unwrap(), 1);
1693    /// # }));
1694    /// # }
1695    /// ```
1696    pub fn min(self) -> Optional<T, L, B::AggregatedOptional>
1697    where
1698        T: Ord,
1699    {
1700        self.assume_retries_trusted::<ExactlyOnce>(nondet!(/** min is idempotent */))
1701            .assume_ordering_trusted_bounded::<TotalOrder>(
1702                nondet!(/** max is commutative, but order affects intermediates */),
1703            )
1704            .reduce(q!(|curr, new| {
1705                if new < *curr {
1706                    *curr = new;
1707                }
1708            }))
1709    }
1710
1711    /// Computes the first element in the stream as an [`Optional`], which
1712    /// will be empty until the first element in the input arrives.
1713    ///
1714    /// This requires the stream to have a [`TotalOrder`] guarantee, otherwise
1715    /// re-ordering of elements may cause the first element to change.
1716    ///
1717    /// # Example
1718    /// ```rust
1719    /// # #[cfg(feature = "deploy")] {
1720    /// # use hydro_lang::prelude::*;
1721    /// # use futures::StreamExt;
1722    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1723    /// let tick = process.tick();
1724    /// let numbers = process.source_iter(q!(vec![1, 2, 3, 4]));
1725    /// let batch = numbers.batch(&tick, nondet!(/** test */));
1726    /// batch.first().all_ticks()
1727    /// # }, |mut stream| async move {
1728    /// // 1
1729    /// # assert_eq!(stream.next().await.unwrap(), 1);
1730    /// # }));
1731    /// # }
1732    /// ```
1733    pub fn first(self) -> Optional<T, L, B::AggregatedOptional>
1734    where
1735        O: IsOrdered,
1736    {
1737        self.make_totally_ordered()
1738            .assume_retries_trusted::<ExactlyOnce>(nondet!(/** first is idempotent */))
1739            .generator(q!(|| ()), q!(|_, item| Generate::Return(item)))
1740            .reduce(q!(|_, _| {}))
1741    }
1742
1743    /// Computes the last element in the stream as an [`Optional`], which
1744    /// will be empty until an element in the input arrives.
1745    ///
1746    /// This requires the stream to have a [`TotalOrder`] guarantee, otherwise
1747    /// re-ordering of elements may cause the last element to change.
1748    ///
1749    /// # Example
1750    /// ```rust
1751    /// # #[cfg(feature = "deploy")] {
1752    /// # use hydro_lang::prelude::*;
1753    /// # use futures::StreamExt;
1754    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1755    /// let tick = process.tick();
1756    /// let numbers = process.source_iter(q!(vec![1, 2, 3, 4]));
1757    /// let batch = numbers.batch(&tick, nondet!(/** test */));
1758    /// batch.last().all_ticks()
1759    /// # }, |mut stream| async move {
1760    /// // 4
1761    /// # assert_eq!(stream.next().await.unwrap(), 4);
1762    /// # }));
1763    /// # }
1764    /// ```
1765    pub fn last(self) -> Optional<T, L, B::AggregatedOptional>
1766    where
1767        O: IsOrdered,
1768    {
1769        self.make_totally_ordered()
1770            .assume_retries_trusted::<ExactlyOnce>(nondet!(/** last is idempotent */))
1771            .reduce(q!(|curr, new| *curr = new))
1772    }
1773
1774    /// Returns a stream containing at most the first `n` elements of the input stream,
1775    /// preserving the original order. Similar to `LIMIT` in SQL.
1776    ///
1777    /// This requires the stream to have a [`TotalOrder`] guarantee and [`ExactlyOnce`]
1778    /// retries, since the result depends on the order and cardinality of elements.
1779    ///
1780    /// # Example
1781    /// ```rust
1782    /// # #[cfg(feature = "deploy")] {
1783    /// # use hydro_lang::prelude::*;
1784    /// # use futures::StreamExt;
1785    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1786    /// let numbers = process.source_iter(q!(vec![10, 20, 30, 40, 50]));
1787    /// numbers.limit(q!(3))
1788    /// # }, |mut stream| async move {
1789    /// // 10, 20, 30
1790    /// # for w in vec![10, 20, 30] {
1791    /// #     assert_eq!(stream.next().await.unwrap(), w);
1792    /// # }
1793    /// # }));
1794    /// # }
1795    /// ```
1796    pub fn limit(
1797        self,
1798        n: impl QuotedWithContext<'a, usize, OperatorContext<L, B>> + Copy + 'a,
1799    ) -> Stream<T, L, B, TotalOrder, ExactlyOnce>
1800    where
1801        O: IsOrdered,
1802        R: IsExactlyOnce,
1803    {
1804        self.generator(
1805            q!(|| 0usize),
1806            q!(move |count, item| {
1807                if *count == n {
1808                    Generate::Break
1809                } else {
1810                    *count += 1;
1811                    if *count == n {
1812                        Generate::Return(item)
1813                    } else {
1814                        Generate::Yield(item)
1815                    }
1816                }
1817            }),
1818        )
1819    }
1820
1821    /// Collects all the elements of this stream into a single [`Vec`] element.
1822    ///
1823    /// If the input stream is [`Unbounded`], the output [`Singleton`] will be [`Unbounded`] as
1824    /// well, which means that the value of the [`Vec`] will asynchronously grow as new elements
1825    /// are added. On such a value, you can use [`Singleton::snapshot`] to grab an instance of
1826    /// the vector at an arbitrary point in time.
1827    ///
1828    /// # Example
1829    /// ```rust
1830    /// # #[cfg(feature = "deploy")] {
1831    /// # use hydro_lang::prelude::*;
1832    /// # use futures::StreamExt;
1833    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1834    /// let tick = process.tick();
1835    /// let numbers = process.source_iter(q!(vec![1, 2, 3, 4]));
1836    /// let batch = numbers.batch(&tick, nondet!(/** test */));
1837    /// batch.collect_vec().all_ticks() // emit each tick's Vec into an unbounded stream
1838    /// # }, |mut stream| async move {
1839    /// // [ vec![1, 2, 3, 4] ]
1840    /// # for w in vec![vec![1, 2, 3, 4]] {
1841    /// #     assert_eq!(stream.next().await.unwrap(), w);
1842    /// # }
1843    /// # }));
1844    /// # }
1845    /// ```
1846    pub fn collect_vec(self) -> Singleton<Vec<T>, L, B>
1847    where
1848        O: IsOrdered,
1849        R: IsExactlyOnce,
1850    {
1851        self.make_totally_ordered().make_exactly_once().fold(
1852            q!(|| vec![]),
1853            q!(|acc, v| {
1854                acc.push(v);
1855            }),
1856        )
1857    }
1858
1859    /// Applies a function to each element of the stream, maintaining an internal state (accumulator)
1860    /// and emitting each intermediate result.
1861    ///
1862    /// Unlike `fold` which only returns the final accumulated value, `scan` produces a new stream
1863    /// containing all intermediate accumulated values. The scan operation can also terminate early
1864    /// by returning `None`.
1865    ///
1866    /// The function takes a mutable reference to the accumulator and the current element, and returns
1867    /// an `Option<U>`. If the function returns `Some(value)`, `value` is emitted to the output stream.
1868    /// If the function returns `None`, the stream is terminated and no more elements are processed.
1869    ///
1870    /// The `init` and `f` closures may capture bounded singletons, optionals, or streams by
1871    /// reference via [`by_ref()`](crate::live_collections::Singleton::by_ref), as long as the
1872    /// referenced collection lives at the same location and has the same boundedness as this
1873    /// stream.
1874    ///
1875    /// # Examples
1876    ///
1877    /// Basic usage - running sum:
1878    /// ```rust
1879    /// # #[cfg(feature = "deploy")] {
1880    /// # use hydro_lang::prelude::*;
1881    /// # use futures::StreamExt;
1882    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1883    /// process.source_iter(q!(vec![1, 2, 3, 4])).scan(
1884    ///     q!(|| 0),
1885    ///     q!(|acc, x| {
1886    ///         *acc += x;
1887    ///         Some(*acc)
1888    ///     }),
1889    /// )
1890    /// # }, |mut stream| async move {
1891    /// // Output: 1, 3, 6, 10
1892    /// # for w in vec![1, 3, 6, 10] {
1893    /// #     assert_eq!(stream.next().await.unwrap(), w);
1894    /// # }
1895    /// # }));
1896    /// # }
1897    /// ```
1898    ///
1899    /// Early termination example:
1900    /// ```rust
1901    /// # #[cfg(feature = "deploy")] {
1902    /// # use hydro_lang::prelude::*;
1903    /// # use futures::StreamExt;
1904    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1905    /// process.source_iter(q!(vec![1, 2, 3, 4])).scan(
1906    ///     q!(|| 1),
1907    ///     q!(|state, x| {
1908    ///         *state = *state * x;
1909    ///         if *state > 6 {
1910    ///             None // Terminate the stream
1911    ///         } else {
1912    ///             Some(-*state)
1913    ///         }
1914    ///     }),
1915    /// )
1916    /// # }, |mut stream| async move {
1917    /// // Output: -1, -2, -6
1918    /// # for w in vec![-1, -2, -6] {
1919    /// #     assert_eq!(stream.next().await.unwrap(), w);
1920    /// # }
1921    /// # }));
1922    /// # }
1923    /// ```
1924    pub fn scan<A, U, I, F>(
1925        self,
1926        init: impl IntoQuotedMut<'a, I, OperatorContext<L, B>>,
1927        f: impl IntoQuotedMut<'a, F, OperatorContext<L, B>>,
1928    ) -> Stream<U, L, B, TotalOrder, ExactlyOnce>
1929    where
1930        O: IsOrdered,
1931        R: IsExactlyOnce,
1932        I: Fn() -> A + 'a,
1933        F: Fn(&mut A, T) -> Option<U> + 'a,
1934    {
1935        let init = crate::handoff_ref::with_ref_capture(|| {
1936            init.splice_fn0_ctx(&OperatorContext::<L, B>::new(&self.location))
1937                .into()
1938        });
1939        let f = crate::handoff_ref::with_ref_capture(|| {
1940            f.splice_fn2_borrow_mut_ctx(&OperatorContext::<L, B>::new(&self.location))
1941                .into()
1942        });
1943
1944        Stream::new(
1945            self.location.clone(),
1946            HydroNode::Scan {
1947                init,
1948                acc: f,
1949                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1950                metadata: self.location.new_node_metadata(
1951                    Stream::<U, L, B, TotalOrder, ExactlyOnce>::collection_kind(),
1952                ),
1953            },
1954        )
1955    }
1956
1957    /// Async version of [`Stream::scan`]. Applies an async function to each element of the
1958    /// stream, maintaining an internal state (accumulator) and emitting the values returned
1959    /// by the function.
1960    ///
1961    /// The closure runs synchronously (so it can mutate the accumulator), then returns a
1962    /// future. The future is polled to completion. If it resolves to `Some`, the value is
1963    /// emitted. If it resolves to `None`, the item is filtered out.
1964    ///
1965    /// The `init` and `f` closures may capture bounded singletons, optionals, or streams by
1966    /// reference via [`by_ref()`](crate::live_collections::Singleton::by_ref), as long as the
1967    /// referenced collection lives at the same location and has the same boundedness as this
1968    /// stream.
1969    ///
1970    /// # Examples
1971    ///
1972    /// ```rust
1973    /// # #[cfg(feature = "deploy")] {
1974    /// # use hydro_lang::prelude::*;
1975    /// # use futures::StreamExt;
1976    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1977    /// process
1978    ///     .source_iter(q!(vec![1, 2, 3, 4]))
1979    ///     .scan_async_blocking(
1980    ///         q!(|| 0),
1981    ///         q!(|acc, x| {
1982    ///             *acc += x;
1983    ///             let val = *acc;
1984    ///             async move { Some(val) }
1985    ///         }),
1986    ///     )
1987    /// # }, |mut stream| async move {
1988    /// // Output: 1, 3, 6, 10
1989    /// # for w in vec![1, 3, 6, 10] {
1990    /// #     assert_eq!(stream.next().await.unwrap(), w);
1991    /// # }
1992    /// # }));
1993    /// # }
1994    /// ```
1995    pub fn scan_async_blocking<A, U, I, F, Fut>(
1996        self,
1997        init: impl IntoQuotedMut<'a, I, OperatorContext<L, B>>,
1998        f: impl IntoQuotedMut<'a, F, OperatorContext<L, B>>,
1999    ) -> Stream<U, L, B, TotalOrder, ExactlyOnce>
2000    where
2001        O: IsOrdered,
2002        R: IsExactlyOnce,
2003        I: Fn() -> A + 'a,
2004        F: Fn(&mut A, T) -> Fut + 'a,
2005        Fut: Future<Output = Option<U>> + 'a,
2006    {
2007        let init = crate::handoff_ref::with_ref_capture(|| {
2008            init.splice_fn0_ctx(&OperatorContext::<L, B>::new(&self.location))
2009                .into()
2010        });
2011        let f = crate::handoff_ref::with_ref_capture(|| {
2012            f.splice_fn2_borrow_mut_ctx(&OperatorContext::<L, B>::new(&self.location))
2013                .into()
2014        });
2015
2016        Stream::new(
2017            self.location.clone(),
2018            HydroNode::ScanAsyncBlocking {
2019                init,
2020                acc: f,
2021                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2022                metadata: self.location.new_node_metadata(
2023                    Stream::<U, L, B, TotalOrder, ExactlyOnce>::collection_kind(),
2024                ),
2025            },
2026        )
2027    }
2028
2029    /// Iteratively processes the elements of the stream using a state machine that can yield
2030    /// elements as it processes its inputs. This is designed to mirror the unstable generator
2031    /// syntax in Rust, without requiring special syntax.
2032    ///
2033    /// Like [`Stream::scan`], this function takes in an initializer that emits the initial
2034    /// state. The second argument defines the processing logic, taking in a mutable reference
2035    /// to the state and the value to be processed. It emits a [`Generate`] value, whose
2036    /// variants define what is emitted and whether further inputs should be processed.
2037    ///
2038    /// The `init` and `f` closures may capture bounded singletons, optionals, or streams by
2039    /// reference via [`by_ref()`](crate::live_collections::Singleton::by_ref), as long as the
2040    /// referenced collection lives at the same location and has the same boundedness as this
2041    /// stream.
2042    ///
2043    /// # Example
2044    /// ```rust
2045    /// # #[cfg(feature = "deploy")] {
2046    /// # use hydro_lang::prelude::*;
2047    /// # use futures::StreamExt;
2048    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
2049    /// process.source_iter(q!(vec![1, 3, 100, 10])).generator(
2050    ///     q!(|| 0),
2051    ///     q!(|acc, x| {
2052    ///         *acc += x;
2053    ///         if *acc > 100 {
2054    ///             hydro_lang::live_collections::keyed_stream::Generate::Return("done!".to_owned())
2055    ///         } else if *acc % 2 == 0 {
2056    ///             hydro_lang::live_collections::keyed_stream::Generate::Yield("even".to_owned())
2057    ///         } else {
2058    ///             hydro_lang::live_collections::keyed_stream::Generate::Continue
2059    ///         }
2060    ///     }),
2061    /// )
2062    /// # }, |mut stream| async move {
2063    /// // Output: "even", "done!"
2064    /// # let mut results = Vec::new();
2065    /// # for _ in 0..2 {
2066    /// #     results.push(stream.next().await.unwrap());
2067    /// # }
2068    /// # results.sort();
2069    /// # assert_eq!(results, vec!["done!".to_owned(), "even".to_owned()]);
2070    /// # }));
2071    /// # }
2072    /// ```
2073    pub fn generator<A, U, I, F>(
2074        self,
2075        init: impl IntoQuotedMut<'a, I, OperatorContext<L, B>> + Copy,
2076        f: impl IntoQuotedMut<'a, F, OperatorContext<L, B>> + Copy,
2077    ) -> Stream<U, L, B, TotalOrder, ExactlyOnce>
2078    where
2079        O: IsOrdered,
2080        R: IsExactlyOnce,
2081        I: Fn() -> A + 'a,
2082        F: Fn(&mut A, T) -> Generate<U> + 'a,
2083    {
2084        let init: ManualExpr<I, _> =
2085            ManualExpr::new(move |ctx: &OperatorContext<L, B>| init.splice_fn0_ctx(ctx));
2086        let f: ManualExpr<F, _> =
2087            ManualExpr::new(move |ctx: &OperatorContext<L, B>| f.splice_fn2_borrow_mut_ctx(ctx));
2088
2089        let this = self.make_totally_ordered().make_exactly_once();
2090
2091        // State is Option<Option<A>>:
2092        //   None = not yet initialized
2093        //   Some(Some(a)) = active with state a
2094        //   Some(None) = terminated
2095        let scan_init = crate::handoff_ref::with_ref_capture(|| {
2096            q!(|| None)
2097                .splice_fn0_ctx::<Option<Option<A>>>(&this.location)
2098                .into()
2099        });
2100        let scan_f = crate::handoff_ref::with_ref_capture(|| {
2101            q!(move |state: &mut Option<Option<_>>, v| {
2102                if state.is_none() {
2103                    *state = Some(Some(init()));
2104                }
2105                match state {
2106                    Some(Some(state_value)) => match f(state_value, v) {
2107                        Generate::Yield(out) => Some(Some(out)),
2108                        Generate::Return(out) => {
2109                            *state = Some(None);
2110                            Some(Some(out))
2111                        }
2112                        // Unlike KeyedStream, we can terminate the scan directly on
2113                        // Break/Return because there is only one state (no other keys
2114                        // that still need processing).
2115                        Generate::Break => None,
2116                        Generate::Continue => Some(None),
2117                    },
2118                    // State is Some(None) after Return; terminate the scan.
2119                    _ => None,
2120                }
2121            })
2122            .splice_fn2_borrow_mut_ctx::<Option<Option<A>>, T, _>(&OperatorContext::<L, B>::new(
2123                &this.location,
2124            ))
2125            .into()
2126        });
2127
2128        let scan_node = HydroNode::Scan {
2129            init: scan_init,
2130            acc: scan_f,
2131            input: Box::new(this.ir_node.replace(HydroNode::Placeholder)),
2132            metadata: this.location.new_node_metadata(Stream::<
2133                Option<U>,
2134                L,
2135                B,
2136                TotalOrder,
2137                ExactlyOnce,
2138            >::collection_kind()),
2139        };
2140
2141        let flatten_f = q!(|d| d)
2142            .splice_fn1_ctx::<Option<U>, _>(&this.location)
2143            .into();
2144        let flatten_node = HydroNode::FlatMap {
2145            f: flatten_f,
2146            input: Box::new(scan_node),
2147            metadata: this
2148                .location
2149                .new_node_metadata(Stream::<U, L, B, TotalOrder, ExactlyOnce>::collection_kind()),
2150        };
2151
2152        Stream::new(this.location.clone(), flatten_node)
2153    }
2154
2155    /// Given a time interval, returns a stream corresponding to samples taken from the
2156    /// stream roughly at that interval. The output will have elements in the same order
2157    /// as the input, but with arbitrary elements skipped between samples. There is also
2158    /// no guarantee on the exact timing of the samples.
2159    ///
2160    /// # Non-Determinism
2161    /// The output stream is non-deterministic in which elements are sampled, since this
2162    /// is controlled by a clock.
2163    ///
2164    /// In simulation tests, the internal batching of elements and of clock samples can be
2165    /// scripted through the guard's composite hook payload, e.g.
2166    /// `nondet!(/** reason */ hook = (elements_hook.into(), None))`.
2167    #[cfg(feature = "tokio")]
2168    #[expect(
2169        clippy::type_complexity,
2170        reason = "composite hook payload names each internal operator's handle type"
2171    )]
2172    pub fn sample_every(
2173        self,
2174        interval: impl QuotedWithContext<'a, std::time::Duration, L> + Copy + 'a,
2175        mut nondet: NonDet<(
2176            Option<crate::sim_hooks::BatchHook<T, O, R, L::SimHookScope>>,
2177            Option<crate::sim_hooks::BatchHook<(), TotalOrder, AtLeastOnce, L::SimHookScope>>,
2178        )>,
2179    ) -> Stream<T, L::DropConsistency, Unbounded, O, AtLeastOnce>
2180    where
2181        L: TopLevel<'a>,
2182    {
2183        let samples = self.location.source_interval(interval);
2184        let (elements_hook, samples_hook) = nondet.take_hook();
2185
2186        let tick = self.location.tick();
2187        self.batch(
2188            &tick,
2189            nondet!(
2190                /// which elements are batched between samples is captured by the caller's guard
2191                hook = elements_hook
2192            ),
2193        )
2194        .filter_if(
2195            samples
2196                .batch(
2197                    &tick,
2198                    nondet!(
2199                        /// sample timing is captured by the caller's guard
2200                        hook = samples_hook
2201                    ),
2202                )
2203                .first()
2204                .is_some(),
2205        )
2206        .all_ticks()
2207        .weaken_retries()
2208    }
2209
2210    /// Given a timeout duration, returns an [`Optional`]  which will have a value if the
2211    /// stream has not emitted a value since that duration.
2212    ///
2213    /// # Non-Determinism
2214    /// Timeout relies on non-deterministic timer and arrival interleavings, so depending on
2215    /// when inputs and timer expirations are batched, timeouts may be non-deterministically
2216    /// generated or missed, and the notification of the timeout may be delayed as well. There
2217    /// is also no guarantee on how long the [`Optional`] will have a value after the timeout is
2218    /// detected, since it is cleared by the next batch containing an input.
2219    #[cfg(feature = "tokio")]
2220    pub fn timeout(
2221        self,
2222        duration: impl QuotedWithContext<
2223            'a,
2224            std::time::Duration,
2225            OperatorContext<L::DropConsistency, Unbounded>,
2226        > + Copy
2227        + 'a,
2228        nondet: NonDet,
2229    ) -> Optional<(), L::DropConsistency, Unbounded>
2230    where
2231        L: TopLevel<'a>,
2232        L::DropConsistency: TopLevel<'a>,
2233    {
2234        // Every batch of inputs starts a new countdown, tagged with a fresh epoch; a countdown
2235        // that expires before any newer input arrives (its epoch is still current) is a
2236        // timeout. Countdowns superseded by a newer input carry a stale epoch and are ignored.
2237        // The slice is driven by the (non-lazy) batches of inputs and of expired countdowns.
2238        let outer = self.location.drop_consistency();
2239        let (expired_complete, expired) =
2240            outer.forward_ref::<Stream<u64, L::DropConsistency, Unbounded, NoOrder, ExactlyOnce>>();
2241
2242        let inputs = self
2243            .assume_retries::<ExactlyOnce>(nondet!(
2244                /// only the presence of an input in a batch matters
2245                nondet
2246            ))
2247            .assume_ordering::<TotalOrder>(nondet!(
2248                /// only the presence of an input in a batch matters
2249                nondet
2250            ));
2251
2252        let (new_countdowns, timed_out) = sliced! {
2253            let inputs = use::batch(inputs, nondet!(
2254                /// arrival timing is captured by the caller's guard
2255                nondet
2256            ));
2257            let expired = use::batch(expired, nondet!(
2258                /// timer timing is captured by the caller's guard
2259                nondet
2260            ));
2261            // (current epoch, whether that epoch's countdown expired with no newer input)
2262            let mut state = use::state(|l| l.singleton(q!((0u64, false))));
2263
2264            let has_input = inputs.first().is_some();
2265            let current_expired = expired
2266                .cross_singleton(state.clone())
2267                .filter_map(q!(|(epoch, (current, _))| (epoch == current).then_some(())))
2268                .assume_ordering::<TotalOrder>(nondet!(/** only presence matters */))
2269                .first()
2270                .is_some();
2271
2272            let next_state = state.zip(has_input.clone()).zip(current_expired).map(q!(
2273                |(((epoch, timed_out), has_input), current_expired)| {
2274                    if has_input {
2275                        (epoch + 1, false)
2276                    } else {
2277                        (epoch, timed_out || current_expired)
2278                    }
2279                }
2280            ));
2281            state = next_state.clone();
2282
2283            (
2284                next_state
2285                    .clone()
2286                    .zip(has_input)
2287                    .filter_map(q!(|((epoch, _), has_input)| has_input.then_some(epoch)))
2288                    .into_stream(),
2289                next_state.filter_map(q!(|(_, timed_out)| timed_out.then_some(()))),
2290            )
2291        };
2292
2293        expired_complete.complete(
2294            new_countdowns
2295                // The countdowns feed back into the slice above; a top-level defer breaks the
2296                // dataflow cycle through the (otherwise immediate) futures.
2297                .defer_tick()
2298                .merge_unordered(outer.source_iter(q!([0u64])).weaken_boundedness())
2299                .map(q!(move |epoch| async move {
2300                    tokio::time::sleep(duration).await;
2301                    epoch
2302                }))
2303                .resolve_futures(),
2304        );
2305
2306        timed_out
2307    }
2308
2309    /// Shifts this stream into an atomic context, which guarantees that any downstream logic
2310    /// will all be executed synchronously before any outputs are yielded (in [`Stream::end_atomic`]).
2311    ///
2312    /// This is useful to enforce local consistency constraints, such as ensuring that a write is
2313    /// processed before an acknowledgement is emitted.
2314    pub fn atomic(self) -> Stream<T, Atomic<L>, B, O, R>
2315    where
2316        L: TopLevel<'a>,
2317    {
2318        let out_location = Atomic {
2319            tick: self.location.tick(),
2320        };
2321        Stream::new(
2322            out_location.clone(),
2323            HydroNode::BeginAtomic {
2324                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2325                metadata: out_location
2326                    .new_node_metadata(Stream::<T, Atomic<L>, B, O, R>::collection_kind()),
2327            },
2328        )
2329    }
2330
2331    /// Given a tick, returns a stream corresponding to a batch of elements segmented by
2332    /// that tick. These batches are guaranteed to be contiguous across ticks and preserve
2333    /// the order of the input. The output stream will execute in the [`Tick`] that was
2334    /// used to create the atomic section.
2335    ///
2336    /// # Non-Determinism
2337    /// The batch boundaries are non-deterministic and may change across executions.
2338    ///
2339    /// In simulation tests, the batching decisions can be scripted by attaching a
2340    /// [`BatchHook`](crate::sim_hooks::BatchHook) to the guard via
2341    /// `nondet!(/** reason */ hook = my_hook)`.
2342    pub fn batch<L2: Location<'a, DropConsistency = L::DropConsistency>>(
2343        self,
2344        tick: &Tick<L2>,
2345        mut nondet: NonDet<Option<crate::sim_hooks::BatchHook<T, O, R, L::SimHookScope>>>,
2346    ) -> Stream<T, Tick<L::DropConsistency>, Bounded, O, R> {
2347        assert_eq!(
2348            Location::id(tick.parent_location()),
2349            Location::id(&self.location)
2350        );
2351
2352        let mut metadata =
2353            tick.new_node_metadata(Stream::<T, Tick<L>, Bounded, O, R>::collection_kind());
2354        metadata.op.sim_hook_id = nondet.take_hook().map(|h| h.id);
2355        Stream::new(
2356            tick.drop_consistency(),
2357            HydroNode::Batch {
2358                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2359                metadata,
2360            },
2361        )
2362    }
2363
2364    /// An operator which allows you to "name" a `HydroNode`.
2365    /// This is only used for testing, to correlate certain `HydroNode`s with IDs.
2366    pub fn ir_node_named(self, name: &str) -> Stream<T, L, B, O, R> {
2367        {
2368            let mut node = self.ir_node.borrow_mut();
2369            let metadata = node.metadata_mut();
2370            metadata.tag = Some(name.to_owned());
2371        }
2372        self
2373    }
2374
2375    /// Turns this [`Stream`] into a [`Optional`], under the invariant assumption that there is at
2376    /// most one element. If this invariant is broken, the program may exhibit undefined behavior,
2377    /// so uses must be carefully vetted.
2378    pub(crate) fn cast_at_most_one_element(self) -> Optional<T, L, B>
2379    where
2380        B: IsBounded,
2381    {
2382        Optional::new(
2383            self.location.clone(),
2384            HydroNode::Cast {
2385                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2386                metadata: self
2387                    .location
2388                    .new_node_metadata(Optional::<T, L, B>::collection_kind()),
2389            },
2390        )
2391    }
2392
2393    pub(crate) fn use_ordering_type<O2: Ordering>(self) -> Stream<T, L, B, O2, R> {
2394        if O::ORDERING_KIND == O2::ORDERING_KIND {
2395            Stream::new(
2396                self.location.clone(),
2397                self.ir_node.replace(HydroNode::Placeholder),
2398            )
2399        } else {
2400            panic!(
2401                "Runtime ordering {:?} did not match requested cast {:?}.",
2402                O::ORDERING_KIND,
2403                O2::ORDERING_KIND
2404            )
2405        }
2406    }
2407
2408    /// Explicitly "casts" the stream to a type with a different ordering
2409    /// guarantee. Useful in unsafe code where the ordering cannot be proven
2410    /// by the type-system.
2411    ///
2412    /// # Non-Determinism
2413    /// This function is used as an escape hatch, and any mistakes in the
2414    /// provided ordering guarantee will propagate into the guarantees
2415    /// for the rest of the program.
2416    ///
2417    /// In simulation tests, the order chosen can be scripted by attaching an
2418    /// [`OrderingHook`](crate::sim_hooks::OrderingHook) to `nondet`.
2419    pub fn assume_ordering<O2: Ordering>(
2420        self,
2421        mut nondet: NonDet<Option<crate::sim_hooks::OrderingHook<T, B, R, L::SimHookScope>>>,
2422    ) -> Stream<T, L::DropConsistency, B, O2, R> {
2423        if O::ORDERING_KIND == O2::ORDERING_KIND {
2424            self.use_ordering_type().weaken_consistency()
2425        } else if O2::ORDERING_KIND == StreamOrder::NoOrder {
2426            // We can always weaken the ordering guarantee
2427            let target_location = self.location().drop_consistency();
2428            Stream::new(
2429                target_location.clone(),
2430                HydroNode::Cast {
2431                    inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2432                    metadata: target_location
2433                        .new_node_metadata(Stream::<T, L, B, O2, R>::collection_kind()),
2434                },
2435            )
2436        } else {
2437            let target_location = self.location().drop_consistency();
2438            let mut metadata =
2439                target_location.new_node_metadata(Stream::<T, L, B, O2, R>::collection_kind());
2440            metadata.op.sim_hook_id = nondet.take_hook().map(|hook| hook.id);
2441            Stream::new(
2442                target_location,
2443                HydroNode::ObserveNonDet {
2444                    inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2445                    trusted: false,
2446                    metadata,
2447                },
2448            )
2449        }
2450    }
2451
2452    // like `assume_ordering_trusted`, but only if the input stream is bounded and therefore
2453    // intermediate states will not be revealed
2454    fn assume_ordering_trusted_bounded<O2: Ordering>(
2455        self,
2456        nondet: NonDet,
2457    ) -> Stream<T, L, B, O2, R> {
2458        if B::BOUNDED {
2459            self.assume_ordering_trusted(nondet)
2460        } else {
2461            let self_location = self.location.clone();
2462            let inner: Stream<T, L::DropConsistency, B, O2, R> = self.assume_ordering(nondet!(
2463                /// the unbounded stream exposes ordering non-determinism in intermediate states
2464                nondet
2465            ));
2466            Stream::new(self_location, inner.ir_node.replace(HydroNode::Placeholder))
2467        }
2468    }
2469
2470    // only for internal APIs that have been carefully vetted to ensure that the non-determinism
2471    // is not observable
2472    pub(crate) fn assume_ordering_trusted<O2: Ordering>(
2473        self,
2474        _nondet: NonDet,
2475    ) -> Stream<T, L, B, O2, R> {
2476        if O::ORDERING_KIND == O2::ORDERING_KIND {
2477            self.use_ordering_type()
2478        } else if O2::ORDERING_KIND == StreamOrder::NoOrder {
2479            // We can always weaken the ordering guarantee
2480            Stream::new(
2481                self.location.clone(),
2482                HydroNode::Cast {
2483                    inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2484                    metadata: self
2485                        .location
2486                        .new_node_metadata(Stream::<T, L, B, O2, R>::collection_kind()),
2487                },
2488            )
2489        } else {
2490            Stream::new(
2491                self.location.clone(),
2492                HydroNode::ObserveNonDet {
2493                    inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2494                    trusted: true,
2495                    metadata: self
2496                        .location
2497                        .new_node_metadata(Stream::<T, L, B, O2, R>::collection_kind()),
2498                },
2499            )
2500        }
2501    }
2502
2503    #[deprecated = "use `weaken_ordering::<NoOrder>()` instead"]
2504    /// Weakens the ordering guarantee provided by the stream to [`NoOrder`],
2505    /// which is always safe because that is the weakest possible guarantee.
2506    pub fn weakest_ordering(self) -> Stream<T, L, B, NoOrder, R> {
2507        self.weaken_ordering::<NoOrder>()
2508    }
2509
2510    /// Weakens the ordering guarantee provided by the stream to `O2`, with the type-system
2511    /// enforcing that `O2` is weaker than the input ordering guarantee.
2512    pub fn weaken_ordering<O2: WeakerOrderingThan<O>>(self) -> Stream<T, L, B, O2, R> {
2513        let nondet = nondet!(/** this is a weaker ordering guarantee, so it is safe to assume */);
2514        self.assume_ordering_trusted::<O2>(nondet)
2515    }
2516
2517    /// Strengthens the ordering guarantee to `TotalOrder`, given that `O: IsOrdered`, which
2518    /// implies that `O == TotalOrder`.
2519    pub fn make_totally_ordered(self) -> Stream<T, L, B, TotalOrder, R>
2520    where
2521        O: IsOrdered,
2522    {
2523        self.assume_ordering_trusted(nondet!(/** no-op */))
2524    }
2525
2526    /// Explicitly "casts" the stream to a type with a different retries
2527    /// guarantee. Useful in unsafe code where the lack of retries cannot
2528    /// be proven by the type-system.
2529    ///
2530    /// # Non-Determinism
2531    /// This function is used as an escape hatch, and any mistakes in the
2532    /// provided retries guarantee will propagate into the guarantees
2533    /// for the rest of the program.
2534    ///
2535    /// In simulation tests, the retry decisions (how many times each element is
2536    /// observed) can be scripted by attaching a
2537    /// [`RetriesHook`](crate::sim_hooks::RetriesHook) to the guard via
2538    /// `nondet!(/** reason */ hook = my_hook)`.
2539    pub fn assume_retries<R2: Retries>(
2540        self,
2541        mut nondet: NonDet<Option<crate::sim_hooks::RetriesHook<T, O, B, L::SimHookScope>>>,
2542    ) -> Stream<T, L::DropConsistency, B, O, R2> {
2543        if R::RETRIES_KIND == R2::RETRIES_KIND {
2544            Stream::new(
2545                self.location.drop_consistency(),
2546                self.ir_node.replace(HydroNode::Placeholder),
2547            )
2548        } else if R2::RETRIES_KIND == StreamRetry::AtLeastOnce {
2549            // We can always weaken the retries guarantee
2550            let target_location = self.location.drop_consistency();
2551            Stream::new(
2552                target_location.clone(),
2553                HydroNode::Cast {
2554                    inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2555                    metadata: target_location
2556                        .new_node_metadata(Stream::<T, L, B, O, R2>::collection_kind()),
2557                },
2558            )
2559        } else {
2560            let target_location = self.location.drop_consistency();
2561            let mut metadata =
2562                target_location.new_node_metadata(Stream::<T, L, B, O, R2>::collection_kind());
2563            metadata.op.sim_hook_id = nondet.take_hook().map(|hook| hook.id);
2564            Stream::new(
2565                target_location.clone(),
2566                HydroNode::ObserveNonDet {
2567                    inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2568                    trusted: false,
2569                    metadata,
2570                },
2571            )
2572        }
2573    }
2574
2575    // only for internal APIs that have been carefully vetted to ensure that the non-determinism
2576    // is not observable
2577    fn assume_retries_trusted<R2: Retries>(self, _nondet: NonDet) -> Stream<T, L, B, O, R2> {
2578        if R::RETRIES_KIND == R2::RETRIES_KIND {
2579            Stream::new(
2580                self.location.clone(),
2581                self.ir_node.replace(HydroNode::Placeholder),
2582            )
2583        } else if R2::RETRIES_KIND == StreamRetry::AtLeastOnce {
2584            // We can always weaken the retries guarantee
2585            Stream::new(
2586                self.location.clone(),
2587                HydroNode::Cast {
2588                    inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2589                    metadata: self
2590                        .location
2591                        .new_node_metadata(Stream::<T, L, B, O, R2>::collection_kind()),
2592                },
2593            )
2594        } else {
2595            Stream::new(
2596                self.location.clone(),
2597                HydroNode::ObserveNonDet {
2598                    inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2599                    trusted: true,
2600                    metadata: self
2601                        .location
2602                        .new_node_metadata(Stream::<T, L, B, O, R2>::collection_kind()),
2603                },
2604            )
2605        }
2606    }
2607
2608    #[deprecated = "use `weaken_retries::<AtLeastOnce>()` instead"]
2609    /// Weakens the retries guarantee provided by the stream to [`AtLeastOnce`],
2610    /// which is always safe because that is the weakest possible guarantee.
2611    pub fn weakest_retries(self) -> Stream<T, L, B, O, AtLeastOnce> {
2612        self.weaken_retries::<AtLeastOnce>()
2613    }
2614
2615    /// Weakens the retries guarantee provided by the stream to `R2`, with the type-system
2616    /// enforcing that `R2` is weaker than the input retries guarantee.
2617    pub fn weaken_retries<R2: WeakerRetryThan<R>>(self) -> Stream<T, L, B, O, R2> {
2618        let nondet = nondet!(/** this is a weaker retry guarantee, so it is safe to assume */);
2619        self.assume_retries_trusted::<R2>(nondet)
2620    }
2621
2622    /// Strengthens the retry guarantee to `ExactlyOnce`, given that `R: IsExactlyOnce`, which
2623    /// implies that `R == ExactlyOnce`.
2624    pub fn make_exactly_once(self) -> Stream<T, L, B, O, ExactlyOnce>
2625    where
2626        R: IsExactlyOnce,
2627    {
2628        self.assume_retries_trusted(nondet!(/** no-op */))
2629    }
2630
2631    /// Strengthens the boundedness guarantee to `Bounded`, given that `B: IsBounded`, which
2632    /// implies that `B == Bounded`.
2633    pub fn make_bounded(self) -> Stream<T, L, Bounded, O, R>
2634    where
2635        B: IsBounded,
2636    {
2637        self.weaken_boundedness()
2638    }
2639
2640    /// Weakens the boundedness guarantee to an arbitrary boundedness `B2`, given that `B: IsBounded`,
2641    /// which implies that `B == Bounded`.
2642    pub fn weaken_boundedness<B2: Boundedness>(self) -> Stream<T, L, B2, O, R> {
2643        if B::BOUNDED == B2::BOUNDED {
2644            Stream::new(
2645                self.location.clone(),
2646                self.ir_node.replace(HydroNode::Placeholder),
2647            )
2648        } else {
2649            // We can always weaken the boundedness
2650            Stream::new(
2651                self.location.clone(),
2652                HydroNode::Cast {
2653                    inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2654                    metadata: self
2655                        .location
2656                        .new_node_metadata(Stream::<T, L, B2, O, R>::collection_kind()),
2657                },
2658            )
2659        }
2660    }
2661}
2662
2663impl<'a, T, L, B: Boundedness, O: Ordering, R: Retries> Stream<&T, L, B, O, R>
2664where
2665    L: Location<'a>,
2666{
2667    /// Clone each element of the stream; akin to `map(q!(|d| d.clone()))`.
2668    ///
2669    /// # Example
2670    /// ```rust
2671    /// # #[cfg(feature = "deploy")] {
2672    /// # use hydro_lang::prelude::*;
2673    /// # use futures::StreamExt;
2674    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
2675    /// process.source_iter(q!(&[1, 2, 3])).cloned()
2676    /// # }, |mut stream| async move {
2677    /// // 1, 2, 3
2678    /// # for w in vec![1, 2, 3] {
2679    /// #     assert_eq!(stream.next().await.unwrap(), w);
2680    /// # }
2681    /// # }));
2682    /// # }
2683    /// ```
2684    pub fn cloned(self) -> Stream<T, L, B, O, R>
2685    where
2686        T: Clone,
2687    {
2688        self.map(q!(|d| d.clone()))
2689    }
2690}
2691
2692impl<'a, T, L, B: Boundedness, O: Ordering> Stream<T, L, B, O, ExactlyOnce>
2693where
2694    L: Location<'a>,
2695{
2696    /// Computes the number of elements in the stream as a [`Singleton`].
2697    ///
2698    /// # Example
2699    /// ```rust
2700    /// # #[cfg(feature = "deploy")] {
2701    /// # use hydro_lang::prelude::*;
2702    /// # use futures::StreamExt;
2703    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
2704    /// let tick = process.tick();
2705    /// let numbers = process.source_iter(q!(vec![1, 2, 3, 4]));
2706    /// let batch = numbers.batch(&tick, nondet!(/** test */));
2707    /// batch.count().all_ticks()
2708    /// # }, |mut stream| async move {
2709    /// // 4
2710    /// # assert_eq!(stream.next().await.unwrap(), 4);
2711    /// # }));
2712    /// # }
2713    /// ```
2714    pub fn count(self) -> Singleton<usize, L, B::StreamToMonotone> {
2715        self.assume_ordering_trusted::<TotalOrder>(nondet!(
2716            /// Order does not affect eventual count, and also does not affect intermediate states.
2717        ))
2718        .fold(
2719            q!(|| 0usize),
2720            q!(
2721                |count, _| *count += 1,
2722                monotone = manual_proof!(/** += 1 is monotone */)
2723            ),
2724        )
2725    }
2726}
2727
2728impl<'a, T, L: Location<'a>, O: Ordering, R: Retries> Stream<T, L, Unbounded, O, R> {
2729    /// Produces a new stream that merges the elements of the two input streams.
2730    /// The result has [`NoOrder`] because the order of merging is not guaranteed.
2731    ///
2732    /// Currently, both input streams must be [`Unbounded`]. When the streams are
2733    /// [`Bounded`], you can use [`Stream::chain`] instead.
2734    ///
2735    /// # Example
2736    /// ```rust
2737    /// # #[cfg(feature = "deploy")] {
2738    /// # use hydro_lang::prelude::*;
2739    /// # use futures::StreamExt;
2740    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
2741    /// let numbers: Stream<i32, _, Unbounded> = // 1, 2, 3, 4
2742    /// # process.source_iter(q!(vec![1, 2, 3, 4])).into();
2743    /// numbers.clone().map(q!(|x| x + 1)).merge_unordered(numbers)
2744    /// # }, |mut stream| async move {
2745    /// // 2, 3, 4, 5, and 1, 2, 3, 4 merged in unknown order
2746    /// # for w in vec![2, 3, 4, 5, 1, 2, 3, 4] {
2747    /// #     assert_eq!(stream.next().await.unwrap(), w);
2748    /// # }
2749    /// # }));
2750    /// # }
2751    /// ```
2752    pub fn merge_unordered<O2: Ordering, R2: Retries>(
2753        self,
2754        other: Stream<T, L, Unbounded, O2, R2>,
2755    ) -> Stream<T, L, Unbounded, NoOrder, <R as MinRetries<R2>>::Min>
2756    where
2757        R: MinRetries<R2>,
2758    {
2759        Stream::new(
2760            self.location.clone(),
2761            HydroNode::Chain {
2762                first: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2763                second: Box::new(other.ir_node.replace(HydroNode::Placeholder)),
2764                metadata: self.location.new_node_metadata(Stream::<
2765                    T,
2766                    L,
2767                    Unbounded,
2768                    NoOrder,
2769                    <R as MinRetries<R2>>::Min,
2770                >::collection_kind()),
2771            },
2772        )
2773    }
2774
2775    /// Deprecated: use [`Stream::merge_unordered`] instead.
2776    #[deprecated(note = "use `merge_unordered` instead")]
2777    pub fn interleave<O2: Ordering, R2: Retries>(
2778        self,
2779        other: Stream<T, L, Unbounded, O2, R2>,
2780    ) -> Stream<T, L, Unbounded, NoOrder, <R as MinRetries<R2>>::Min>
2781    where
2782        R: MinRetries<R2>,
2783    {
2784        self.merge_unordered(other)
2785    }
2786}
2787
2788impl<'a, T, L: Location<'a>, B: Boundedness, R: Retries> Stream<T, L, B, TotalOrder, R> {
2789    /// Produces a new stream that combines the elements of the two input streams,
2790    /// preserving the relative order of elements within each input.
2791    ///
2792    /// # Non-Determinism
2793    /// The order in which elements *across* the two streams will be interleaved is
2794    /// non-deterministic, so the order of elements will vary across runs. If the output
2795    /// order is irrelevant, use [`Stream::merge_unordered`] instead, which is deterministic
2796    /// but emits an unordered stream. For deterministic first-then-second ordering on
2797    /// bounded streams, use [`Stream::chain`].
2798    ///
2799    /// In simulation tests, the interleaving decisions can be scripted by attaching a
2800    /// [`MergeOrderedHook`](crate::sim_hooks::MergeOrderedHook) to the guard via
2801    /// `nondet!(/** reason */ hook = my_hook)`.
2802    ///
2803    /// # Example
2804    /// ```rust
2805    /// # #[cfg(feature = "deploy")] {
2806    /// # use hydro_lang::prelude::*;
2807    /// # use futures::StreamExt;
2808    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
2809    /// let numbers: Stream<i32, _, Unbounded> = // 1, 3
2810    /// # process.source_iter(q!(vec![1, 3])).into();
2811    /// numbers.clone().merge_ordered(numbers.map(q!(|x| x + 1)), nondet!(/** example */))
2812    /// # }, |mut stream| async move {
2813    /// // 1, 3 and 2, 4 in some order, preserving the original local order
2814    /// # for w in vec![1, 3, 2, 4] {
2815    /// #     assert_eq!(stream.next().await.unwrap(), w);
2816    /// # }
2817    /// # }));
2818    /// # }
2819    /// ```
2820    pub fn merge_ordered<R2: Retries>(
2821        self,
2822        other: Stream<T, L, B, TotalOrder, R2>,
2823        mut nondet: NonDet<Option<crate::sim_hooks::MergeOrderedHook<T, B, L::SimHookScope>>>,
2824    ) -> Stream<T, L::DropConsistency, B, TotalOrder, <R as MinRetries<R2>>::Min>
2825    where
2826        R: MinRetries<R2>,
2827    {
2828        let target_location = self.location().drop_consistency();
2829        let mut metadata = target_location.new_node_metadata(Stream::<
2830            T,
2831            L::DropConsistency,
2832            B,
2833            TotalOrder,
2834            <R as MinRetries<R2>>::Min,
2835        >::collection_kind());
2836        metadata.op.sim_hook_id = nondet.take_hook().map(|hook| hook.id);
2837        Stream::new(
2838            target_location,
2839            HydroNode::MergeOrdered {
2840                first: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2841                second: Box::new(other.ir_node.replace(HydroNode::Placeholder)),
2842                metadata,
2843            },
2844        )
2845    }
2846}
2847
2848impl<'a, T, L, B: Boundedness, O: Ordering, R: Retries> Stream<T, L, B, O, R>
2849where
2850    L: Location<'a>,
2851{
2852    /// Produces a new stream that emits the input elements in sorted order.
2853    ///
2854    /// The input stream can have any ordering guarantee, but the output stream
2855    /// will have a [`TotalOrder`] guarantee. This operator will block until all
2856    /// elements in the input stream are available, so it requires the input stream
2857    /// to be [`Bounded`].
2858    ///
2859    /// # Example
2860    /// ```rust
2861    /// # #[cfg(feature = "deploy")] {
2862    /// # use hydro_lang::prelude::*;
2863    /// # use futures::StreamExt;
2864    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
2865    /// let tick = process.tick();
2866    /// let numbers = process.source_iter(q!(vec![4, 2, 3, 1]));
2867    /// let batch = numbers.batch(&tick, nondet!(/** test */));
2868    /// batch.sort().all_ticks()
2869    /// # }, |mut stream| async move {
2870    /// // 1, 2, 3, 4
2871    /// # for w in (1..5) {
2872    /// #     assert_eq!(stream.next().await.unwrap(), w);
2873    /// # }
2874    /// # }));
2875    /// # }
2876    /// ```
2877    pub fn sort(self) -> Stream<T, L, Bounded, TotalOrder, R>
2878    where
2879        B: IsBounded,
2880        T: Ord,
2881    {
2882        let this = self.make_bounded();
2883        Stream::new(
2884            this.location.clone(),
2885            HydroNode::Sort {
2886                input: Box::new(this.ir_node.replace(HydroNode::Placeholder)),
2887                metadata: this
2888                    .location
2889                    .new_node_metadata(Stream::<T, L, Bounded, TotalOrder, R>::collection_kind()),
2890            },
2891        )
2892    }
2893
2894    /// Produces a new stream that first emits the elements of the `self` stream,
2895    /// and then emits the elements of the `other` stream. The output stream has
2896    /// a [`TotalOrder`] guarantee if and only if both input streams have a
2897    /// [`TotalOrder`] guarantee.
2898    ///
2899    /// Currently, both input streams must be [`Bounded`]. This operator will block
2900    /// on the first stream until all its elements are available. In a future version,
2901    /// we will relax the requirement on the `other` stream.
2902    ///
2903    /// # Example
2904    /// ```rust
2905    /// # #[cfg(feature = "deploy")] {
2906    /// # use hydro_lang::prelude::*;
2907    /// # use futures::StreamExt;
2908    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
2909    /// let tick = process.tick();
2910    /// let numbers = process.source_iter(q!(vec![1, 2, 3, 4]));
2911    /// let batch = numbers.batch(&tick, nondet!(/** test */));
2912    /// batch.clone().map(q!(|x| x + 1)).chain(batch).all_ticks()
2913    /// # }, |mut stream| async move {
2914    /// // 2, 3, 4, 5, 1, 2, 3, 4
2915    /// # for w in vec![2, 3, 4, 5, 1, 2, 3, 4] {
2916    /// #     assert_eq!(stream.next().await.unwrap(), w);
2917    /// # }
2918    /// # }));
2919    /// # }
2920    /// ```
2921    pub fn chain<O2: Ordering, R2: Retries, B2: Boundedness>(
2922        self,
2923        other: Stream<T, L, B2, O2, R2>,
2924    ) -> Stream<T, L, B2, <O as MinOrder<O2>>::Min, <R as MinRetries<R2>>::Min>
2925    where
2926        B: IsBounded,
2927        O: MinOrder<O2>,
2928        R: MinRetries<R2>,
2929    {
2930        check_matching_location(&self.location, &other.location);
2931
2932        Stream::new(
2933            self.location.clone(),
2934            HydroNode::Chain {
2935                first: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2936                second: Box::new(other.ir_node.replace(HydroNode::Placeholder)),
2937                metadata: self.location.new_node_metadata(Stream::<
2938                    T,
2939                    L,
2940                    B2,
2941                    <O as MinOrder<O2>>::Min,
2942                    <R as MinRetries<R2>>::Min,
2943                >::collection_kind()),
2944            },
2945        )
2946    }
2947
2948    /// Forms the cross-product (Cartesian product, cross-join) of the items in the 2 input streams.
2949    /// Unlike [`Stream::cross_product`], the output order is totally ordered when the inputs are
2950    /// because this is compiled into a nested loop.
2951    pub fn cross_product_nested_loop<T2, O2: Ordering + MinOrder<O>, R2: Retries>(
2952        self,
2953        other: Stream<T2, L, Bounded, O2, R2>,
2954    ) -> Stream<(T, T2), L, Bounded, <O2 as MinOrder<O>>::Min, <R as MinRetries<R2>>::Min>
2955    where
2956        B: IsBounded,
2957        T: Clone,
2958        T2: Clone,
2959        R: MinRetries<R2>,
2960    {
2961        let this = self.make_bounded();
2962        check_matching_location(&this.location, &other.location);
2963
2964        Stream::new(
2965            this.location.clone(),
2966            HydroNode::CrossProduct {
2967                left: Box::new(this.ir_node.replace(HydroNode::Placeholder)),
2968                right: Box::new(other.ir_node.replace(HydroNode::Placeholder)),
2969                metadata: this.location.new_node_metadata(Stream::<
2970                    (T, T2),
2971                    L,
2972                    Bounded,
2973                    <O2 as MinOrder<O>>::Min,
2974                    <R as MinRetries<R2>>::Min,
2975                >::collection_kind()),
2976            },
2977        )
2978    }
2979
2980    /// Creates a [`KeyedStream`] with the same set of keys as `keys`, but with the elements in
2981    /// `self` used as the values for *each* key.
2982    ///
2983    /// This is helpful when "broadcasting" a set of values so that all the keys have the same
2984    /// values. For example, it can be used to send the same set of elements to several cluster
2985    /// members, if the membership information is available as a [`KeyedSingleton`].
2986    ///
2987    /// # Example
2988    /// ```rust
2989    /// # #[cfg(feature = "deploy")] {
2990    /// # use hydro_lang::prelude::*;
2991    /// # use futures::StreamExt;
2992    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
2993    /// # let tick = process.tick();
2994    /// let keyed_singleton = // { 1: (), 2: () }
2995    /// # process
2996    /// #     .source_iter(q!(vec![(1, ()), (2, ())]))
2997    /// #     .into_keyed()
2998    /// #     .batch(&tick, nondet!(/** test */))
2999    /// #     .first();
3000    /// let stream = // [ "a", "b" ]
3001    /// # process
3002    /// #     .source_iter(q!(vec!["a".to_owned(), "b".to_owned()]))
3003    /// #     .batch(&tick, nondet!(/** test */));
3004    /// stream.repeat_with_keys(keyed_singleton)
3005    /// # .entries().all_ticks()
3006    /// # }, |mut stream| async move {
3007    /// // { 1: ["a", "b" ], 2: ["a", "b"] }
3008    /// # let mut results = Vec::new();
3009    /// # for _ in 0..4 {
3010    /// #     results.push(stream.next().await.unwrap());
3011    /// # }
3012    /// # results.sort();
3013    /// # assert_eq!(results, vec![(1, "a".to_owned()), (1, "b".to_owned()), (2, "a".to_owned()), (2, "b".to_owned())]);
3014    /// # }));
3015    /// # }
3016    /// ```
3017    pub fn repeat_with_keys<K, V2>(
3018        self,
3019        keys: KeyedSingleton<K, V2, L, Bounded>,
3020    ) -> KeyedStream<K, T, L, Bounded, O, R>
3021    where
3022        B: IsBounded,
3023        K: Clone,
3024        T: Clone,
3025    {
3026        keys.keys()
3027            .assume_ordering_trusted::<TotalOrder>(
3028                nondet!(/** keyed stream does not depend on ordering of keys */),
3029            )
3030            .cross_product_nested_loop(self.make_bounded())
3031            .into_keyed()
3032    }
3033
3034    /// Consumes a stream of `Future<T>`, resolving each future while blocking subgraph
3035    /// execution until all results are available. The output order is based on when futures
3036    /// complete, and may be different than the input order.
3037    ///
3038    /// Unlike [`Stream::resolve_futures`], which allows the subgraph to continue executing
3039    /// while futures are pending, this variant blocks until the futures resolve.
3040    ///
3041    /// # Example
3042    /// ```rust
3043    /// # #[cfg(feature = "deploy")] {
3044    /// # use std::collections::HashSet;
3045    /// # use futures::StreamExt;
3046    /// # use hydro_lang::prelude::*;
3047    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
3048    /// process
3049    ///     .source_iter(q!([2, 3, 1, 9, 6, 5, 4, 7, 8]))
3050    ///     .map(q!(|x| async move {
3051    ///         tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
3052    ///         x
3053    ///     }))
3054    ///     .resolve_futures_blocking()
3055    /// #   },
3056    /// #   |mut stream| async move {
3057    /// // 1, 2, 3, 4, 5, 6, 7, 8, 9 (in any order)
3058    /// #       let mut output = HashSet::new();
3059    /// #       for _ in 1..10 {
3060    /// #           output.insert(stream.next().await.unwrap());
3061    /// #       }
3062    /// #       assert_eq!(
3063    /// #           output,
3064    /// #           HashSet::<i32>::from_iter(1..10)
3065    /// #       );
3066    /// #   },
3067    /// # ));
3068    /// # }
3069    /// ```
3070    pub fn resolve_futures_blocking(self) -> Stream<T::Output, L, B, NoOrder, R>
3071    where
3072        T: Future,
3073    {
3074        Stream::new(
3075            self.location.clone(),
3076            HydroNode::ResolveFuturesBlocking {
3077                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
3078                metadata: self
3079                    .location
3080                    .new_node_metadata(Stream::<T::Output, L, B, NoOrder, R>::collection_kind()),
3081            },
3082        )
3083    }
3084
3085    /// Returns a [`Singleton`] containing `true` if the stream has no elements, or `false` otherwise.
3086    ///
3087    /// # Example
3088    /// ```rust
3089    /// # #[cfg(feature = "deploy")] {
3090    /// # use hydro_lang::prelude::*;
3091    /// # use futures::StreamExt;
3092    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
3093    /// let tick = process.tick();
3094    /// let empty: Stream<i32, _, Bounded> = process
3095    ///   .source_iter(q!(Vec::<i32>::new()))
3096    ///   .batch(&tick, nondet!(/** test */));
3097    /// empty.is_empty().all_ticks()
3098    /// # }, |mut stream| async move {
3099    /// // true
3100    /// # assert_eq!(stream.next().await.unwrap(), true);
3101    /// # }));
3102    /// # }
3103    /// ```
3104    #[expect(clippy::wrong_self_convention, reason = "stream function naming")]
3105    pub fn is_empty(self) -> Singleton<bool, L, Bounded>
3106    where
3107        B: IsBounded,
3108    {
3109        self.make_bounded()
3110            .assume_ordering_trusted::<TotalOrder>(
3111                nondet!(/** is_empty intermediates unaffected by order */),
3112            )
3113            .first()
3114            .is_none()
3115    }
3116}
3117
3118impl<'a, K, V1, L, B: Boundedness, O: Ordering, R: Retries> Stream<(K, V1), L, B, O, R>
3119where
3120    L: Location<'a>,
3121{
3122    /// Given two streams of pairs `(K, V1)` and `(K, V2)`, produces a new stream of nested pairs `(K, (V1, V2))`
3123    /// by equi-joining the two streams on the key attribute `K`.
3124    ///
3125    /// When the right-hand side is [`Bounded`], the join accumulates the right side first
3126    /// and streams the left side through, preserving the left side's ordering. When both
3127    /// sides are [`Unbounded`], a symmetric hash join is used and ordering is [`NoOrder`].
3128    ///
3129    /// # Example
3130    /// ```rust
3131    /// # #[cfg(feature = "deploy")] {
3132    /// # use hydro_lang::prelude::*;
3133    /// # use std::collections::HashSet;
3134    /// # use futures::StreamExt;
3135    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
3136    /// let tick = process.tick();
3137    /// let stream1 = process.source_iter(q!(vec![(1, 'a'), (2, 'b')]));
3138    /// let stream2 = process.source_iter(q!(vec![(1, 'x'), (2, 'y')]));
3139    /// stream1.join(stream2)
3140    /// # }, |mut stream| async move {
3141    /// // (1, ('a', 'x')), (2, ('b', 'y'))
3142    /// # let expected = HashSet::from([(1, ('a', 'x')), (2, ('b', 'y'))]);
3143    /// # stream.map(|i| assert!(expected.contains(&i)));
3144    /// # }));
3145    /// # }
3146    pub fn join<V2, B2: Boundedness, O2: Ordering, R2: Retries>(
3147        self,
3148        n: Stream<(K, V2), L, B2, O2, R2>,
3149    ) -> Stream<(K, (V1, V2)), L, B, B2::PreserveOrderIfBounded<O>, <R as MinRetries<R2>>::Min>
3150    where
3151        K: Eq + Hash + Clone,
3152        R: MinRetries<R2>,
3153        V1: Clone,
3154        V2: Clone,
3155    {
3156        check_matching_location(&self.location, &n.location);
3157
3158        let ir_node = if B2::BOUNDED {
3159            HydroNode::JoinHalf {
3160                left: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
3161                right: Box::new(n.ir_node.replace(HydroNode::Placeholder)),
3162                metadata: self.location.new_node_metadata(Stream::<
3163                    (K, (V1, V2)),
3164                    L,
3165                    B,
3166                    B2::PreserveOrderIfBounded<O>,
3167                    <R as MinRetries<R2>>::Min,
3168                >::collection_kind()),
3169            }
3170        } else {
3171            HydroNode::Join {
3172                left: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
3173                right: Box::new(n.ir_node.replace(HydroNode::Placeholder)),
3174                metadata: self.location.new_node_metadata(Stream::<
3175                    (K, (V1, V2)),
3176                    L,
3177                    B,
3178                    B2::PreserveOrderIfBounded<O>,
3179                    <R as MinRetries<R2>>::Min,
3180                >::collection_kind()),
3181            }
3182        };
3183
3184        Stream::new(self.location.clone(), ir_node)
3185    }
3186
3187    /// Given a stream of pairs `(K, V1)` and a bounded stream of keys `K`,
3188    /// computes the anti-join of the items in the input -- i.e. returns
3189    /// unique items in the first input that do not have a matching key
3190    /// in the second input.
3191    ///
3192    /// # Example
3193    /// ```rust
3194    /// # #[cfg(feature = "deploy")] {
3195    /// # use hydro_lang::prelude::*;
3196    /// # use futures::StreamExt;
3197    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
3198    /// let tick = process.tick();
3199    /// let stream = process
3200    ///   .source_iter(q!(vec![ (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd') ]))
3201    ///   .batch(&tick, nondet!(/** test */));
3202    /// let batch = process
3203    ///   .source_iter(q!(vec![1, 2]))
3204    ///   .batch(&tick, nondet!(/** test */));
3205    /// stream.anti_join(batch).all_ticks()
3206    /// # }, |mut stream| async move {
3207    /// # for w in vec![(3, 'c'), (4, 'd')] {
3208    /// #     assert_eq!(stream.next().await.unwrap(), w);
3209    /// # }
3210    /// # }));
3211    /// # }
3212    pub fn anti_join<O2: Ordering, R2: Retries>(
3213        self,
3214        n: Stream<K, L, Bounded, O2, R2>,
3215    ) -> Stream<(K, V1), L, B, O, R>
3216    where
3217        K: Eq + Hash,
3218    {
3219        check_matching_location(&self.location, &n.location);
3220
3221        Stream::new(
3222            self.location.clone(),
3223            HydroNode::AntiJoin {
3224                pos: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
3225                neg: Box::new(n.ir_node.replace(HydroNode::Placeholder)),
3226                metadata: self
3227                    .location
3228                    .new_node_metadata(Stream::<(K, V1), L, B, O, R>::collection_kind()),
3229            },
3230        )
3231    }
3232}
3233
3234impl<'a, K, V, L: Location<'a>, B: Boundedness, O: Ordering, R: Retries>
3235    Stream<(K, V), L, B, O, R>
3236{
3237    /// Transforms this stream into a [`KeyedStream`], where the first element of each tuple
3238    /// is used as the key and the second element is added to the entries associated with that key.
3239    ///
3240    /// Because [`KeyedStream`] lazily groups values into buckets, this operator has zero computational
3241    /// cost and _does not_ require that the key type is hashable. Keyed streams are useful for
3242    /// performing grouped aggregations, but also for more precise ordering guarantees such as
3243    /// total ordering _within_ each group but no ordering _across_ groups.
3244    ///
3245    /// # Example
3246    /// ```rust
3247    /// # #[cfg(feature = "deploy")] {
3248    /// # use hydro_lang::prelude::*;
3249    /// # use futures::StreamExt;
3250    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
3251    /// process
3252    ///     .source_iter(q!(vec![(1, 2), (1, 3), (2, 4)]))
3253    ///     .into_keyed()
3254    /// #   .entries()
3255    /// # }, |mut stream| async move {
3256    /// // { 1: [2, 3], 2: [4] }
3257    /// # for w in vec![(1, 2), (1, 3), (2, 4)] {
3258    /// #     assert_eq!(stream.next().await.unwrap(), w);
3259    /// # }
3260    /// # }));
3261    /// # }
3262    /// ```
3263    pub fn into_keyed(self) -> KeyedStream<K, V, L, B, O, R> {
3264        KeyedStream::new(
3265            self.location.clone(),
3266            HydroNode::Cast {
3267                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
3268                metadata: self
3269                    .location
3270                    .new_node_metadata(KeyedStream::<K, V, L, B, O, R>::collection_kind()),
3271            },
3272        )
3273    }
3274}
3275
3276impl<'a, K, V, L, O: Ordering, R: Retries> Stream<(K, V), Tick<L>, Bounded, O, R>
3277where
3278    K: Eq + Hash,
3279    L: Location<'a>,
3280{
3281    /// Given a stream of pairs `(K, V)`, produces a new stream of unique keys `K`.
3282    /// # Example
3283    /// ```rust
3284    /// # #[cfg(feature = "deploy")] {
3285    /// # use hydro_lang::prelude::*;
3286    /// # use futures::StreamExt;
3287    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
3288    /// let tick = process.tick();
3289    /// let numbers = process.source_iter(q!(vec![(1, 2), (2, 3), (1, 3), (2, 4)]));
3290    /// let batch = numbers.batch(&tick, nondet!(/** test */));
3291    /// batch.keys().all_ticks()
3292    /// # }, |mut stream| async move {
3293    /// // 1, 2
3294    /// # assert_eq!(stream.next().await.unwrap(), 1);
3295    /// # assert_eq!(stream.next().await.unwrap(), 2);
3296    /// # }));
3297    /// # }
3298    /// ```
3299    pub fn keys(self) -> Stream<K, Tick<L>, Bounded, NoOrder, ExactlyOnce> {
3300        self.into_keyed()
3301            .fold(
3302                q!(|| ()),
3303                q!(
3304                    |_, _| {},
3305                    commutative = manual_proof!(/** values are ignored */),
3306                    idempotent = manual_proof!(/** values are ignored */)
3307                ),
3308            )
3309            .keys()
3310    }
3311}
3312
3313impl<'a, T, L, B: Boundedness, O: Ordering, R: Retries> Stream<T, Atomic<L>, B, O, R>
3314where
3315    L: Location<'a>,
3316{
3317    /// Returns a stream corresponding to the latest batch of elements being atomically
3318    /// processed. These batches are guaranteed to be contiguous across ticks and preserve
3319    /// the order of the input.
3320    ///
3321    /// # Non-Determinism
3322    /// The batch boundaries are non-deterministic and may change across executions.
3323    pub fn batch_atomic<L2: Location<'a, DropConsistency = L::DropConsistency>>(
3324        self,
3325        tick: &Tick<L2>,
3326        mut nondet: NonDet<Option<crate::sim_hooks::BatchHook<T, O, R, L::SimHookScope>>>,
3327    ) -> Stream<T, Tick<L::DropConsistency>, Bounded, O, R> {
3328        assert_eq!(
3329            Location::id(tick.parent_location()),
3330            Location::id(self.location.tick.parent_location())
3331        );
3332
3333        let mut metadata =
3334            tick.new_node_metadata(Stream::<T, Tick<L>, Bounded, O, R>::collection_kind());
3335
3336        metadata.op.sim_hook_id = nondet.take_hook().map(|h| h.id);
3337        Stream::new(
3338            tick.drop_consistency(),
3339            HydroNode::Batch {
3340                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
3341                metadata,
3342            },
3343        )
3344    }
3345
3346    /// Yields the elements of this stream back into a top-level, asynchronous execution context.
3347    /// See [`Stream::atomic`] for more details.
3348    pub fn end_atomic(self) -> Stream<T, L, B, O, R> {
3349        Stream::new(
3350            self.location.tick.l.clone(),
3351            HydroNode::EndAtomic {
3352                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
3353                metadata: self
3354                    .location
3355                    .tick
3356                    .l
3357                    .new_node_metadata(Stream::<T, L, B, O, R>::collection_kind()),
3358            },
3359        )
3360    }
3361}
3362
3363impl<'a, F, T, L, B: Boundedness, O: Ordering, R: Retries> Stream<F, L, B, O, R>
3364where
3365    L: TopLevel<'a>,
3366    F: Future<Output = T>,
3367{
3368    /// Consumes a stream of `Future<T>`, produces a new stream of the resulting `T` outputs.
3369    /// Future outputs are produced as available, regardless of input arrival order.
3370    ///
3371    /// # Example
3372    /// ```rust
3373    /// # #[cfg(feature = "deploy")] {
3374    /// # use std::collections::HashSet;
3375    /// # use futures::StreamExt;
3376    /// # use hydro_lang::prelude::*;
3377    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
3378    /// process.source_iter(q!([2, 3, 1, 9, 6, 5, 4, 7, 8]))
3379    ///     .map(q!(|x| async move {
3380    ///         tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
3381    ///         x
3382    ///     }))
3383    ///     .resolve_futures()
3384    /// #   },
3385    /// #   |mut stream| async move {
3386    /// // 1, 2, 3, 4, 5, 6, 7, 8, 9 (in any order)
3387    /// #       let mut output = HashSet::new();
3388    /// #       for _ in 1..10 {
3389    /// #           output.insert(stream.next().await.unwrap());
3390    /// #       }
3391    /// #       assert_eq!(
3392    /// #           output,
3393    /// #           HashSet::<i32>::from_iter(1..10)
3394    /// #       );
3395    /// #   },
3396    /// # ));
3397    /// # }
3398    pub fn resolve_futures(self) -> Stream<T, L, Unbounded, NoOrder, R> {
3399        Stream::new(
3400            self.location.clone(),
3401            HydroNode::ResolveFutures {
3402                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
3403                metadata: self
3404                    .location
3405                    .new_node_metadata(Stream::<T, L, Unbounded, NoOrder, R>::collection_kind()),
3406            },
3407        )
3408    }
3409
3410    /// Consumes a stream of `Future<T>`, produces a new stream of the resulting `T` outputs.
3411    /// Future outputs are produced in the same order as the input stream.
3412    ///
3413    /// # Example
3414    /// ```rust
3415    /// # #[cfg(feature = "deploy")] {
3416    /// # use std::collections::HashSet;
3417    /// # use futures::StreamExt;
3418    /// # use hydro_lang::prelude::*;
3419    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
3420    /// process.source_iter(q!([2, 3, 1, 9, 6, 5, 4, 7, 8]))
3421    ///     .map(q!(|x| async move {
3422    ///         tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
3423    ///         x
3424    ///     }))
3425    ///     .resolve_futures_ordered()
3426    /// #   },
3427    /// #   |mut stream| async move {
3428    /// // 2, 3, 1, 9, 6, 5, 4, 7, 8
3429    /// #       let mut output = Vec::new();
3430    /// #       for _ in 1..10 {
3431    /// #           output.push(stream.next().await.unwrap());
3432    /// #       }
3433    /// #       assert_eq!(
3434    /// #           output,
3435    /// #           vec![2, 3, 1, 9, 6, 5, 4, 7, 8]
3436    /// #       );
3437    /// #   },
3438    /// # ));
3439    /// # }
3440    pub fn resolve_futures_ordered(self) -> Stream<T, L, Unbounded, O, R> {
3441        Stream::new(
3442            self.location.clone(),
3443            HydroNode::ResolveFuturesOrdered {
3444                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
3445                metadata: self
3446                    .location
3447                    .new_node_metadata(Stream::<T, L, Unbounded, O, R>::collection_kind()),
3448            },
3449        )
3450    }
3451}
3452
3453impl<'a, T, L, O: Ordering, R: Retries> Stream<T, Tick<L>, Bounded, O, R>
3454where
3455    L: Location<'a>,
3456{
3457    /// Asynchronously yields this batch of elements outside the tick as an unbounded stream,
3458    /// which will stream all the elements across _all_ tick iterations by concatenating the batches.
3459    pub fn all_ticks(self) -> Stream<T, L, Unbounded, O, R> {
3460        Stream::new(
3461            self.location.parent_location().clone(),
3462            HydroNode::YieldConcat {
3463                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
3464                metadata: self.location.parent_location().new_node_metadata(Stream::<
3465                    T,
3466                    L,
3467                    Unbounded,
3468                    O,
3469                    R,
3470                >::collection_kind(
3471                )),
3472            },
3473        )
3474    }
3475
3476    /// Synchronously yields this batch of elements outside the tick as an unbounded stream,
3477    /// which will stream all the elements across _all_ tick iterations by concatenating the batches.
3478    ///
3479    /// Unlike [`Stream::all_ticks`], this preserves synchronous execution, as the output stream
3480    /// is emitted in an [`Atomic`] context that will process elements synchronously with the input
3481    /// stream's [`Tick`] context.
3482    pub fn all_ticks_atomic(self) -> Stream<T, Atomic<L>, Unbounded, O, R> {
3483        let out_location = Atomic {
3484            tick: self.location.clone(),
3485        };
3486
3487        Stream::new(
3488            out_location.clone(),
3489            HydroNode::YieldConcat {
3490                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
3491                metadata: out_location
3492                    .new_node_metadata(Stream::<T, Atomic<L>, Unbounded, O, R>::collection_kind()),
3493            },
3494        )
3495    }
3496
3497    /// Transforms the stream using the given closure in "stateful" mode, where stateful operators
3498    /// such as `fold` retrain their memory across ticks rather than resetting across batches of
3499    /// input.
3500    ///
3501    /// This API is particularly useful for stateful computation on batches of data, such as
3502    /// maintaining an accumulated state that is up to date with the current batch.
3503    ///
3504    /// # Example
3505    /// ```rust
3506    /// # #[cfg(feature = "deploy")] {
3507    /// # use hydro_lang::prelude::*;
3508    /// # use futures::StreamExt;
3509    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
3510    /// let tick = process.tick();
3511    /// # // ticks are lazy by default, forces the second tick to run
3512    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
3513    /// # let batch_first_tick = process
3514    /// #   .source_iter(q!(vec![1, 2, 3, 4]))
3515    /// #  .batch(&tick, nondet!(/** test */));
3516    /// # let batch_second_tick = process
3517    /// #   .source_iter(q!(vec![5, 6, 7]))
3518    /// #   .batch(&tick, nondet!(/** test */))
3519    /// #   .defer_tick(); // appears on the second tick
3520    /// let input = // [1, 2, 3, 4 (first batch), 5, 6, 7 (second batch)]
3521    /// # batch_first_tick.chain(batch_second_tick);
3522    ///
3523    /// input.across_ticks(|s| s.count()).all_ticks()
3524    /// # }, |mut stream| async move {
3525    /// // [4, 7]
3526    /// assert_eq!(stream.next().await.unwrap(), 4);
3527    /// assert_eq!(stream.next().await.unwrap(), 7);
3528    /// # }));
3529    /// # }
3530    /// ```
3531    pub fn across_ticks<Out: BatchAtomic<'a>>(
3532        self,
3533        thunk: impl FnOnce(Stream<T, Atomic<L>, Unbounded, O, R>) -> Out,
3534    ) -> Out::Batched {
3535        thunk(self.all_ticks_atomic()).batched_atomic()
3536    }
3537
3538    /// Shifts the elements in `self` to the **next tick**, so that the returned stream at tick `T`
3539    /// always has the elements of `self` at tick `T - 1`.
3540    ///
3541    /// At tick `0`, the output stream is empty, since there is no previous tick.
3542    ///
3543    /// This operator enables stateful iterative processing with ticks, by sending data from one
3544    /// tick to the next. For example, you can use it to compare inputs across consecutive batches.
3545    ///
3546    /// # Example
3547    /// ```rust
3548    /// # #[cfg(feature = "deploy")] {
3549    /// # use hydro_lang::prelude::*;
3550    /// # use futures::StreamExt;
3551    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
3552    /// let tick = process.tick();
3553    /// // ticks are lazy by default, forces the second tick to run
3554    /// tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
3555    ///
3556    /// let batch_first_tick = process
3557    ///   .source_iter(q!(vec![1, 2, 3, 4]))
3558    ///   .batch(&tick, nondet!(/** test */));
3559    /// let batch_second_tick = process
3560    ///   .source_iter(q!(vec![0, 3, 4, 5, 6]))
3561    ///   .batch(&tick, nondet!(/** test */))
3562    ///   .defer_tick(); // appears on the second tick
3563    /// let changes_across_ticks = batch_first_tick.chain(batch_second_tick);
3564    ///
3565    /// changes_across_ticks.clone().filter_not_in(
3566    ///     changes_across_ticks.defer_tick() // the elements from the previous tick
3567    /// ).all_ticks()
3568    /// # }, |mut stream| async move {
3569    /// // [1, 2, 3, 4 /* first tick */, 0, 5, 6 /* second tick */]
3570    /// # for w in vec![1, 2, 3, 4, 0, 5, 6] {
3571    /// #     assert_eq!(stream.next().await.unwrap(), w);
3572    /// # }
3573    /// # }));
3574    /// # }
3575    /// ```
3576    pub fn defer_tick(self) -> Stream<T, Tick<L>, Bounded, O, R> {
3577        Stream::new(
3578            self.location.clone(),
3579            HydroNode::DeferTick {
3580                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
3581                metadata: self
3582                    .location
3583                    .new_node_metadata(Stream::<T, Tick<L>, Bounded, O, R>::collection_kind()),
3584            },
3585        )
3586    }
3587}
3588
3589impl<'a, T, L, B: Boundedness, O: Ordering, R: Retries> Stream<T, L, B, O, R>
3590where
3591    L: TopLevel<'a>,
3592{
3593    /// Delays every element of this top-level stream by one (internal) tick.
3594    ///
3595    /// A top-level stream has no observable ticks, so this does not change *which* elements the
3596    /// stream contains, only that each one arrives slightly later. Its purpose is to break
3597    /// dataflow cycles at the top level, e.g. a stream that is batched into a tick, yielded back
3598    /// out, and fed back (through a [`Location::forward_ref`]) into the same tick, which would
3599    /// otherwise be cyclical within a single tick.
3600    ///
3601    /// # Example
3602    /// ```rust
3603    /// # #[cfg(feature = "deploy")] {
3604    /// # use hydro_lang::prelude::*;
3605    /// # use futures::StreamExt;
3606    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
3607    /// process.source_iter(q!(vec![1, 2, 3])).defer_tick()
3608    /// # }, |mut stream| async move {
3609    /// // 1, 2, 3
3610    /// # for w in vec![1, 2, 3] {
3611    /// #     assert_eq!(stream.next().await.unwrap(), w);
3612    /// # }
3613    /// # }));
3614    /// # }
3615    /// ```
3616    pub fn defer_tick(self) -> Stream<T, L, B, O, R> {
3617        Stream::new(
3618            self.location.clone(),
3619            HydroNode::DeferTick {
3620                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
3621                metadata: self
3622                    .location
3623                    .new_node_metadata(Stream::<T, L, B, O, R>::collection_kind()),
3624            },
3625        )
3626    }
3627}
3628
3629#[cfg(test)]
3630mod tests {
3631    #[cfg(feature = "deploy")]
3632    use futures::{SinkExt, StreamExt};
3633    #[cfg(feature = "deploy")]
3634    use hydro_deploy::Deployment;
3635    #[cfg(feature = "deploy")]
3636    use serde::{Deserialize, Serialize};
3637    #[cfg(any(feature = "deploy", feature = "sim"))]
3638    use stageleft::q;
3639
3640    #[cfg(any(feature = "deploy", feature = "sim"))]
3641    use crate::compile::builder::FlowBuilder;
3642    #[cfg(feature = "deploy")]
3643    use crate::live_collections::sliced::sliced;
3644    #[cfg(feature = "deploy")]
3645    use crate::live_collections::stream::ExactlyOnce;
3646    #[cfg(feature = "sim")]
3647    use crate::live_collections::stream::NoOrder;
3648    #[cfg(any(feature = "deploy", feature = "sim"))]
3649    use crate::live_collections::stream::TotalOrder;
3650    #[cfg(any(feature = "deploy", feature = "sim"))]
3651    use crate::location::Location;
3652    #[cfg(feature = "sim")]
3653    use crate::networking::TCP;
3654    #[cfg(any(feature = "deploy", feature = "sim"))]
3655    use crate::nondet::nondet;
3656
3657    mod backtrace_chained_ops;
3658
3659    #[cfg(feature = "deploy")]
3660    struct P1 {}
3661    #[cfg(feature = "deploy")]
3662    struct P2 {}
3663
3664    #[cfg(feature = "deploy")]
3665    #[derive(Serialize, Deserialize, Debug)]
3666    struct SendOverNetwork {
3667        n: u32,
3668    }
3669
3670    #[cfg(feature = "deploy")]
3671    #[tokio::test]
3672    async fn first_ten_distributed() {
3673        use crate::networking::TCP;
3674
3675        let mut deployment = Deployment::new();
3676
3677        let mut flow = FlowBuilder::new();
3678        let first_node = flow.process::<P1>();
3679        let second_node = flow.process::<P2>();
3680        let external = flow.external::<P2>();
3681
3682        let numbers = first_node.source_iter(q!(0..10));
3683        let out_port = numbers
3684            .map(q!(|n| SendOverNetwork { n }))
3685            .send(&second_node, TCP.fail_stop().bincode())
3686            .send_bincode_external(&external);
3687
3688        let nodes = flow
3689            .with_process(&first_node, deployment.Localhost())
3690            .with_process(&second_node, deployment.Localhost())
3691            .with_external(&external, deployment.Localhost())
3692            .deploy(&mut deployment);
3693
3694        deployment.deploy().await.unwrap();
3695
3696        let mut external_out = nodes.connect(out_port).await;
3697
3698        deployment.start().await.unwrap();
3699
3700        for i in 0..10 {
3701            assert_eq!(external_out.next().await.unwrap().n, i);
3702        }
3703    }
3704
3705    #[cfg(feature = "deploy")]
3706    #[tokio::test]
3707    async fn first_cardinality() {
3708        let mut deployment = Deployment::new();
3709
3710        let mut flow = FlowBuilder::new();
3711        let node = flow.process::<()>();
3712        let external = flow.external::<()>();
3713
3714        let node_tick = node.tick();
3715        // Tick-located constants are lazy and never fire the tick on their own, so a spinning
3716        // batch drives `node_tick`.
3717        node_tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
3718        let count = node_tick
3719            .singleton(q!([1, 2, 3]))
3720            .into_stream()
3721            .flatten_ordered()
3722            .first()
3723            .into_stream()
3724            .count()
3725            .all_ticks()
3726            .send_bincode_external(&external);
3727
3728        let nodes = flow
3729            .with_process(&node, deployment.Localhost())
3730            .with_external(&external, deployment.Localhost())
3731            .deploy(&mut deployment);
3732
3733        deployment.deploy().await.unwrap();
3734
3735        let mut external_out = nodes.connect(count).await;
3736
3737        deployment.start().await.unwrap();
3738
3739        assert_eq!(external_out.next().await.unwrap(), 1);
3740    }
3741
3742    #[cfg(feature = "deploy")]
3743    #[tokio::test]
3744    async fn unbounded_reduce_remembers_state() {
3745        let mut deployment = Deployment::new();
3746
3747        let mut flow = FlowBuilder::new();
3748        let node = flow.process::<()>();
3749        let external = flow.external::<()>();
3750
3751        let (input_port, input) = node.source_external_bincode(&external);
3752        let out = input
3753            .reduce(q!(|acc, v| *acc += v))
3754            .sample_eager(nondet!(/** test */))
3755            .send_bincode_external(&external);
3756
3757        let nodes = flow
3758            .with_process(&node, deployment.Localhost())
3759            .with_external(&external, deployment.Localhost())
3760            .deploy(&mut deployment);
3761
3762        deployment.deploy().await.unwrap();
3763
3764        let mut external_in = nodes.connect(input_port).await;
3765        let mut external_out = nodes.connect(out).await;
3766
3767        deployment.start().await.unwrap();
3768
3769        external_in.send(1).await.unwrap();
3770        assert_eq!(external_out.next().await.unwrap(), 1);
3771
3772        external_in.send(2).await.unwrap();
3773        assert_eq!(external_out.next().await.unwrap(), 3);
3774    }
3775
3776    #[cfg(feature = "deploy")]
3777    #[tokio::test]
3778    async fn top_level_bounded_cross_singleton() {
3779        let mut deployment = Deployment::new();
3780
3781        let mut flow = FlowBuilder::new();
3782        let node = flow.process::<()>();
3783        let external = flow.external::<()>();
3784
3785        let (input_port, input) =
3786            node.source_external_bincode::<_, _, TotalOrder, ExactlyOnce>(&external);
3787
3788        let out = input
3789            .cross_singleton(
3790                node.source_iter(q!(vec![1, 2, 3]))
3791                    .fold(q!(|| 0), q!(|acc, v| *acc += v)),
3792            )
3793            .send_bincode_external(&external);
3794
3795        let nodes = flow
3796            .with_process(&node, deployment.Localhost())
3797            .with_external(&external, deployment.Localhost())
3798            .deploy(&mut deployment);
3799
3800        deployment.deploy().await.unwrap();
3801
3802        let mut external_in = nodes.connect(input_port).await;
3803        let mut external_out = nodes.connect(out).await;
3804
3805        deployment.start().await.unwrap();
3806
3807        external_in.send(1).await.unwrap();
3808        assert_eq!(external_out.next().await.unwrap(), (1, 6));
3809
3810        external_in.send(2).await.unwrap();
3811        assert_eq!(external_out.next().await.unwrap(), (2, 6));
3812    }
3813
3814    #[cfg(feature = "deploy")]
3815    #[tokio::test]
3816    async fn top_level_bounded_reduce_cardinality() {
3817        let mut deployment = Deployment::new();
3818
3819        let mut flow = FlowBuilder::new();
3820        let node = flow.process::<()>();
3821        let external = flow.external::<()>();
3822
3823        let (input_port, input) =
3824            node.source_external_bincode::<_, _, TotalOrder, ExactlyOnce>(&external);
3825
3826        let out = sliced! {
3827            let input = use::batch(input, nondet!(/** test */));
3828            let v = use::snapshot(node.source_iter(q!(vec![1, 2, 3])).reduce(q!(|acc, v| *acc += v)), nondet!(/** test */));
3829            input.cross_singleton(v.into_stream().count())
3830        }
3831        .send_bincode_external(&external);
3832
3833        let nodes = flow
3834            .with_process(&node, deployment.Localhost())
3835            .with_external(&external, deployment.Localhost())
3836            .deploy(&mut deployment);
3837
3838        deployment.deploy().await.unwrap();
3839
3840        let mut external_in = nodes.connect(input_port).await;
3841        let mut external_out = nodes.connect(out).await;
3842
3843        deployment.start().await.unwrap();
3844
3845        external_in.send(1).await.unwrap();
3846        assert_eq!(external_out.next().await.unwrap(), (1, 1));
3847
3848        external_in.send(2).await.unwrap();
3849        assert_eq!(external_out.next().await.unwrap(), (2, 1));
3850    }
3851
3852    #[cfg(feature = "deploy")]
3853    #[tokio::test]
3854    async fn top_level_bounded_into_singleton_cardinality() {
3855        let mut deployment = Deployment::new();
3856
3857        let mut flow = FlowBuilder::new();
3858        let node = flow.process::<()>();
3859        let external = flow.external::<()>();
3860
3861        let (input_port, input) =
3862            node.source_external_bincode::<_, _, TotalOrder, ExactlyOnce>(&external);
3863
3864        let out = sliced! {
3865            let input = use::batch(input, nondet!(/** test */));
3866            let v = use::snapshot(node.source_iter(q!(vec![1, 2, 3])).reduce(q!(|acc, v| *acc += v)).into_singleton(), nondet!(/** test */));
3867            input.cross_singleton(v.into_stream().count())
3868        }
3869        .send_bincode_external(&external);
3870
3871        let nodes = flow
3872            .with_process(&node, deployment.Localhost())
3873            .with_external(&external, deployment.Localhost())
3874            .deploy(&mut deployment);
3875
3876        deployment.deploy().await.unwrap();
3877
3878        let mut external_in = nodes.connect(input_port).await;
3879        let mut external_out = nodes.connect(out).await;
3880
3881        deployment.start().await.unwrap();
3882
3883        external_in.send(1).await.unwrap();
3884        assert_eq!(external_out.next().await.unwrap(), (1, 1));
3885
3886        external_in.send(2).await.unwrap();
3887        assert_eq!(external_out.next().await.unwrap(), (2, 1));
3888    }
3889
3890    #[cfg(feature = "deploy")]
3891    #[tokio::test]
3892    async fn atomic_fold_replays_each_tick() {
3893        let mut deployment = Deployment::new();
3894
3895        let mut flow = FlowBuilder::new();
3896        let node = flow.process::<()>();
3897        let external = flow.external::<()>();
3898
3899        let (input_port, input) =
3900            node.source_external_bincode::<_, _, TotalOrder, ExactlyOnce>(&external);
3901        let tick = node.tick();
3902
3903        let out = input
3904            .batch(&tick, nondet!(/** test */))
3905            .cross_singleton(
3906                node.source_iter(q!(vec![1, 2, 3]))
3907                    .atomic()
3908                    .fold(q!(|| 0), q!(|acc, v| *acc += v))
3909                    .snapshot_atomic(&tick, nondet!(/** test */)),
3910            )
3911            .all_ticks()
3912            .send_bincode_external(&external);
3913
3914        let nodes = flow
3915            .with_process(&node, deployment.Localhost())
3916            .with_external(&external, deployment.Localhost())
3917            .deploy(&mut deployment);
3918
3919        deployment.deploy().await.unwrap();
3920
3921        let mut external_in = nodes.connect(input_port).await;
3922        let mut external_out = nodes.connect(out).await;
3923
3924        deployment.start().await.unwrap();
3925
3926        external_in.send(1).await.unwrap();
3927        assert_eq!(external_out.next().await.unwrap(), (1, 6));
3928
3929        external_in.send(2).await.unwrap();
3930        assert_eq!(external_out.next().await.unwrap(), (2, 6));
3931    }
3932
3933    #[cfg(feature = "deploy")]
3934    #[tokio::test]
3935    async fn unbounded_scan_remembers_state() {
3936        let mut deployment = Deployment::new();
3937
3938        let mut flow = FlowBuilder::new();
3939        let node = flow.process::<()>();
3940        let external = flow.external::<()>();
3941
3942        let (input_port, input) = node.source_external_bincode(&external);
3943        let out = input
3944            .scan(
3945                q!(|| 0),
3946                q!(|acc, v| {
3947                    *acc += v;
3948                    Some(*acc)
3949                }),
3950            )
3951            .send_bincode_external(&external);
3952
3953        let nodes = flow
3954            .with_process(&node, deployment.Localhost())
3955            .with_external(&external, deployment.Localhost())
3956            .deploy(&mut deployment);
3957
3958        deployment.deploy().await.unwrap();
3959
3960        let mut external_in = nodes.connect(input_port).await;
3961        let mut external_out = nodes.connect(out).await;
3962
3963        deployment.start().await.unwrap();
3964
3965        external_in.send(1).await.unwrap();
3966        assert_eq!(external_out.next().await.unwrap(), 1);
3967
3968        external_in.send(2).await.unwrap();
3969        assert_eq!(external_out.next().await.unwrap(), 3);
3970    }
3971
3972    #[cfg(feature = "deploy")]
3973    #[tokio::test]
3974    async fn unbounded_enumerate_remembers_state() {
3975        let mut deployment = Deployment::new();
3976
3977        let mut flow = FlowBuilder::new();
3978        let node = flow.process::<()>();
3979        let external = flow.external::<()>();
3980
3981        let (input_port, input) = node.source_external_bincode(&external);
3982        let out = input.enumerate().send_bincode_external(&external);
3983
3984        let nodes = flow
3985            .with_process(&node, deployment.Localhost())
3986            .with_external(&external, deployment.Localhost())
3987            .deploy(&mut deployment);
3988
3989        deployment.deploy().await.unwrap();
3990
3991        let mut external_in = nodes.connect(input_port).await;
3992        let mut external_out = nodes.connect(out).await;
3993
3994        deployment.start().await.unwrap();
3995
3996        external_in.send(1).await.unwrap();
3997        assert_eq!(external_out.next().await.unwrap(), (0, 1));
3998
3999        external_in.send(2).await.unwrap();
4000        assert_eq!(external_out.next().await.unwrap(), (1, 2));
4001    }
4002
4003    #[cfg(feature = "deploy")]
4004    #[tokio::test]
4005    async fn unbounded_unique_remembers_state() {
4006        let mut deployment = Deployment::new();
4007
4008        let mut flow = FlowBuilder::new();
4009        let node = flow.process::<()>();
4010        let external = flow.external::<()>();
4011
4012        let (input_port, input) =
4013            node.source_external_bincode::<_, _, TotalOrder, ExactlyOnce>(&external);
4014        let out = input.unique().send_bincode_external(&external);
4015
4016        let nodes = flow
4017            .with_process(&node, deployment.Localhost())
4018            .with_external(&external, deployment.Localhost())
4019            .deploy(&mut deployment);
4020
4021        deployment.deploy().await.unwrap();
4022
4023        let mut external_in = nodes.connect(input_port).await;
4024        let mut external_out = nodes.connect(out).await;
4025
4026        deployment.start().await.unwrap();
4027
4028        external_in.send(1).await.unwrap();
4029        assert_eq!(external_out.next().await.unwrap(), 1);
4030
4031        external_in.send(2).await.unwrap();
4032        assert_eq!(external_out.next().await.unwrap(), 2);
4033
4034        external_in.send(1).await.unwrap();
4035        external_in.send(3).await.unwrap();
4036        assert_eq!(external_out.next().await.unwrap(), 3);
4037    }
4038
4039    #[cfg(feature = "sim")]
4040    #[test]
4041    #[should_panic]
4042    fn sim_batch_nondet_size() {
4043        let mut flow = FlowBuilder::new();
4044        let node = flow.process::<()>();
4045
4046        let (in_send, input) = node.sim_input::<_, TotalOrder, _>();
4047
4048        let tick = node.tick();
4049        let out_recv = input
4050            .batch(&tick, nondet!(/** test */))
4051            .count()
4052            .all_ticks()
4053            .sim_output();
4054
4055        flow.sim().exhaustive(async || {
4056            in_send.send(());
4057            in_send.send(());
4058            in_send.send(());
4059
4060            assert_eq!(out_recv.next().await, 3); // fails with nondet batching
4061        });
4062    }
4063
4064    #[cfg(feature = "sim")]
4065    #[test]
4066    fn sim_batch_preserves_order() {
4067        let mut flow = FlowBuilder::new();
4068        let node = flow.process::<()>();
4069
4070        let (in_send, input) = node.sim_input();
4071
4072        let tick = node.tick();
4073        let out_recv = input
4074            .batch(&tick, nondet!(/** test */))
4075            .all_ticks()
4076            .sim_output();
4077
4078        flow.sim().exhaustive(async || {
4079            in_send.send(1);
4080            in_send.send(2);
4081            in_send.send(3);
4082
4083            out_recv.assert_yields_only([1, 2, 3]).await;
4084        });
4085    }
4086
4087    #[cfg(feature = "sim")]
4088    #[test]
4089    #[should_panic]
4090    fn sim_batch_unordered_shuffles() {
4091        let mut flow = FlowBuilder::new();
4092        let node = flow.process::<()>();
4093
4094        let (in_send, input) = node.sim_input::<_, NoOrder, _>();
4095
4096        let tick = node.tick();
4097        let batch = input.batch(&tick, nondet!(/** test */));
4098        let out_recv = batch
4099            .clone()
4100            .min()
4101            .zip(batch.max())
4102            .all_ticks()
4103            .sim_output();
4104
4105        flow.sim().exhaustive(async || {
4106            in_send.send_many_unordered([1, 2, 3]);
4107
4108            assert!(
4109                out_recv.collect::<Vec<_>>().await != vec![(1, 3), (2, 2)],
4110                "saw both (1, 3) and (2, 2), so batching must have shuffled the order"
4111            )
4112        });
4113    }
4114
4115    #[cfg(feature = "sim")]
4116    #[test]
4117    fn sim_batch_unordered_shuffles_count() {
4118        let mut flow = FlowBuilder::new();
4119        let node = flow.process::<()>();
4120
4121        let (in_send, input) = node.sim_input::<_, NoOrder, _>();
4122
4123        let tick = node.tick();
4124        let batch = input.batch(&tick, nondet!(/** test */));
4125        let out_recv = batch.all_ticks().sim_output();
4126
4127        let instance_count = flow.sim().exhaustive(async || {
4128            in_send.send_many_unordered([1, 2, 3, 4]);
4129            out_recv.assert_yields_only_unordered([1, 2, 3, 4]).await;
4130        });
4131
4132        assert_eq!(
4133            instance_count,
4134            75 // ∑ (k=1 to 4) S(4,k) × k! = 75
4135        )
4136    }
4137
4138    #[cfg(feature = "sim")]
4139    #[test]
4140    #[should_panic]
4141    fn sim_observe_order_batched() {
4142        let mut flow = FlowBuilder::new();
4143        let node = flow.process::<()>();
4144
4145        let (in_send, input) = node.sim_input::<_, NoOrder, _>();
4146
4147        let tick = node.tick();
4148        let batch = input.batch(&tick, nondet!(/** test */));
4149        let out_recv = batch
4150            .assume_ordering::<TotalOrder>(nondet!(/** test */))
4151            .all_ticks()
4152            .sim_output();
4153
4154        flow.sim().exhaustive(async || {
4155            in_send.send_many_unordered([1, 2, 3, 4]);
4156            out_recv.assert_yields_only([1, 2, 3, 4]).await; // fails with assume_ordering
4157        });
4158    }
4159
4160    #[cfg(feature = "sim")]
4161    #[test]
4162    fn sim_observe_order_batched_count() {
4163        let mut flow = FlowBuilder::new();
4164        let node = flow.process::<()>();
4165
4166        let (in_send, input) = node.sim_input::<_, NoOrder, _>();
4167
4168        let tick = node.tick();
4169        let batch = input.batch(&tick, nondet!(/** test */));
4170        let out_recv = batch
4171            .assume_ordering::<TotalOrder>(nondet!(/** test */))
4172            .all_ticks()
4173            .sim_output();
4174
4175        let instance_count = flow.sim().exhaustive(async || {
4176            in_send.send_many_unordered([1, 2, 3, 4]);
4177            let _ = out_recv.collect::<Vec<_>>().await;
4178        });
4179
4180        assert_eq!(
4181            instance_count,
4182            192 // 4! * 2^{4 - 1}
4183        )
4184    }
4185
4186    #[cfg(feature = "sim")]
4187    #[test]
4188    fn sim_unordered_count_instance_count() {
4189        let mut flow = FlowBuilder::new();
4190        let node = flow.process::<()>();
4191
4192        let (in_send, input) = node.sim_input::<_, NoOrder, _>();
4193        // Snapshot ingress is lazy and never wakes the tick on its own, so an auxiliary
4194        // trigger stream drives the tick.
4195        let (trigger_send, trigger) = node.sim_input::<i32, TotalOrder, _>();
4196
4197        let tick = node.tick();
4198        let out_recv = trigger
4199            .batch(&tick, nondet!(/** test */))
4200            .cross_singleton(input.count().snapshot(&tick, nondet!(/** test */)))
4201            .map(q!(|(_, v)| v))
4202            .all_ticks()
4203            .sim_output();
4204
4205        let mut observed = std::collections::HashSet::new();
4206
4207        let instance_count = flow.sim().exhaustive(async || {
4208            in_send.send_many_unordered([1, 2, 3, 4]);
4209            trigger_send.send(1);
4210            let out = out_recv.collect::<Vec<_>>().await;
4211            // The single trigger drives exactly one tick, which observes one snapshot of
4212            // the count.
4213            assert_eq!(out.len(), 1);
4214            observed.insert(out[0]);
4215        });
4216
4217        assert_eq!(
4218            instance_count,
4219            5 // one instance per intermediate count (including the initial state 0)
4220        );
4221        assert_eq!(
4222            observed,
4223            [0, 1, 2, 3, 4]
4224                .into_iter()
4225                .collect::<std::collections::HashSet<_>>()
4226        );
4227    }
4228
4229    #[cfg(feature = "sim")]
4230    #[test]
4231    fn sim_top_level_assume_ordering() {
4232        let mut flow = FlowBuilder::new();
4233        let node = flow.process::<()>();
4234
4235        let (in_send, input) = node.sim_input::<_, NoOrder, _>();
4236
4237        let out_recv = input
4238            .assume_ordering::<TotalOrder>(nondet!(/** test */))
4239            .sim_output();
4240
4241        let instance_count = flow.sim().exhaustive(async || {
4242            in_send.send_many_unordered([1, 2, 3]);
4243            let mut out = out_recv.collect::<Vec<_>>().await;
4244            out.sort();
4245            assert_eq!(out, vec![1, 2, 3]);
4246        });
4247
4248        assert_eq!(instance_count, 6)
4249    }
4250
4251    #[cfg(feature = "sim")]
4252    #[test]
4253    fn sim_top_level_assume_ordering_cycle_back() {
4254        let mut flow = FlowBuilder::new();
4255        let node = flow.process::<()>();
4256        let node2 = flow.process::<()>();
4257
4258        let (in_send, input) = node.sim_input::<_, NoOrder, _>();
4259
4260        let (complete_cycle_back, cycle_back) =
4261            node.forward_ref::<super::Stream<_, _, _, NoOrder>>();
4262        let ordered = input
4263            .merge_unordered(cycle_back)
4264            .assume_ordering::<TotalOrder>(nondet!(/** test */));
4265        complete_cycle_back.complete(
4266            ordered
4267                .clone()
4268                .map(q!(|v| v + 1))
4269                .filter(q!(|v| v % 2 == 1))
4270                .send(&node2, TCP.fail_stop().bincode())
4271                .send(&node, TCP.fail_stop().bincode()),
4272        );
4273
4274        let out_recv = ordered.sim_output();
4275
4276        let mut saw = false;
4277        let instance_count = flow.sim().exhaustive(async || {
4278            in_send.send_many_unordered([0, 2]);
4279            let out = out_recv.collect::<Vec<_>>().await;
4280
4281            if out.starts_with(&[0, 1, 2]) {
4282                saw = true;
4283            }
4284        });
4285
4286        assert!(saw, "did not see an instance with 0, 1, 2 in order");
4287        assert_eq!(instance_count, 6);
4288    }
4289
4290    #[cfg(feature = "sim")]
4291    #[test]
4292    fn sim_top_level_assume_ordering_cycle_back_tick() {
4293        let mut flow = FlowBuilder::new();
4294        let node = flow.process::<()>();
4295        let node2 = flow.process::<()>();
4296
4297        let (in_send, input) = node.sim_input::<_, NoOrder, _>();
4298
4299        let (complete_cycle_back, cycle_back) =
4300            node.forward_ref::<super::Stream<_, _, _, NoOrder>>();
4301        let ordered = input
4302            .merge_unordered(cycle_back)
4303            .assume_ordering::<TotalOrder>(nondet!(/** test */));
4304        complete_cycle_back.complete(
4305            ordered
4306                .clone()
4307                .batch(&node.tick(), nondet!(/** test */))
4308                .all_ticks()
4309                .map(q!(|v| v + 1))
4310                .filter(q!(|v| v % 2 == 1))
4311                .send(&node2, TCP.fail_stop().bincode())
4312                .send(&node, TCP.fail_stop().bincode()),
4313        );
4314
4315        let out_recv = ordered.sim_output();
4316
4317        let mut saw = false;
4318        let instance_count = flow.sim().exhaustive(async || {
4319            in_send.send_many_unordered([0, 2]);
4320            let out = out_recv.collect::<Vec<_>>().await;
4321
4322            if out.starts_with(&[0, 1, 2]) {
4323                saw = true;
4324            }
4325        });
4326
4327        assert!(saw, "did not see an instance with 0, 1, 2 in order");
4328        assert_eq!(instance_count, 58);
4329    }
4330
4331    #[cfg(feature = "sim")]
4332    #[test]
4333    fn sim_top_level_assume_ordering_multiple() {
4334        let mut flow = FlowBuilder::new();
4335        let node = flow.process::<()>();
4336        let node2 = flow.process::<()>();
4337
4338        let (in_send, input) = node.sim_input::<_, NoOrder, _>();
4339        let (_, input2) = node.sim_input::<_, NoOrder, _>();
4340
4341        let (complete_cycle_back, cycle_back) =
4342            node.forward_ref::<super::Stream<_, _, _, NoOrder>>();
4343        let input1_ordered = input
4344            .clone()
4345            .merge_unordered(cycle_back)
4346            .assume_ordering::<TotalOrder>(nondet!(/** test */));
4347        let foo = input1_ordered
4348            .clone()
4349            .map(q!(|v| v + 3))
4350            .weaken_ordering::<NoOrder>()
4351            .merge_unordered(input2)
4352            .assume_ordering::<TotalOrder>(nondet!(/** test */));
4353
4354        complete_cycle_back.complete(
4355            foo.filter(q!(|v| *v == 3))
4356                .send(&node2, TCP.fail_stop().bincode())
4357                .send(&node, TCP.fail_stop().bincode()),
4358        );
4359
4360        let out_recv = input1_ordered.sim_output();
4361
4362        let mut saw = false;
4363        let instance_count = flow.sim().exhaustive(async || {
4364            in_send.send_many_unordered([0, 1]);
4365            let out = out_recv.collect::<Vec<_>>().await;
4366
4367            if out.starts_with(&[0, 3, 1]) {
4368                saw = true;
4369            }
4370        });
4371
4372        assert!(saw, "did not see an instance with 0, 3, 1 in order");
4373        assert_eq!(instance_count, 15);
4374    }
4375
4376    #[cfg(feature = "sim")]
4377    #[test]
4378    fn sim_atomic_assume_ordering_cycle_back() {
4379        let mut flow = FlowBuilder::new();
4380        let node = flow.process::<()>();
4381        let node2 = flow.process::<()>();
4382
4383        let (in_send, input) = node.sim_input::<_, NoOrder, _>();
4384
4385        let (complete_cycle_back, cycle_back) =
4386            node.forward_ref::<super::Stream<_, _, _, NoOrder>>();
4387        let ordered = input
4388            .merge_unordered(cycle_back)
4389            .atomic()
4390            .assume_ordering::<TotalOrder>(nondet!(/** test */))
4391            .end_atomic();
4392        complete_cycle_back.complete(
4393            ordered
4394                .clone()
4395                .map(q!(|v| v + 1))
4396                .filter(q!(|v| v % 2 == 1))
4397                .send(&node2, TCP.fail_stop().bincode())
4398                .send(&node, TCP.fail_stop().bincode()),
4399        );
4400
4401        let out_recv = ordered.sim_output();
4402
4403        let instance_count = flow.sim().exhaustive(async || {
4404            in_send.send_many_unordered([0, 2]);
4405            let out = out_recv.collect::<Vec<_>>().await;
4406            assert_eq!(out.len(), 4);
4407        });
4408        assert_eq!(instance_count, 22);
4409    }
4410
4411    #[cfg(feature = "deploy")]
4412    #[tokio::test]
4413    async fn partition_evens_odds() {
4414        let mut deployment = Deployment::new();
4415
4416        let mut flow = FlowBuilder::new();
4417        let node = flow.process::<()>();
4418        let external = flow.external::<()>();
4419
4420        let numbers = node.source_iter(q!(vec![1i32, 2, 3, 4, 5, 6]));
4421        let (evens, odds) = numbers.partition(q!(|x: &i32| x % 2 == 0));
4422        let evens_port = evens.send_bincode_external(&external);
4423        let odds_port = odds.send_bincode_external(&external);
4424
4425        let nodes = flow
4426            .with_process(&node, deployment.Localhost())
4427            .with_external(&external, deployment.Localhost())
4428            .deploy(&mut deployment);
4429
4430        deployment.deploy().await.unwrap();
4431
4432        let mut evens_out = nodes.connect(evens_port).await;
4433        let mut odds_out = nodes.connect(odds_port).await;
4434
4435        deployment.start().await.unwrap();
4436
4437        let mut even_results = Vec::new();
4438        for _ in 0..3 {
4439            even_results.push(evens_out.next().await.unwrap());
4440        }
4441        even_results.sort();
4442        assert_eq!(even_results, vec![2, 4, 6]);
4443
4444        let mut odd_results = Vec::new();
4445        for _ in 0..3 {
4446            odd_results.push(odds_out.next().await.unwrap());
4447        }
4448        odd_results.sort();
4449        assert_eq!(odd_results, vec![1, 3, 5]);
4450    }
4451
4452    #[cfg(feature = "deploy")]
4453    #[tokio::test]
4454    async fn unconsumed_inspect_still_runs() {
4455        use crate::deploy::DeployCrateWrapper;
4456
4457        let mut deployment = Deployment::new();
4458
4459        let mut flow = FlowBuilder::new();
4460        let node = flow.process::<()>();
4461
4462        // The return value of .inspect() is intentionally dropped.
4463        // Before the Null-root fix, this would silently do nothing.
4464        node.source_iter(q!(0..5))
4465            .inspect(q!(|x| println!("inspect: {}", x)));
4466
4467        let nodes = flow
4468            .with_process(&node, deployment.Localhost())
4469            .deploy(&mut deployment);
4470
4471        deployment.deploy().await.unwrap();
4472
4473        let mut stdout = nodes.get_process(&node).stdout();
4474
4475        deployment.start().await.unwrap();
4476
4477        let mut lines = Vec::new();
4478        for _ in 0..5 {
4479            lines.push(stdout.recv().await.unwrap());
4480        }
4481        lines.sort();
4482        assert_eq!(
4483            lines,
4484            vec![
4485                "inspect: 0",
4486                "inspect: 1",
4487                "inspect: 2",
4488                "inspect: 3",
4489                "inspect: 4",
4490            ]
4491        );
4492    }
4493
4494    #[cfg(feature = "deploy")]
4495    #[tokio::test]
4496    async fn unconsumed_inspect_alive_at_deploy_still_runs() {
4497        use crate::deploy::DeployCrateWrapper;
4498
4499        let mut deployment = Deployment::new();
4500
4501        let mut flow = FlowBuilder::new();
4502        let node = flow.process::<()>();
4503
4504        // The return value of .inspect() is bound to a variable that is still alive
4505        // when the flow is finalized by `deploy` below, so its `Drop` runs too late
4506        // to register a root the usual way. The FlowBuilder must yank the IR from
4507        // still-live collections when finalizing.
4508        let _inspected = node
4509            .source_iter(q!(0..5))
4510            .inspect(q!(|x| println!("inspect: {}", x)));
4511
4512        let nodes = flow
4513            .with_process(&node, deployment.Localhost())
4514            .deploy(&mut deployment);
4515
4516        deployment.deploy().await.unwrap();
4517
4518        let mut stdout = nodes.get_process(&node).stdout();
4519
4520        deployment.start().await.unwrap();
4521
4522        let mut lines = Vec::new();
4523        for _ in 0..5 {
4524            lines.push(stdout.recv().await.unwrap());
4525        }
4526        lines.sort();
4527        assert_eq!(
4528            lines,
4529            vec![
4530                "inspect: 0",
4531                "inspect: 1",
4532                "inspect: 2",
4533                "inspect: 3",
4534                "inspect: 4",
4535            ]
4536        );
4537    }
4538
4539    #[cfg(feature = "sim")]
4540    #[test]
4541    fn sim_limit() {
4542        let mut flow = FlowBuilder::new();
4543        let node = flow.process::<()>();
4544
4545        let (in_send, input) = node.sim_input();
4546
4547        let out_recv = input.limit(q!(3)).sim_output();
4548
4549        flow.sim().exhaustive(async || {
4550            in_send.send(1);
4551            in_send.send(2);
4552            in_send.send(3);
4553            in_send.send(4);
4554            in_send.send(5);
4555
4556            out_recv.assert_yields_only([1, 2, 3]).await;
4557        });
4558    }
4559
4560    #[cfg(feature = "sim")]
4561    #[test]
4562    fn sim_limit_zero() {
4563        let mut flow = FlowBuilder::new();
4564        let node = flow.process::<()>();
4565
4566        let (in_send, input) = node.sim_input();
4567
4568        let out_recv = input.limit(q!(0)).sim_output();
4569
4570        flow.sim().exhaustive(async || {
4571            in_send.send(1);
4572            in_send.send(2);
4573
4574            out_recv.assert_yields_only::<i32, _>([]).await;
4575        });
4576    }
4577
4578    #[cfg(feature = "sim")]
4579    #[test]
4580    fn sim_merge_ordered() {
4581        let mut flow = FlowBuilder::new();
4582        let node = flow.process::<()>();
4583
4584        let (in_send, input) = node.sim_input();
4585        let (in_send2, input2) = node.sim_input();
4586
4587        let out_recv = input
4588            .merge_ordered(input2, nondet!(/** test */))
4589            .sim_output();
4590
4591        let mut saw_out_of_order = false;
4592        let instances = flow.sim().exhaustive(async || {
4593            in_send.send(1);
4594            in_send.send(2);
4595            in_send2.send(3);
4596            in_send2.send(4);
4597
4598            let out = out_recv.collect::<Vec<_>>().await;
4599
4600            if out == [1, 3, 2, 4] {
4601                saw_out_of_order = true;
4602            }
4603
4604            // Assert ordering preservation: elements from each input must
4605            // appear in their original relative order.
4606            let mut first_elements = out.iter().filter(|v| **v <= 2).copied().collect::<Vec<_>>();
4607            let mut second_elements = out.iter().filter(|v| **v > 2).copied().collect::<Vec<_>>();
4608            assert_eq!(
4609                first_elements,
4610                vec![1, 2],
4611                "first input order violated: {:?}",
4612                out
4613            );
4614            assert_eq!(
4615                second_elements,
4616                vec![3, 4],
4617                "second input order violated: {:?}",
4618                out
4619            );
4620
4621            first_elements.append(&mut second_elements);
4622            first_elements.sort();
4623            assert_eq!(first_elements, vec![1, 2, 3, 4]);
4624        });
4625
4626        assert!(saw_out_of_order);
4627        assert_eq!(instances, 6);
4628    }
4629
4630    /// Tests that `merge_ordered` passes through elements when only one input
4631    /// has data.
4632    #[cfg(feature = "sim")]
4633    #[test]
4634    fn sim_merge_ordered_one_empty() {
4635        let mut flow = FlowBuilder::new();
4636        let node = flow.process::<()>();
4637
4638        let (in_send, input) = node.sim_input();
4639        let (_in_send2, input2) = node.sim_input();
4640
4641        let out_recv = input
4642            .merge_ordered(input2, nondet!(/** test */))
4643            .sim_output();
4644
4645        let instances = flow.sim().exhaustive(async || {
4646            in_send.send(1);
4647            in_send.send(2);
4648
4649            let out = out_recv.collect::<Vec<_>>().await;
4650            assert_eq!(out, vec![1, 2]);
4651        });
4652
4653        // Only one possible interleaving when one input is empty
4654        assert_eq!(instances, 1);
4655    }
4656
4657    /// Tests that `merge_ordered` correctly handles feedback cycles.
4658    /// An element output from `merge_ordered` is filtered and cycled back to
4659    /// one of its inputs. The one-at-a-time release must allow the cycled-back
4660    /// element to arrive and potentially be emitted before elements still
4661    /// waiting on the other input.
4662    #[cfg(feature = "sim")]
4663    #[test]
4664    fn sim_merge_ordered_cycle_back() {
4665        let mut flow = FlowBuilder::new();
4666        let node = flow.process::<()>();
4667
4668        let (in_send, input) = node.sim_input();
4669
4670        // Create a forward ref for the cycle back
4671        let (complete_cycle_back, cycle_back) =
4672            node.forward_ref::<super::Stream<_, _, _, TotalOrder>>();
4673
4674        // merge_ordered: input (external) with cycle_back
4675        let merged = input.merge_ordered(cycle_back, nondet!(/** test */));
4676
4677        // Cycle back: elements equal to 1 get mapped to 10 and fed back
4678        complete_cycle_back.complete(merged.clone().filter(q!(|v| *v == 1)).map(q!(|v| v * 10)));
4679
4680        let out_recv = merged.sim_output();
4681
4682        // Send 1 and 2. Element 1 should cycle back as 10.
4683        // Valid orderings must have 1 before 10 (since 10 depends on 1).
4684        let mut saw_cycle_before_second = false;
4685        flow.sim().exhaustive(async || {
4686            in_send.send(1);
4687            in_send.send(2);
4688
4689            let out = out_recv.collect::<Vec<_>>().await;
4690
4691            // 10 must always come after 1 (causal dependency)
4692            let pos_1 = out.iter().position(|v| *v == 1).unwrap();
4693            let pos_10 = out.iter().position(|v| *v == 10).unwrap();
4694            assert!(pos_1 < pos_10, "causal order violated: {:?}", out);
4695
4696            // Check if we see [1, 10, 2] — the cycled element beats the second input
4697            if out == [1, 10, 2] {
4698                saw_cycle_before_second = true;
4699            }
4700
4701            let mut sorted = out;
4702            sorted.sort();
4703            assert_eq!(sorted, vec![1, 2, 10]);
4704        });
4705
4706        assert!(
4707            saw_cycle_before_second,
4708            "never saw the cycled element arrive before the second input element"
4709        );
4710    }
4711
4712    /// Tests that `merge_ordered` correctly interleaves when one input has a
4713    /// delayed element. With a: [1, _delay_, 2] and b: [3, 4], the delayed
4714    /// element 2 should be able to appear after b's elements.
4715    #[cfg(feature = "sim")]
4716    #[test]
4717    fn sim_merge_ordered_delayed() {
4718        let mut flow = FlowBuilder::new();
4719        let node = flow.process::<()>();
4720
4721        let (in_send, input) = node.sim_input();
4722        let (in_send2, input2) = node.sim_input();
4723
4724        let out_recv = input
4725            .merge_ordered(input2, nondet!(/** test */))
4726            .sim_output();
4727
4728        let mut saw_delayed_interleaving = false;
4729        flow.sim().exhaustive(async || {
4730            // Send 1 from a, and 3, 4 from b
4731            in_send.send(1);
4732            in_send2.send(3);
4733            in_send2.send(4);
4734
4735            // Collect what's available so far
4736            let first_batch = out_recv.collect::<Vec<_>>().await;
4737
4738            // Now send the delayed element 2 from a
4739            in_send.send(2);
4740            let second_batch = out_recv.collect::<Vec<_>>().await;
4741
4742            let mut all: Vec<_> = first_batch
4743                .iter()
4744                .chain(second_batch.iter())
4745                .copied()
4746                .collect();
4747
4748            // Check if we saw [1, 3, 4, 2] — the delayed interleaving
4749            if all == [1, 3, 4, 2] {
4750                saw_delayed_interleaving = true;
4751            }
4752
4753            all.sort();
4754            assert_eq!(all, vec![1, 2, 3, 4]);
4755        });
4756
4757        assert!(saw_delayed_interleaving);
4758    }
4759
4760    /// Deploy test: `merge_ordered` with a delayed element on one input.
4761    /// Sends a=1, b=3, b=4, then after receiving those, sends a=2.
4762    /// Expects to see [1, 3, 4] first, then [2] — demonstrating that
4763    /// both inputs are pulled and the delayed element arrives later.
4764    #[cfg(feature = "deploy")]
4765    #[tokio::test]
4766    async fn deploy_merge_ordered_delayed() {
4767        let mut deployment = Deployment::new();
4768
4769        let mut flow = FlowBuilder::new();
4770        let node = flow.process::<()>();
4771        let external = flow.external::<()>();
4772
4773        let (input_a_port, input_a) = node.source_external_bincode(&external);
4774        let (input_b_port, input_b) = node.source_external_bincode(&external);
4775
4776        let out = input_a
4777            .assume_ordering(nondet!(/** test */))
4778            .merge_ordered(
4779                input_b.assume_ordering(nondet!(/** test */)),
4780                nondet!(/** test */),
4781            )
4782            .send_bincode_external(&external);
4783
4784        let nodes = flow
4785            .with_process(&node, deployment.Localhost())
4786            .with_external(&external, deployment.Localhost())
4787            .deploy(&mut deployment);
4788
4789        deployment.deploy().await.unwrap();
4790
4791        let mut ext_a = nodes.connect(input_a_port).await;
4792        let mut ext_b = nodes.connect(input_b_port).await;
4793        let mut ext_out = nodes.connect(out).await;
4794
4795        deployment.start().await.unwrap();
4796
4797        // Send a=1, b=3, b=4
4798        ext_a.send(1).await.unwrap();
4799        ext_b.send(3).await.unwrap();
4800        ext_b.send(4).await.unwrap();
4801
4802        // Collect the first 3 elements
4803        let mut received = Vec::new();
4804        for _ in 0..3 {
4805            received.push(ext_out.next().await.unwrap());
4806        }
4807
4808        // Now send the delayed a=2
4809        ext_a.send(2).await.unwrap();
4810        received.push(ext_out.next().await.unwrap());
4811
4812        // All elements should be present
4813        received.sort();
4814        assert_eq!(received, vec![1, 2, 3, 4]);
4815    }
4816
4817    #[cfg(feature = "deploy")]
4818    #[tokio::test]
4819    async fn monotone_fold_threshold() {
4820        use crate::properties::manual_proof;
4821
4822        let mut deployment = Deployment::new();
4823
4824        let mut flow = FlowBuilder::new();
4825        let node = flow.process::<()>();
4826        let external = flow.external::<()>();
4827
4828        let in_unbounded: super::Stream<_, _> =
4829            node.source_iter(q!(vec![1i32, 2, 3, 4, 5, 6])).into();
4830        let sum = in_unbounded.fold(
4831            q!(|| 0),
4832            q!(
4833                |sum, v| {
4834                    *sum += v;
4835                },
4836                monotone = manual_proof!(/** test */)
4837            ),
4838        );
4839
4840        let threshold_out = sum
4841            .threshold_greater_or_equal(node.singleton(q!(7)))
4842            .send_bincode_external(&external);
4843
4844        let nodes = flow
4845            .with_process(&node, deployment.Localhost())
4846            .with_external(&external, deployment.Localhost())
4847            .deploy(&mut deployment);
4848
4849        deployment.deploy().await.unwrap();
4850
4851        let mut threshold_out = nodes.connect(threshold_out).await;
4852
4853        deployment.start().await.unwrap();
4854
4855        assert_eq!(threshold_out.next().await.unwrap(), 7);
4856    }
4857
4858    #[cfg(feature = "deploy")]
4859    #[tokio::test]
4860    async fn monotone_count_threshold() {
4861        let mut deployment = Deployment::new();
4862
4863        let mut flow = FlowBuilder::new();
4864        let node = flow.process::<()>();
4865        let external = flow.external::<()>();
4866
4867        let in_unbounded: super::Stream<_, _> =
4868            node.source_iter(q!(vec![1i32, 2, 3, 4, 5, 6])).into();
4869        let sum = in_unbounded.count();
4870
4871        let threshold_out = sum
4872            .threshold_greater_or_equal(node.singleton(q!(3)))
4873            .send_bincode_external(&external);
4874
4875        let nodes = flow
4876            .with_process(&node, deployment.Localhost())
4877            .with_external(&external, deployment.Localhost())
4878            .deploy(&mut deployment);
4879
4880        deployment.deploy().await.unwrap();
4881
4882        let mut threshold_out = nodes.connect(threshold_out).await;
4883
4884        deployment.start().await.unwrap();
4885
4886        assert_eq!(threshold_out.next().await.unwrap(), 3);
4887    }
4888
4889    #[cfg(feature = "deploy")]
4890    #[tokio::test]
4891    async fn monotone_map_order_preserving_threshold() {
4892        use crate::properties::manual_proof;
4893
4894        let mut deployment = Deployment::new();
4895
4896        let mut flow = FlowBuilder::new();
4897        let node = flow.process::<()>();
4898        let external = flow.external::<()>();
4899
4900        let in_unbounded: super::Stream<_, _> =
4901            node.source_iter(q!(vec![1i32, 2, 3, 4, 5, 6])).into();
4902        let sum = in_unbounded.fold(
4903            q!(|| 0),
4904            q!(
4905                |sum, v| {
4906                    *sum += v;
4907                },
4908                monotone = manual_proof!(/** test */)
4909            ),
4910        );
4911
4912        // map with order_preserving should preserve monotonicity
4913        let doubled = sum.map(q!(
4914            |v| v * 2,
4915            order_preserving = manual_proof!(/** doubling preserves order */)
4916        ));
4917
4918        let threshold_out = doubled
4919            .threshold_greater_or_equal(node.singleton(q!(14)))
4920            .send_bincode_external(&external);
4921
4922        let nodes = flow
4923            .with_process(&node, deployment.Localhost())
4924            .with_external(&external, deployment.Localhost())
4925            .deploy(&mut deployment);
4926
4927        deployment.deploy().await.unwrap();
4928
4929        let mut threshold_out = nodes.connect(threshold_out).await;
4930
4931        deployment.start().await.unwrap();
4932
4933        assert_eq!(threshold_out.next().await.unwrap(), 14);
4934    }
4935
4936    // === Compile-time type tests for join/cross_product ordering ===
4937
4938    #[cfg(any(feature = "deploy", feature = "sim"))]
4939    mod join_ordering_type_tests {
4940        use crate::live_collections::boundedness::{Bounded, Unbounded};
4941        use crate::live_collections::stream::{ExactlyOnce, NoOrder, Stream, TotalOrder};
4942        use crate::location::{Location, Process};
4943
4944        #[expect(dead_code, reason = "compile-time type test")]
4945        fn join_unbounded_with_bounded_preserves_order<'a>(
4946            left: Stream<(i32, char), Process<'a>, Unbounded, TotalOrder, ExactlyOnce>,
4947            right: Stream<(i32, char), Process<'a>, Bounded, TotalOrder, ExactlyOnce>,
4948        ) -> Stream<(i32, (char, char)), Process<'a>, Unbounded, TotalOrder, ExactlyOnce> {
4949            left.join(right)
4950        }
4951
4952        #[expect(dead_code, reason = "compile-time type test")]
4953        fn join_unbounded_with_unbounded_is_no_order<'a>(
4954            left: Stream<(i32, char), Process<'a>, Unbounded, TotalOrder, ExactlyOnce>,
4955            right: Stream<(i32, char), Process<'a>, Unbounded, TotalOrder, ExactlyOnce>,
4956        ) -> Stream<(i32, (char, char)), Process<'a>, Unbounded, NoOrder, ExactlyOnce> {
4957            left.join(right)
4958        }
4959
4960        #[expect(dead_code, reason = "compile-time type test")]
4961        fn join_bounded_with_bounded_preserves_order<'a, L: Location<'a>>(
4962            left: Stream<(i32, char), L, Bounded, TotalOrder, ExactlyOnce>,
4963            right: Stream<(i32, char), L, Bounded, TotalOrder, ExactlyOnce>,
4964        ) -> Stream<(i32, (char, char)), L, Bounded, TotalOrder, ExactlyOnce> {
4965            left.join(right)
4966        }
4967
4968        #[expect(dead_code, reason = "compile-time type test")]
4969        fn join_unbounded_noorder_with_bounded<'a>(
4970            left: Stream<(i32, char), Process<'a>, Unbounded, NoOrder, ExactlyOnce>,
4971            right: Stream<(i32, char), Process<'a>, Bounded, NoOrder, ExactlyOnce>,
4972        ) -> Stream<(i32, (char, char)), Process<'a>, Unbounded, NoOrder, ExactlyOnce> {
4973            left.join(right)
4974        }
4975
4976        // === Compile-time type tests for cross_product ordering ===
4977
4978        #[expect(dead_code, reason = "compile-time type test")]
4979        fn cross_product_unbounded_with_bounded_preserves_order<'a>(
4980            left: Stream<i32, Process<'a>, Unbounded, TotalOrder, ExactlyOnce>,
4981            right: Stream<char, Process<'a>, Bounded, TotalOrder, ExactlyOnce>,
4982        ) -> Stream<(i32, char), Process<'a>, Unbounded, TotalOrder, ExactlyOnce> {
4983            left.cross_product(right)
4984        }
4985
4986        #[expect(dead_code, reason = "compile-time type test")]
4987        fn cross_product_bounded_with_bounded_preserves_order<'a>(
4988            left: Stream<i32, Process<'a>, Bounded, TotalOrder, ExactlyOnce>,
4989            right: Stream<char, Process<'a>, Bounded, TotalOrder, ExactlyOnce>,
4990        ) -> Stream<(i32, char), Process<'a>, Bounded, TotalOrder, ExactlyOnce> {
4991            left.cross_product(right)
4992        }
4993
4994        #[expect(dead_code, reason = "compile-time type test")]
4995        fn cross_product_unbounded_with_unbounded_is_no_order<'a>(
4996            left: Stream<i32, Process<'a>, Unbounded, TotalOrder, ExactlyOnce>,
4997            right: Stream<char, Process<'a>, Unbounded, TotalOrder, ExactlyOnce>,
4998        ) -> Stream<(i32, char), Process<'a>, Unbounded, NoOrder, ExactlyOnce> {
4999            left.cross_product(right)
5000        }
5001    } // mod join_ordering_type_tests
5002
5003    // === Runtime correctness tests for bounded join/cross_product ===
5004
5005    #[cfg(feature = "sim")]
5006    #[test]
5007    fn cross_product_mixed_boundedness_correctness() {
5008        use stageleft::q;
5009
5010        use crate::compile::builder::FlowBuilder;
5011        use crate::nondet::nondet;
5012
5013        let mut flow = FlowBuilder::new();
5014        let process = flow.process::<()>();
5015        let tick = process.tick();
5016
5017        let left = process.source_iter(q!(vec![1, 2]));
5018        let right = process
5019            .source_iter(q!(vec!['a', 'b']))
5020            .batch(&tick, nondet!(/** test */))
5021            .all_ticks();
5022
5023        let out = left.cross_product(right).sim_output();
5024
5025        flow.sim().exhaustive(async || {
5026            out.assert_yields_only_unordered(vec![(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')])
5027                .await;
5028        });
5029    }
5030
5031    #[cfg(feature = "sim")]
5032    #[test]
5033    fn join_mixed_boundedness_correctness() {
5034        use stageleft::q;
5035
5036        use crate::compile::builder::FlowBuilder;
5037        use crate::nondet::nondet;
5038
5039        let mut flow = FlowBuilder::new();
5040        let process = flow.process::<()>();
5041        let tick = process.tick();
5042
5043        let left = process.source_iter(q!(vec![(1, 'a'), (2, 'b')]));
5044        let right = process
5045            .source_iter(q!(vec![(1, 'x'), (2, 'y')]))
5046            .batch(&tick, nondet!(/** test */))
5047            .all_ticks();
5048
5049        let out = left.join(right).sim_output();
5050
5051        flow.sim().exhaustive(async || {
5052            out.assert_yields_only_unordered(vec![(1, ('a', 'x')), (2, ('b', 'y'))])
5053                .await;
5054        });
5055    }
5056
5057    #[cfg(feature = "sim")]
5058    #[test]
5059    fn sim_merge_unordered_independent_atomics() {
5060        let mut flow = FlowBuilder::new();
5061        let node = flow.process::<()>();
5062
5063        let (in1_send, input1) = node.sim_input::<_, TotalOrder, _>();
5064        let (in2_send, input2) = node.sim_input::<_, TotalOrder, _>();
5065
5066        let out = input1
5067            .atomic()
5068            .merge_unordered(input2.atomic())
5069            .end_atomic()
5070            .sim_output();
5071
5072        flow.sim().exhaustive(async || {
5073            in1_send.send(1);
5074            in2_send.send(2);
5075
5076            out.assert_yields_only_unordered(vec![1, 2]).await;
5077        });
5078    }
5079
5080    #[cfg(feature = "deploy")]
5081    #[tokio::test]
5082    async fn test_stream_ref() {
5083        let mut deployment = Deployment::new();
5084
5085        let mut flow = FlowBuilder::new();
5086        let external = flow.external::<()>();
5087        let p1 = flow.process::<()>();
5088
5089        // Create a bounded stream (source_iter is bounded within a tick)
5090        let my_stream = p1.source_iter(q!(1..=5i32));
5091
5092        let stream_ref = my_stream.by_ref();
5093
5094        // Use the stream ref to get the vec's length
5095        let out_port = p1
5096            .source_iter(q!([()]))
5097            .map(q!(|_| stream_ref.len() as i32))
5098            .send_bincode_external(&external);
5099
5100        // Also consume the stream via pipe
5101        my_stream.for_each(q!(|_| {}));
5102
5103        let nodes = flow
5104            .with_default_optimize()
5105            .with_process(&p1, deployment.Localhost())
5106            .with_external(&external, deployment.Localhost())
5107            .deploy(&mut deployment);
5108
5109        deployment.deploy().await.unwrap();
5110
5111        let mut out_recv = nodes.connect(out_port).await;
5112
5113        deployment.start().await.unwrap();
5114
5115        let result = out_recv.next().await.unwrap();
5116        // stream has 5 elements
5117        assert_eq!(result, 5);
5118    }
5119
5120    #[cfg(feature = "deploy")]
5121    #[tokio::test]
5122    async fn test_stream_ref_contents() {
5123        let mut deployment = Deployment::new();
5124
5125        let mut flow = FlowBuilder::new();
5126        let external = flow.external::<()>();
5127        let p1 = flow.process::<()>();
5128
5129        // Create a bounded stream
5130        let my_stream = p1.source_iter(q!(1..=3i32));
5131
5132        let stream_ref = my_stream.by_ref();
5133
5134        // Sum the referenced vec's contents
5135        let out_port = p1
5136            .source_iter(q!([()]))
5137            .map(q!(|_| stream_ref.iter().sum::<i32>()))
5138            .send_bincode_external(&external);
5139
5140        my_stream.for_each(q!(|_| {}));
5141
5142        let nodes = flow
5143            .with_default_optimize()
5144            .with_process(&p1, deployment.Localhost())
5145            .with_external(&external, deployment.Localhost())
5146            .deploy(&mut deployment);
5147
5148        deployment.deploy().await.unwrap();
5149
5150        let mut out_recv = nodes.connect(out_port).await;
5151
5152        deployment.start().await.unwrap();
5153
5154        let result = out_recv.next().await.unwrap();
5155        // sum of 1+2+3 = 6
5156        assert_eq!(result, 6);
5157    }
5158
5159    #[cfg(feature = "deploy")]
5160    #[tokio::test]
5161    async fn test_stream_ref_no_consumer() {
5162        let mut deployment = Deployment::new();
5163
5164        let mut flow = FlowBuilder::new();
5165        let external = flow.external::<()>();
5166        let p1 = flow.process::<()>();
5167
5168        // Create a bounded stream — no pipe consumer, only ref
5169        let my_stream = p1.source_iter(q!(1..=4i32));
5170
5171        let stream_ref = my_stream.by_ref();
5172
5173        let out_port = p1
5174            .source_iter(q!([()]))
5175            .map(q!(|_| stream_ref.len() as i32))
5176            .send_bincode_external(&external);
5177
5178        let nodes = flow
5179            .with_default_optimize()
5180            .with_process(&p1, deployment.Localhost())
5181            .with_external(&external, deployment.Localhost())
5182            .deploy(&mut deployment);
5183
5184        deployment.deploy().await.unwrap();
5185
5186        let mut out_recv = nodes.connect(out_port).await;
5187
5188        deployment.start().await.unwrap();
5189
5190        let result = out_recv.next().await.unwrap();
5191        assert_eq!(result, 4);
5192    }
5193
5194    #[cfg(feature = "deploy")]
5195    #[tokio::test]
5196    async fn test_stream_mut() {
5197        let mut deployment = Deployment::new();
5198
5199        let mut flow = FlowBuilder::new();
5200        let external = flow.external::<()>();
5201        let p1 = flow.process::<()>();
5202
5203        // Create a bounded stream
5204        let my_stream = p1.source_iter(q!(1..=5i32));
5205
5206        let stream_mut = my_stream.by_mut();
5207
5208        // Mutably reference the buffer to retain only items > 3
5209        let out_port = p1
5210            .source_iter(q!([()]))
5211            .map(q!(|_| {
5212                stream_mut.retain(|x| *x > 3);
5213                stream_mut.len() as i32
5214            }))
5215            .send_bincode_external(&external);
5216
5217        my_stream.for_each(q!(|_| {}));
5218
5219        let nodes = flow
5220            .with_default_optimize()
5221            .with_process(&p1, deployment.Localhost())
5222            .with_external(&external, deployment.Localhost())
5223            .deploy(&mut deployment);
5224
5225        deployment.deploy().await.unwrap();
5226
5227        let mut out_recv = nodes.connect(out_port).await;
5228
5229        deployment.start().await.unwrap();
5230
5231        let result = out_recv.next().await.unwrap();
5232        // After retain(> 3): [4, 5] => len = 2
5233        assert_eq!(result, 2);
5234    }
5235
5236    /// A map with a mut singleton ref on an unordered input should produce > 1
5237    /// simulation instance because the ordering of elements through the mut closure
5238    /// is non-deterministic.
5239    #[cfg(feature = "sim")]
5240    #[test]
5241    fn sim_map_with_mut_on_unordered_explores_multiple_states() {
5242        use crate::live_collections::sliced::sliced;
5243        use crate::live_collections::stream::ExactlyOnce;
5244        use crate::properties::manual_proof;
5245
5246        let mut flow = FlowBuilder::new();
5247        let node = flow.process::<()>();
5248
5249        let (trigger_send, trigger) = node.sim_input::<i32, TotalOrder, ExactlyOnce>();
5250
5251        let out_recv = sliced! {
5252            let batch = use::batch(trigger, nondet!(/** test */));
5253            let counter = batch.location().source_iter(q!(vec![0i32]))
5254                .fold(q!(|| 0i32), q!(|acc, v| *acc += v));
5255            let counter_mut = counter.by_mut();
5256            let items = batch.location().source_iter(q!(vec![1i32, 2])).weaken_ordering::<NoOrder>();
5257            items.map(q!(
5258                |x| {
5259                    *counter_mut += x;
5260                    *counter_mut
5261                },
5262                commutative = manual_proof!(/** test */)
5263            ))
5264        }
5265        .sim_output();
5266
5267        let count = flow.sim().exhaustive(async || {
5268            trigger_send.send(1);
5269            let _all: Vec<i32> = out_recv.collect_sorted().await;
5270        });
5271
5272        assert_eq!(
5273            count, 2,
5274            "Expected 2 simulation instances due to mut on unordered input, got {}",
5275            count
5276        );
5277    }
5278
5279    /// A `scan` closure that captures a bounded singleton by reference should compile,
5280    /// run correctly, and (because the input is totally ordered) explore a single
5281    /// simulation instance.
5282    #[cfg(feature = "sim")]
5283    #[test]
5284    fn sim_scan_with_ref_capture() {
5285        use crate::live_collections::sliced::sliced;
5286        use crate::live_collections::stream::ExactlyOnce;
5287
5288        let mut flow = FlowBuilder::new();
5289        let node = flow.process::<()>();
5290
5291        let (trigger_send, trigger) = node.sim_input::<i32, TotalOrder, ExactlyOnce>();
5292
5293        let out_recv = sliced! {
5294            let batch = use::batch(trigger, nondet!(/** test */));
5295            let offset = batch
5296                .location()
5297                .source_iter(q!(vec![10i32]))
5298                .fold(q!(|| 0i32), q!(|acc, v| *acc += v));
5299            let offset_ref = offset.by_ref();
5300            batch
5301                .location()
5302                .source_iter(q!(vec![1i32, 2, 3]))
5303                .scan(
5304                    q!(|| 0i32),
5305                    q!(move |acc: &mut i32, x| {
5306                        *acc += x + *offset_ref;
5307                        Some(*acc)
5308                    }),
5309                )
5310        }
5311        .sim_output();
5312
5313        let count = flow.sim().exhaustive(async || {
5314            trigger_send.send(1);
5315            let all: Vec<i32> = out_recv.collect().await;
5316            // offset = 10, running accumulator starts at 0:
5317            //   x=1: acc += 1 + 10 = 11 -> 11
5318            //   x=2: acc += 2 + 10 = 12 -> 23
5319            //   x=3: acc += 3 + 10 = 13 -> 36
5320            assert_eq!(all, vec![11, 23, 36]);
5321        });
5322
5323        assert_eq!(
5324            count, 1,
5325            "Expected a single simulation instance for a totally-ordered scan, got {}",
5326            count
5327        );
5328    }
5329
5330    /// A map with a mut singleton ref on a top-level unordered input should produce > 1
5331    /// simulation instance. Currently panics because `observe_nondet` doesn't support
5332    /// top-level bounded inputs yet.
5333    #[cfg(feature = "sim")]
5334    #[test]
5335    #[ignore = "observe_nondet not yet supported for top-level bounded inputs (https://github.com/hydro-project/hydro/issues/2950)"]
5336    fn sim_map_with_mut_on_unordered_top_level() {
5337        use crate::properties::manual_proof;
5338
5339        let mut flow = FlowBuilder::new();
5340        let node = flow.process::<()>();
5341
5342        let counter = node
5343            .source_iter(q!(vec![0i32]))
5344            .fold(q!(|| 0i32), q!(|acc, v| *acc += v));
5345        let counter_mut = counter.by_mut();
5346
5347        let out_recv = node
5348            .source_iter(q!(vec![1i32, 2]))
5349            .weaken_ordering::<NoOrder>()
5350            .map(q!(
5351                |x| {
5352                    *counter_mut += x;
5353                    *counter_mut
5354                },
5355                commutative = manual_proof!(/** test */)
5356            ))
5357            .assume_ordering::<TotalOrder>(nondet!(/** test */))
5358            .sim_output();
5359
5360        counter.into_stream().for_each(q!(|_| {}));
5361
5362        let count = flow.sim().exhaustive(async || {
5363            let _all: Vec<i32> = out_recv.collect().await;
5364        });
5365
5366        assert_eq!(
5367            count, 2,
5368            "Expected 2 simulation instances due to mut on unordered input, got {}",
5369            count
5370        );
5371    }
5372
5373    #[cfg(feature = "sim")]
5374    #[test]
5375    fn sim_top_level_defer_tick() {
5376        let mut flow = FlowBuilder::new();
5377        let node = flow.process::<()>();
5378
5379        let out_recv = node
5380            .source_iter(q!(vec![1, 2, 3]))
5381            .defer_tick()
5382            .sim_output();
5383
5384        flow.sim().exhaustive(async || {
5385            out_recv.assert_yields_only([1, 2, 3]).await;
5386        });
5387    }
5388
5389    /// A top-level `defer_tick` breaks a cycle that is batched into a tick, yielded back out,
5390    /// and fed back into the same tick.
5391    #[cfg(feature = "sim")]
5392    #[test]
5393    fn sim_top_level_defer_tick_breaks_tick_cycle() {
5394        let mut flow = FlowBuilder::new();
5395        let node = flow.process::<()>();
5396
5397        let (back_complete, back) = node.forward_ref::<super::Stream<
5398            u32,
5399            _,
5400            crate::live_collections::boundedness::Unbounded,
5401        >>();
5402        let tick = node.tick();
5403        let out = node
5404            .source_iter(q!(vec![0u32]))
5405            .batch(&tick, nondet!(/** test */))
5406            .chain(back.batch(&tick, nondet!(/** test */)))
5407            .all_ticks();
5408        back_complete.complete(
5409            out.clone()
5410                .filter(q!(|x| *x < 3))
5411                .map(q!(|x| x + 1))
5412                .defer_tick(),
5413        );
5414        let out_recv = out.sim_output();
5415
5416        flow.sim().exhaustive(async || {
5417            out_recv.assert_yields_only([0, 1, 2, 3]).await;
5418        });
5419    }
5420}