Skip to main content

hydro_lang/live_collections/sliced/
mod.rs

1//! Utilities for transforming live collections via slicing.
2
3pub mod style;
4
5use super::boundedness::{Bounded, Unbounded};
6use super::stream::{Ordering, Retries};
7use crate::location::{Location, Tick};
8
9#[doc(hidden)]
10#[macro_export]
11macro_rules! __sliced_parse_uses__ {
12    // Parse immutable use statements with style: let name = use::style(args...);
13    (
14        @uses [$($uses:tt)*]
15        @states [$($states:tt)*]
16        let $name:ident = use:: $invocation:expr; $($rest:tt)*
17    ) => {
18        $crate::__sliced_parse_uses__!(
19            @uses [$($uses)* { $name, $invocation, $invocation }]
20            @states [$($states)*]
21            $($rest)*
22        )
23    };
24
25    // Parse immutable use statements without style: let name = use(args...);
26    // This form is deprecated; the `default` style function it expands to is marked
27    // `#[deprecated]`, which surfaces a deprecation warning on the user's `use(...)` tokens
28    // (via `copy_span!`).
29    (
30        @uses [$($uses:tt)*]
31        @states [$($states:tt)*]
32        let $name:ident = use($($args:expr),* $(,)?); $($rest:tt)*
33    ) => {
34        $crate::__sliced_parse_uses__!(
35            @uses [$($uses)* { $name, $crate::macro_support::copy_span::copy_span!($($args,)* default)($($args),*), $($args),* }]
36            @states [$($states)*]
37            $($rest)*
38        )
39    };
40
41    // Parse mutable state statements: let mut name = use::style::<Type>(args);
42    (
43        @uses [$($uses:tt)*]
44        @states [$($states:tt)*]
45        let mut $name:ident = use:: $style:ident $(::<$ty:ty>)? ($($args:expr)?); $($rest:tt)*
46    ) => {
47        $crate::__sliced_parse_uses__!(
48            @uses [$($uses)*]
49            @states [$($states)* { $name, $style, (($($ty)?), ($($args)?)) }]
50            $($rest)*
51        )
52    };
53
54    // Terminal case: no uses, only states
55    (
56        @uses []
57        @states [$({ $state_name:ident, $state_style:ident, $state_arg:tt })+]
58        $($body:tt)*
59    ) => {
60        {
61            // We need at least one use to get a tick, so panic if there are none
62            compile_error!("sliced! requires at least one `let name = use(...)` statement to determine the tick")
63        }
64    };
65
66    // Terminal case: uses with optional states
67    (
68        @uses [$({ $use_name:ident, $invocation:expr, $($invocation_spans:expr),* })+]
69        @states [$({ $state_name:ident, $state_style:ident, (($($state_ty:ty)?), ($($state_arg:expr)?)) })*]
70        $($body:tt)*
71    ) => {
72        {
73            use $crate::live_collections::sliced::style::*;
74            let __styled = (
75                $($invocation,)+
76            );
77
78            let __tick = $crate::live_collections::sliced::Slicable::create_tick(&__styled.0);
79            let __backtraces = {
80                use $crate::compile::ir::backtrace::__macro_get_backtrace;
81                (
82                    $($crate::macro_support::copy_span::copy_span!($($invocation_spans,)* {
83                        __macro_get_backtrace(1)
84                    }),)+
85                )
86            };
87            let __sliced = $crate::live_collections::sliced::Slicable::slice(__styled, &__tick, __backtraces);
88            let (
89                $($use_name,)+
90            ) = __sliced;
91
92            // Create all cycles and pack handles/values into tuples.
93            //
94            // The `copy_span!` wrapper re-spans the macro-generated tokens (the style function
95            // path and the `build` call) to the user's tokens, so that errors arising from the
96            // state creation (e.g. an initializer that is not general enough over lifetimes) are
97            // attributed to the originating `use` statement instead of the entire `sliced!`
98            // invocation. The `$state_ty` and `$state_arg` fragments are passed through untouched
99            // (as interpolated fragments), preserving the precise spans of errors within the
100            // user-provided argument.
101            //
102            // Each state borrows its own clone of the tick (created inside the `copy_span!`
103            // target and spanned to the style name, e.g. `state`), so lifetime errors caused
104            // by a bad initializer point at the originating `use` statement rather than the
105            // shared `__tick` local, whose span covers the entire macro invocation.
106            let (__handles, __states) = $crate::live_collections::sliced::unzip_cycles((
107                $($crate::macro_support::copy_span::copy_span!($state_style, {
108                    $crate::live_collections::sliced::style::$state_style$(::<$state_ty, _>)?(& __tick.clone()).build($($state_arg)?)
109                }),)*
110            ));
111
112            // Unpack mutable state values
113            let (
114                $(mut $state_name,)*
115            ) = __states;
116
117            // Execute the body
118            let __body_result = {
119                $($body)*
120            };
121
122            // Re-pack the final state values and complete cycles
123            let __final_states = (
124                $($state_name,)*
125            );
126            $crate::live_collections::sliced::complete_cycles(__handles, __final_states);
127
128            // Unslice the result
129            $crate::live_collections::sliced::Unslicable::unslice(__body_result)
130        }
131    };
132}
133
134#[macro_export]
135/// Transforms a live collection with a computation relying on a slice of another live collection.
136/// This is useful for reading a snapshot of an asynchronously updated collection while processing another
137/// collection, such as joining a stream with the latest values from a singleton.
138///
139/// # Syntax
140/// The `sliced!` macro takes in a closure-like syntax specifying the live collections to be sliced
141/// and the body of the transformation. Each `use` statement indicates a live collection to be sliced,
142/// along with a non-determinism explanation. The style specifies how the live collection is sliced:
143/// `use::batch` for stream-like collections (such as [`Stream`](crate::live_collections::Stream)),
144/// `use::snapshot` for singleton-like collections (such as
145/// [`Singleton`](crate::live_collections::Singleton)), `use::atomic` for atomically-processed
146/// collections, and `use::clone` (which takes no non-determinism explanation) for reading a
147/// bounded singleton-like collection (see [Bounded Values](#bounded-values)). All `use`
148/// statements must appear before the body.
149///
150/// ```rust,ignore
151/// let stream = sliced! {
152///     let name1 = use::batch(stream1, nondet!(/** explanation */));
153///     let name2 = use::snapshot(singleton2, nondet!(/** explanation */));
154///     let name3 = use::atomic(collection3, nondet!(/** explanation */));
155///
156///     // arbitrary statements can follow
157///     let intermediate = name1.map(...);
158///     intermediate.cross_singleton(name2)
159/// };
160/// ```
161///
162/// The style-less form `use(collection, nondet!(...))`, which picks between batching and
163/// snapshotting automatically based on the collection type, is deprecated; use the explicit
164/// `use::batch` or `use::snapshot` styles instead.
165///
166/// # Bounded Values
167/// A top-level **bounded** [`Singleton`](crate::live_collections::Singleton) or
168/// [`Optional`](crate::live_collections::Optional) (for example, a configuration value fixed
169/// when the flow is built) can be read in every slice with `use::clone(collection)`, which
170/// takes no non-determinism explanation since the collection has a single immutable value.
171/// The binding is a bounded `Singleton` (or `Optional`) on the slice's tick, which can be used
172/// like any snapshot (e.g. with `cross_singleton` or `by_ref()`). The value is cloned into
173/// every tick, so it must implement [`Clone`]; avoiding that clone requires snapshots to
174/// return references ([hydro#2415](https://github.com/hydro-project/hydro/issues/2415)), and
175/// a `use::reference` style is planned for that. Unbounded collections are rejected at compile
176/// time; use `use::snapshot` for those. See
177/// [`clone`](crate::live_collections::sliced::style::clone) for details.
178///
179/// ```rust,ignore
180/// let stream = sliced! {
181///     let batch = use::batch(stream1, nondet!(/** explanation */));
182///     let config = use::clone(bounded_config);
183///
184///     let config = config.by_ref();
185///     batch.map(q!(|x| x * config.scale))
186/// };
187/// ```
188///
189/// # Stateful Computations
190/// The `sliced!` macro also supports stateful computations across iterations using `let mut` bindings
191/// with `use::state` or `use::state_null`. These create cycles that persist values between iterations.
192///
193/// - `use::state(|l| initial)`: Creates a cycle with an initial value. The closure receives
194///   the slice location and returns the initial state for the first iteration.
195/// - `use::state_null::<Type>()`: Creates a cycle that starts as null/empty on the first iteration.
196///
197/// The mutable binding can be reassigned in the body, and the final value will be passed to the
198/// next iteration.
199///
200/// ```rust,ignore
201/// let counter_stream = sliced! {
202///     let batch = use::batch(input_stream, nondet!(/** explanation */));
203///     let mut counter = use::state(|l| l.singleton(q!(0)));
204///
205///     // Increment counter by the number of items in this batch
206///     let new_count = counter.clone().zip(batch.count())
207///         .map(q!(|(old, add)| old + add));
208///     counter = new_count.clone();
209///     new_count.into_stream()
210/// };
211/// ```
212macro_rules! __sliced__ {
213    ($($tt:tt)*) => {
214        $crate::__sliced_parse_uses__!(
215            @uses []
216            @states []
217            $($tt)*
218        )
219    };
220}
221
222pub use crate::__sliced__ as sliced;
223
224/// Marks this live collection as atomically-yielded, which means that the output outside
225/// `sliced` will be at an atomic location that is synchronous with respect to the body
226/// of the slice.
227pub fn yield_atomic<T>(t: T) -> style::Atomic<T> {
228    style::Atomic {
229        collection: t,
230        // yield_atomic doesn't need a nondet since it's for output, not input
231        nondet: crate::nondet::NonDet::unhooked(),
232    }
233}
234
235/// A trait for live collections which can be sliced into bounded versions at a tick.
236pub trait Slicable<'a, L: Location<'a>> {
237    /// The sliced version of this live collection.
238    type Slice;
239
240    /// The type of backtrace associated with this slice.
241    type Backtrace;
242
243    /// Gets the location associated with this live collection.
244    fn get_location(&self) -> L;
245
246    /// Creates a tick that is appropriate for the collection's location.
247    fn create_tick(&self) -> Tick<L> {
248        self.get_location().try_tick().unwrap()
249    }
250
251    /// Slices this live collection at the given tick.
252    ///
253    /// # Non-Determinism
254    /// Slicing a live collection may involve non-determinism, such as choosing which messages
255    /// to include in a batch.
256    fn slice(self, tick: &Tick<L>, backtrace: Self::Backtrace) -> Self::Slice;
257}
258
259/// A trait for live collections which can be yielded out of a slice back into their original form.
260pub trait Unslicable {
261    /// The unsliced version of this live collection.
262    type Unsliced;
263
264    /// Unslices a sliced live collection back into its original form.
265    fn unslice(self) -> Self::Unsliced;
266}
267
268/// A trait for unzipping a tuple of (handle, state) pairs into separate tuples.
269#[doc(hidden)]
270pub trait UnzipCycles {
271    /// The tuple of cycle handles.
272    type Handles;
273    /// The tuple of state values.
274    type States;
275
276    /// Unzips the cycles into handles and states.
277    fn unzip(self) -> (Self::Handles, Self::States);
278}
279
280/// Unzips a tuple of cycles into handles and states.
281#[doc(hidden)]
282pub fn unzip_cycles<T: UnzipCycles>(cycles: T) -> (T::Handles, T::States) {
283    cycles.unzip()
284}
285
286/// A trait for completing a tuple of cycle handles with their final state values.
287#[doc(hidden)]
288pub trait CompleteCycles<States> {
289    /// Completes all cycles with the provided state values.
290    fn complete(self, states: States);
291}
292
293/// Completes a tuple of cycle handles with their final state values.
294#[doc(hidden)]
295pub fn complete_cycles<H: CompleteCycles<S>, S>(handles: H, states: S) {
296    handles.complete(states);
297}
298
299impl<'a, L: Location<'a>> Slicable<'a, L> for () {
300    type Slice = ();
301    type Backtrace = ();
302
303    fn get_location(&self) -> L {
304        unreachable!()
305    }
306
307    fn slice(self, _tick: &Tick<L>, _backtrace: Self::Backtrace) -> Self::Slice {}
308}
309
310impl Unslicable for () {
311    type Unsliced = ();
312
313    fn unslice(self) -> Self::Unsliced {}
314}
315
316macro_rules! impl_slicable_for_tuple {
317    ($($T:ident, $T_bt:ident, $idx:tt),+) => {
318        impl<'a, L: Location<'a>, $($T: Slicable<'a, L>),+> Slicable<'a, L> for ($($T,)+) {
319            type Slice = ($($T::Slice,)+);
320            type Backtrace = ($($T::Backtrace,)+);
321
322            fn get_location(&self) -> L {
323                self.0.get_location()
324            }
325
326            #[expect(non_snake_case, reason = "macro codegen")]
327            fn slice(self, tick: &Tick<L>, backtrace: Self::Backtrace) -> Self::Slice {
328                let ($($T,)+) = self;
329                let ($($T_bt,)+) = backtrace;
330                ($($T.slice(tick, $T_bt),)+)
331            }
332        }
333
334        impl<$($T: Unslicable),+> Unslicable for ($($T,)+) {
335            type Unsliced = ($($T::Unsliced,)+);
336
337            #[expect(non_snake_case, reason = "macro codegen")]
338            fn unslice(self) -> Self::Unsliced {
339                let ($($T,)+) = self;
340                ($($T.unslice(),)+)
341            }
342        }
343    };
344}
345
346#[cfg(stageleft_runtime)]
347impl_slicable_for_tuple!(S1, S1_bt, 0);
348#[cfg(stageleft_runtime)]
349impl_slicable_for_tuple!(S1, S1_bt, 0, S2, S2_bt, 1);
350#[cfg(stageleft_runtime)]
351impl_slicable_for_tuple!(S1, S1_bt, 0, S2, S2_bt, 1, S3, S3_bt, 2);
352#[cfg(stageleft_runtime)]
353impl_slicable_for_tuple!(S1, S1_bt, 0, S2, S2_bt, 1, S3, S3_bt, 2, S4, S4_bt, 3);
354#[cfg(stageleft_runtime)]
355impl_slicable_for_tuple!(
356    S1, S1_bt, 0, S2, S2_bt, 1, S3, S3_bt, 2, S4, S4_bt, 3, S5, S5_bt, 4
357);
358#[cfg(stageleft_runtime)]
359impl_slicable_for_tuple!(
360    S1, S1_bt, 0, S2, S2_bt, 1, S3, S3_bt, 2, S4, S4_bt, 3, S5, S5_bt, 4, S6, S6_bt, 5
361);
362#[cfg(stageleft_runtime)]
363impl_slicable_for_tuple!(
364    S1, S1_bt, 0, S2, S2_bt, 1, S3, S3_bt, 2, S4, S4_bt, 3, S5, S5_bt, 4, S6, S6_bt, 5, S7, S7_bt,
365    6
366);
367#[cfg(stageleft_runtime)]
368impl_slicable_for_tuple!(
369    S1, S1_bt, 0, S2, S2_bt, 1, S3, S3_bt, 2, S4, S4_bt, 3, S5, S5_bt, 4, S6, S6_bt, 5, S7, S7_bt,
370    6, S8, S8_bt, 7
371);
372#[cfg(stageleft_runtime)]
373impl_slicable_for_tuple!(
374    S1, S1_bt, 0, S2, S2_bt, 1, S3, S3_bt, 2, S4, S4_bt, 3, S5, S5_bt, 4, S6, S6_bt, 5, S7, S7_bt,
375    6, S8, S8_bt, 7, S9, S9_bt, 8
376);
377#[cfg(stageleft_runtime)]
378impl_slicable_for_tuple!(
379    S1, S1_bt, 0, S2, S2_bt, 1, S3, S3_bt, 2, S4, S4_bt, 3, S5, S5_bt, 4, S6, S6_bt, 5, S7, S7_bt,
380    6, S8, S8_bt, 7, S9, S9_bt, 8, S10, S10_bt, 9
381);
382#[cfg(stageleft_runtime)]
383impl_slicable_for_tuple!(
384    S1, S1_bt, 0, S2, S2_bt, 1, S3, S3_bt, 2, S4, S4_bt, 3, S5, S5_bt, 4, S6, S6_bt, 5, S7, S7_bt,
385    6, S8, S8_bt, 7, S9, S9_bt, 8, S10, S10_bt, 9, S11, S11_bt, 10
386);
387#[cfg(stageleft_runtime)]
388impl_slicable_for_tuple!(
389    S1, S1_bt, 0, S2, S2_bt, 1, S3, S3_bt, 2, S4, S4_bt, 3, S5, S5_bt, 4, S6, S6_bt, 5, S7, S7_bt,
390    6, S8, S8_bt, 7, S9, S9_bt, 8, S10, S10_bt, 9, S11, S11_bt, 10, S12, S12_bt, 11
391);
392
393macro_rules! impl_cycles_for_tuple {
394    ($($H:ident, $S:ident, $idx:tt),*) => {
395        impl<$($H, $S),*> UnzipCycles for ($(($H, $S),)*) {
396            type Handles = ($($H,)*);
397            type States = ($($S,)*);
398
399            #[expect(clippy::allow_attributes, reason = "macro codegen")]
400            #[allow(non_snake_case, reason = "macro codegen")]
401            fn unzip(self) -> (Self::Handles, Self::States) {
402                let ($($H,)*) = self;
403                (
404                    ($($H.0,)*),
405                    ($($H.1,)*),
406                )
407            }
408        }
409
410        impl<$($H: crate::forward_handle::CompleteCycle<$S>, $S),*> CompleteCycles<($($S,)*)> for ($($H,)*) {
411            #[expect(clippy::allow_attributes, reason = "macro codegen")]
412            #[allow(non_snake_case, reason = "macro codegen")]
413            fn complete(self, states: ($($S,)*)) {
414                let ($($H,)*) = self;
415                let ($($S,)*) = states;
416                $($H.complete_next_tick($S);)*
417            }
418        }
419    };
420}
421
422#[cfg(stageleft_runtime)]
423impl_cycles_for_tuple!();
424#[cfg(stageleft_runtime)]
425impl_cycles_for_tuple!(H1, S1, 0);
426#[cfg(stageleft_runtime)]
427impl_cycles_for_tuple!(H1, S1, 0, H2, S2, 1);
428#[cfg(stageleft_runtime)]
429impl_cycles_for_tuple!(H1, S1, 0, H2, S2, 1, H3, S3, 2);
430#[cfg(stageleft_runtime)]
431impl_cycles_for_tuple!(H1, S1, 0, H2, S2, 1, H3, S3, 2, H4, S4, 3);
432#[cfg(stageleft_runtime)]
433impl_cycles_for_tuple!(H1, S1, 0, H2, S2, 1, H3, S3, 2, H4, S4, 3, H5, S5, 4);
434#[cfg(stageleft_runtime)]
435impl_cycles_for_tuple!(
436    H1, S1, 0, H2, S2, 1, H3, S3, 2, H4, S4, 3, H5, S5, 4, H6, S6, 5
437);
438#[cfg(stageleft_runtime)]
439impl_cycles_for_tuple!(
440    H1, S1, 0, H2, S2, 1, H3, S3, 2, H4, S4, 3, H5, S5, 4, H6, S6, 5, H7, S7, 6
441);
442#[cfg(stageleft_runtime)]
443impl_cycles_for_tuple!(
444    H1, S1, 0, H2, S2, 1, H3, S3, 2, H4, S4, 3, H5, S5, 4, H6, S6, 5, H7, S7, 6, H8, S8, 7
445);
446#[cfg(stageleft_runtime)]
447impl_cycles_for_tuple!(
448    H1, S1, 0, H2, S2, 1, H3, S3, 2, H4, S4, 3, H5, S5, 4, H6, S6, 5, H7, S7, 6, H8, S8, 7, H9, S9,
449    8
450);
451#[cfg(stageleft_runtime)]
452impl_cycles_for_tuple!(
453    H1, S1, 0, H2, S2, 1, H3, S3, 2, H4, S4, 3, H5, S5, 4, H6, S6, 5, H7, S7, 6, H8, S8, 7, H9, S9,
454    8, H10, S10, 9
455);
456#[cfg(stageleft_runtime)]
457impl_cycles_for_tuple!(
458    H1, S1, 0, H2, S2, 1, H3, S3, 2, H4, S4, 3, H5, S5, 4, H6, S6, 5, H7, S7, 6, H8, S8, 7, H9, S9,
459    8, H10, S10, 9, H11, S11, 10
460);
461#[cfg(stageleft_runtime)]
462impl_cycles_for_tuple!(
463    H1, S1, 0, H2, S2, 1, H3, S3, 2, H4, S4, 3, H5, S5, 4, H6, S6, 5, H7, S7, 6, H8, S8, 7, H9, S9,
464    8, H10, S10, 9, H11, S11, 10, H12, S12, 11
465);
466
467// Unslicable implementations for plain collections (used when returning from sliced! body)
468impl<'a, T, L: Location<'a>, O: Ordering, R: Retries> Unslicable
469    for super::Stream<T, Tick<L>, Bounded, O, R>
470{
471    type Unsliced = super::Stream<T, L, Unbounded, O, R>;
472
473    fn unslice(self) -> Self::Unsliced {
474        self.all_ticks()
475    }
476}
477
478impl<'a, T, L: Location<'a>> Unslicable for super::Singleton<T, Tick<L>, Bounded> {
479    type Unsliced = super::Optional<T, L, crate::live_collections::optional::InitNone>;
480
481    fn unslice(self) -> Self::Unsliced {
482        self.latest()
483    }
484}
485
486impl<'a, T, L: Location<'a>> Unslicable for super::Optional<T, Tick<L>, Bounded> {
487    type Unsliced = super::Optional<T, L, Unbounded>;
488
489    fn unslice(self) -> Self::Unsliced {
490        self.latest()
491    }
492}
493
494impl<'a, K, V, L: Location<'a>, O: Ordering, R: Retries> Unslicable
495    for super::KeyedStream<K, V, Tick<L>, Bounded, O, R>
496{
497    type Unsliced = super::KeyedStream<K, V, L, Unbounded, O, R>;
498
499    fn unslice(self) -> Self::Unsliced {
500        self.all_ticks()
501    }
502}
503
504// Unslicable implementations for Atomic-wrapped bounded collections
505impl<'a, T, L: Location<'a>, O: Ordering, R: Retries> Unslicable
506    for style::Atomic<super::Stream<T, Tick<L>, Bounded, O, R>>
507{
508    type Unsliced = super::Stream<T, crate::location::Atomic<L>, Unbounded, O, R>;
509
510    fn unslice(self) -> Self::Unsliced {
511        self.collection.all_ticks_atomic()
512    }
513}
514
515impl<'a, T, L: Location<'a>> Unslicable for style::Atomic<super::Singleton<T, Tick<L>, Bounded>> {
516    type Unsliced =
517        super::Optional<T, crate::location::Atomic<L>, crate::live_collections::optional::InitNone>;
518
519    fn unslice(self) -> Self::Unsliced {
520        self.collection.latest_atomic()
521    }
522}
523
524impl<'a, T, L: Location<'a>> Unslicable for style::Atomic<super::Optional<T, Tick<L>, Bounded>> {
525    type Unsliced = super::Optional<T, crate::location::Atomic<L>, Unbounded>;
526
527    fn unslice(self) -> Self::Unsliced {
528        self.collection.latest_atomic()
529    }
530}
531
532impl<'a, K, V, L: Location<'a>, O: Ordering, R: Retries> Unslicable
533    for style::Atomic<super::KeyedStream<K, V, Tick<L>, Bounded, O, R>>
534{
535    type Unsliced = super::KeyedStream<K, V, crate::location::Atomic<L>, Unbounded, O, R>;
536
537    fn unslice(self) -> Self::Unsliced {
538        self.collection.all_ticks_atomic()
539    }
540}
541
542#[cfg(feature = "sim")]
543#[cfg(test)]
544mod tests {
545    use stageleft::q;
546
547    use super::sliced;
548    use crate::location::Location;
549    use crate::nondet::nondet;
550    use crate::prelude::FlowBuilder;
551
552    /// Test a counter using `use::state` with an initial singleton value.
553    /// Each input increments the counter, and we verify the output after each tick.
554    #[test]
555    fn sim_state_counter() {
556        let mut flow = FlowBuilder::new();
557        let node = flow.process::<()>();
558
559        let (input_send, input) = node.sim_input::<i32, _, _>();
560
561        let out_recv = sliced! {
562            let batch = use::batch(input, nondet!(/** test */));
563            let mut counter = use::state(|l| l.singleton(q!(0)));
564
565            let new_count = counter.clone().zip(batch.count())
566                .map(q!(|(old, add)| old + add));
567            counter = new_count.clone();
568            new_count.into_stream()
569        }
570        .sim_output();
571
572        flow.sim().exhaustive(async || {
573            input_send.send(1);
574            assert_eq!(out_recv.next().await, 1);
575
576            input_send.send(1);
577            assert_eq!(out_recv.next().await, 2);
578
579            input_send.send(1);
580            assert_eq!(out_recv.next().await, 3);
581        });
582    }
583
584    /// Test `use::state_null` with an Optional that starts as None.
585    #[cfg(feature = "sim")]
586    #[test]
587    fn sim_state_null_optional() {
588        use crate::live_collections::Optional;
589        use crate::live_collections::boundedness::Bounded;
590        use crate::location::{Location, Tick};
591
592        let mut flow = FlowBuilder::new();
593        let node = flow.process::<()>();
594
595        let (input_send, input) = node.sim_input::<i32, _, _>();
596
597        let out_recv = sliced! {
598            let batch = use::batch(input, nondet!(/** test */));
599            let mut prev = use::state_null::<Optional<i32, Tick<_>, Bounded>>();
600
601            // Output the previous value (or -1 if none)
602            let output = prev.clone().unwrap_or(prev.location().singleton(q!(-1)));
603            // Store the current batch's first value for next tick
604            prev = batch.first();
605            output.into_stream()
606        }
607        .sim_output();
608
609        flow.sim().exhaustive(async || {
610            input_send.send(10);
611            // First tick: prev is None, so output is -1
612            assert_eq!(out_recv.next().await, -1);
613
614            input_send.send(20);
615            // Second tick: prev is Some(10), so output is 10
616            assert_eq!(out_recv.next().await, 10);
617
618            input_send.send(30);
619            // Third tick: prev is Some(20), so output is 20
620            assert_eq!(out_recv.next().await, 20);
621        });
622    }
623
624    /// Test `use::state` with `source_iter` to initialize a stream state.
625    /// On the first tick, the state is the initial `[10, 20]` from `source_iter`.
626    /// On subsequent ticks, the state is the batch from the previous tick.
627    #[test]
628    fn sim_state_source_iter() {
629        let mut flow = FlowBuilder::new();
630        let node = flow.process::<()>();
631
632        let (input_send, input) = node.sim_input::<i32, _, _>();
633
634        let out_recv = sliced! {
635            let batch = use::batch(input, nondet!(/** test */));
636            let mut items = use::state(|l| l.source_iter(q!([10, 20])));
637
638            // Output the current state, then replace it with the batch
639            let output = items.clone();
640            items = batch;
641            output
642        }
643        .sim_output();
644
645        flow.sim().exhaustive(async || {
646            input_send.send(3);
647            // First tick: items = initial [10, 20], output = [10, 20]
648            let mut results = vec![];
649            results.push(out_recv.next().await);
650            results.push(out_recv.next().await);
651            results.sort();
652            assert_eq!(results, vec![10, 20]);
653
654            input_send.send(4);
655            // Second tick: items = [3] (from previous batch), output = [3]
656            assert_eq!(out_recv.next().await, 3);
657
658            input_send.send(5);
659            // Third tick: items = [4] (from previous batch), output = [4]
660            assert_eq!(out_recv.next().await, 4);
661        });
662    }
663
664    /// Test atomic slicing with keyed streams.
665    #[test]
666    fn sim_sliced_atomic_keyed_stream() {
667        let mut flow = FlowBuilder::new();
668        let node = flow.process::<()>();
669
670        let (input_send, input) = node.sim_input::<(i32, i32), _, _>();
671        let atomic_keyed_input = input.into_keyed().atomic();
672        let accumulated_inputs = atomic_keyed_input
673            .clone()
674            .assume_ordering(nondet!(/** Test */))
675            .fold(
676                q!(|| 0),
677                q!(|curr, new| {
678                    *curr += new;
679                }),
680            );
681
682        let out_recv = sliced! {
683            let atomic_keyed_input = use::atomic(atomic_keyed_input, nondet!(/** test */));
684            let accumulated_inputs = use::atomic(accumulated_inputs, nondet!(/** test */));
685            accumulated_inputs.join_keyed_stream(atomic_keyed_input)
686                .map(q!(|(sum, _input)| sum))
687                .entries()
688        }
689        .assume_ordering_trusted(nondet!(/** test */))
690        .sim_output();
691
692        flow.sim().exhaustive(async || {
693            input_send.send((1, 1));
694            assert_eq!(out_recv.next().await, (1, 1));
695
696            input_send.send((1, 2));
697            assert_eq!(out_recv.next().await, (1, 3));
698
699            input_send.send((2, 1));
700            assert_eq!(out_recv.next().await, (2, 1));
701
702            input_send.send((1, 3));
703            assert_eq!(out_recv.next().await, (1, 6));
704        });
705    }
706
707    /// A configuration value that is `Clone` but not `Copy`.
708    #[derive(Clone)]
709    pub struct Config {
710        pub offset: i32,
711    }
712
713    /// Test `use::clone` with a bounded singleton, read from several `q!` closures (via
714    /// `by_ref`) on every tick (not just the first).
715    #[test]
716    fn sim_clone_singleton() {
717        let mut flow = FlowBuilder::new();
718        let node = flow.process::<()>();
719
720        let (input_send, input) = node.sim_input::<i32, _, _>();
721        let config = node.singleton(q!(Config { offset: 100 }));
722
723        let out_recv = sliced! {
724            let batch = use::batch(input, nondet!(/** test */));
725            let config = use::clone(config);
726
727            let config = config.by_ref();
728            batch
729                .filter(q!(|x| *x < config.offset))
730                .map(q!(|x| x + config.offset))
731        }
732        .sim_output();
733
734        flow.sim().exhaustive(async || {
735            input_send.send(1);
736            assert_eq!(out_recv.next().await, 101);
737
738            input_send.send(200);
739            input_send.send(2);
740            assert_eq!(out_recv.next().await, 102);
741
742            input_send.send(3);
743            assert_eq!(out_recv.next().await, 103);
744        });
745    }
746
747    /// Test `use::clone` with bounded optionals, both present and absent.
748    #[test]
749    fn sim_clone_optional() {
750        let mut flow = FlowBuilder::new();
751        let node = flow.process::<()>();
752
753        let (input_send, input) = node.sim_input::<i32, _, _>();
754        let present = node.singleton(q!(5)).filter(q!(|x| *x > 0));
755        let absent = node.singleton(q!(5)).filter(q!(|x| *x > 10));
756
757        let out_recv = sliced! {
758            let batch = use::batch(input, nondet!(/** test */));
759            let present = use::clone(present);
760            let absent = use::clone(absent);
761
762            batch
763                .cross_singleton(present.into_singleton())
764                .cross_singleton(absent.into_singleton())
765                .map(q!(|((x, present), absent)| (
766                    x + present.unwrap_or(-1),
767                    absent.unwrap_or(-1)
768                )))
769        }
770        .sim_output();
771
772        flow.sim().exhaustive(async || {
773            input_send.send(1);
774            assert_eq!(out_recv.next().await, (6, -1));
775
776            input_send.send(2);
777            assert_eq!(out_recv.next().await, (7, -1));
778        });
779    }
780
781    /// Test `use::clone` on a cluster, where the other sliced inputs drop consistency.
782    #[test]
783    fn sim_clone_cluster() {
784        let mut flow = FlowBuilder::new();
785        let cluster = flow.cluster::<(), u32>();
786
787        let (input_send, input) = cluster.sim_input::<i32, _, _>();
788        let config = cluster.singleton(q!(Config { offset: 100 }));
789
790        let out_recv = sliced! {
791            let batch = use::batch(input, nondet!(/** test */));
792            let config = use::clone(config);
793            batch
794                .cross_singleton(config)
795                .map(q!(|(x, config)| x + config.offset))
796        }
797        .sim_cluster_output();
798
799        flow.sim()
800            .with_cluster_size(&cluster, 2)
801            .exhaustive(async || {
802                input_send.send(0, 1);
803                input_send.send(1, 2);
804                assert_eq!(out_recv.next(0).await, 101);
805                assert_eq!(out_recv.next(1).await, 102);
806
807                input_send.send(0, 3);
808                assert_eq!(out_recv.next(0).await, 103);
809            });
810    }
811
812    /// `use::clone` introduces no non-deterministic choices: the simulator explores exactly as
813    /// many instances as for the same flow without it.
814    #[test]
815    fn sim_clone_no_extra_instances() {
816        let with_clone = {
817            let mut flow = FlowBuilder::new();
818            let node = flow.process::<()>();
819
820            let input = node.source_iter(q!(vec![1, 2, 3, 4]));
821            let offset = node.singleton(q!(100));
822
823            let out_recv = sliced! {
824                let batch = use::batch(input, nondet!(/** test */));
825                let offset = use::clone(offset);
826                batch.cross_singleton(offset).map(q!(|(x, offset)| x + offset))
827            }
828            .sim_output();
829
830            flow.sim().exhaustive(async || {
831                out_recv.assert_yields_only([101, 102, 103, 104]).await;
832            })
833        };
834
835        let without_clone = {
836            let mut flow = FlowBuilder::new();
837            let node = flow.process::<()>();
838
839            let input = node.source_iter(q!(vec![1, 2, 3, 4]));
840
841            let out_recv = sliced! {
842                let batch = use::batch(input, nondet!(/** test */));
843                batch.map(q!(|x| x + 100))
844            }
845            .sim_output();
846
847            flow.sim().exhaustive(async || {
848                out_recv.assert_yields_only([101, 102, 103, 104]).await;
849            })
850        };
851
852        assert_eq!(with_clone, without_clone);
853        assert_eq!(
854            with_clone,
855            8 // 2^3 ways to split up the 4 elements into non-empty batches
856        );
857    }
858}