Skip to main content

hydro_lang/live_collections/
keyed_singleton.rs

1//! Definitions for the [`KeyedSingleton`] live collection.
2
3use std::cell::RefCell;
4use std::collections::HashMap;
5use std::hash::Hash;
6use std::marker::PhantomData;
7use std::ops::Deref;
8use std::rc::Rc;
9
10use sealed::sealed;
11use stageleft::{IntoQuotedMut, QuotedWithContext, q};
12
13use super::OperatorContext;
14use super::boundedness::{Bounded, Boundedness, IsBounded, Unbounded};
15use super::keyed_stream::KeyedStream;
16use super::optional::Optional;
17use super::singleton::Singleton;
18use super::sliced::sliced;
19use super::stream::{ExactlyOnce, NoOrder, Stream, TotalOrder};
20use crate::compile::builder::{CycleId, FlowState};
21use crate::compile::ir::{
22    CollectionKind, HydroIrOpMetadata, HydroNode, HydroRoot, KeyedSingletonBoundKind, SharedNode,
23};
24#[cfg(stageleft_runtime)]
25use crate::forward_handle::{CycleCollection, ReceiverComplete};
26use crate::forward_handle::{ForwardRef, TickCycle};
27use crate::live_collections::stream::{Ordering, Retries};
28#[cfg(stageleft_runtime)]
29use crate::location::dynamic::{DynLocation, LocationId};
30use crate::location::tick::DeferTick;
31use crate::location::{Atomic, Location, Tick, TopLevel, check_matching_location};
32use crate::manual_expr::ManualExpr;
33use crate::nondet::{NonDet, nondet};
34use crate::properties::manual_proof;
35
36/// A marker trait indicating which components of a [`KeyedSingleton`] may change.
37///
38/// In addition to [`Bounded`] (all entries are fixed) and [`Unbounded`] (entries may be added /
39/// changed, but not removed), this also includes an additional variant [`BoundedValue`], which
40/// indicates that entries may be added over time, but once an entry is added it will never be
41/// removed and its value will never change.
42pub trait KeyedSingletonBound {
43    /// The [`Boundedness`] of the [`Stream`] underlying the keyed singleton.
44    type UnderlyingBound: Boundedness;
45    /// The [`Boundedness`] of each entry's value; [`Bounded`] means it is immutable.
46    type ValueBound: Boundedness;
47
48    /// The type of the keyed singleton if the value for each key is immutable.
49    type WithBoundedValue: KeyedSingletonBound<
50            UnderlyingBound = Self::UnderlyingBound,
51            ValueBound = Bounded,
52            EraseMonotonic = Self::WithBoundedValue,
53        >;
54
55    /// The [`Boundedness`] of this [`Singleton`] if it is produced from a [`KeyedStream`] with [`Self`] boundedness.
56    type KeyedStreamToMonotone: KeyedSingletonBound<UnderlyingBound = Self::UnderlyingBound, ValueBound = Self::ValueBound>;
57
58    /// The [`Boundedness`] of the keyed singleton produced by folding a [`KeyedStream`] with
59    /// [`Self`] boundedness when the aggregation does *not* have a monotonicity proof.
60    ///
61    /// Without a monotonicity proof, the per-key values may change arbitrarily, so an unbounded
62    /// input collapses to [`MonotonicKeys`] (keys are still only added, never removed).
63    type KeyedStreamToNonMonotone: KeyedSingletonBound<UnderlyingBound = Self::UnderlyingBound, ValueBound = Self::ValueBound>;
64
65    /// The type of the keyed singleton if the value for each key is no longer monotonic.
66    type EraseMonotonic: KeyedSingletonBound<UnderlyingBound = Self::UnderlyingBound, ValueBound = Self::ValueBound>;
67
68    /// The type of each per-key update value in this keyed singleton's top-level update feed
69    /// (see [`CollectionKind::root_repr_is_tombstoned_update_feed`](crate::compile::ir::CollectionKind::root_repr_is_tombstoned_update_feed)):
70    /// `Option<V>` (where `None` is a tombstone removing the key) for [`Unbounded`] keyed
71    /// singletons, which may remove keys, and plain `V` otherwise.
72    type UpdateValue<V>;
73
74    /// Returns the [`KeyedSingletonBoundKind`] corresponding to this type.
75    fn bound_kind() -> KeyedSingletonBoundKind;
76}
77
78impl KeyedSingletonBound for Unbounded {
79    type UnderlyingBound = Unbounded;
80    type ValueBound = Unbounded;
81    type WithBoundedValue = BoundedValue;
82    type KeyedStreamToMonotone = MonotonicValue;
83    type KeyedStreamToNonMonotone = MonotonicKeys;
84    type EraseMonotonic = Unbounded;
85    type UpdateValue<V> = Option<V>;
86
87    fn bound_kind() -> KeyedSingletonBoundKind {
88        KeyedSingletonBoundKind::Unbounded
89    }
90}
91
92impl KeyedSingletonBound for Bounded {
93    type UnderlyingBound = Bounded;
94    type ValueBound = Bounded;
95    type WithBoundedValue = Bounded;
96    type KeyedStreamToMonotone = Bounded;
97    type KeyedStreamToNonMonotone = Bounded;
98    type EraseMonotonic = Bounded;
99    type UpdateValue<V> = V;
100
101    fn bound_kind() -> KeyedSingletonBoundKind {
102        KeyedSingletonBoundKind::Bounded
103    }
104}
105
106/// A variation of boundedness specific to [`KeyedSingleton`], which indicates that once a key appears,
107/// its value is bounded and will never change, but new entries may appear asynchronously
108pub enum BoundedValue {}
109
110impl KeyedSingletonBound for BoundedValue {
111    type UnderlyingBound = Unbounded;
112    type ValueBound = Bounded;
113    type WithBoundedValue = BoundedValue;
114    type KeyedStreamToMonotone = BoundedValue;
115    type KeyedStreamToNonMonotone = BoundedValue;
116    type EraseMonotonic = BoundedValue;
117    type UpdateValue<V> = V;
118
119    fn bound_kind() -> KeyedSingletonBoundKind {
120        KeyedSingletonBoundKind::BoundedValue
121    }
122}
123
124/// A variation of boundedness specific to [`KeyedSingleton`], which indicates that once a key appears,
125/// it will never be removed, and the corresponding value will only increase monotonically.
126pub enum MonotonicValue {}
127
128impl KeyedSingletonBound for MonotonicValue {
129    type UnderlyingBound = Unbounded;
130    type ValueBound = Unbounded;
131    type WithBoundedValue = BoundedValue;
132    type KeyedStreamToMonotone = MonotonicValue;
133    type KeyedStreamToNonMonotone = MonotonicKeys;
134    type EraseMonotonic = MonotonicKeys;
135    type UpdateValue<V> = V;
136
137    fn bound_kind() -> KeyedSingletonBoundKind {
138        KeyedSingletonBoundKind::MonotonicValue
139    }
140}
141
142/// A variation of boundedness specific to [`KeyedSingleton`], which indicates that once a key
143/// appears, it will never be removed, but the corresponding value may change arbitrarily.
144pub enum MonotonicKeys {}
145
146impl KeyedSingletonBound for MonotonicKeys {
147    type UnderlyingBound = Unbounded;
148    type ValueBound = Unbounded;
149    type WithBoundedValue = BoundedValue;
150    type KeyedStreamToMonotone = MonotonicKeys;
151    type KeyedStreamToNonMonotone = MonotonicKeys;
152    type EraseMonotonic = MonotonicKeys;
153    type UpdateValue<V> = V;
154
155    fn bound_kind() -> KeyedSingletonBoundKind {
156        KeyedSingletonBoundKind::MonotonicKeys
157    }
158}
159
160#[sealed]
161#[diagnostic::on_unimplemented(
162    message = "the keyed singleton must have monotonic values (`MonotonicValue`) or be bounded (`Bounded`), but has bound `{Self}`",
163    label = "required here",
164    note = "strengthen the monotonicity upstream, or consider a different API",
165    note = "to intentionally process a non-deterministic snapshot or batch, you may want to use a `sliced!` region; this introduces non-determinism, so avoid it unless necessary"
166)]
167/// Marker trait that is implemented for [`KeyedSingletonBound`] types whose per-key values
168/// are monotonically non-decreasing (or bounded).
169pub trait IsKeyedMonotonic: KeyedSingletonBound {}
170
171#[sealed]
172#[diagnostic::do_not_recommend]
173impl IsKeyedMonotonic for MonotonicValue {}
174
175#[sealed]
176#[diagnostic::do_not_recommend]
177impl IsKeyedMonotonic for BoundedValue {}
178
179#[sealed]
180#[diagnostic::do_not_recommend]
181impl<B: IsBounded + KeyedSingletonBound> IsKeyedMonotonic for B {}
182
183#[sealed]
184#[diagnostic::on_unimplemented(
185    message = "`{Self}` keyed singletons cannot be snapshotted: each entry's value is final once it appears, so use `batch` to observe the new entries instead",
186    label = "required here"
187)]
188/// Marker trait for the [`KeyedSingletonBound`] types that support
189/// [`KeyedSingleton::snapshot`]: those whose entries may change over time ([`Unbounded`],
190/// [`MonotonicKeys`], [`MonotonicValue`]) and fully [`Bounded`] keyed singletons (whose
191/// complete contents are observed on every tick).
192///
193/// [`BoundedValue`] is excluded: each of its entries is final once it appears, so it is windowed
194/// into a tick with [`KeyedSingleton::batch`], which observes just the *new* entries.
195pub trait KeyedSingletonSnapshotBound: KeyedSingletonBound {}
196
197#[sealed]
198impl KeyedSingletonSnapshotBound for Unbounded {}
199
200#[sealed]
201impl KeyedSingletonSnapshotBound for MonotonicKeys {}
202
203#[sealed]
204impl KeyedSingletonSnapshotBound for MonotonicValue {}
205
206#[sealed]
207impl KeyedSingletonSnapshotBound for Bounded {}
208
209/// Mapping from keys of type `K` to values of type `V`.
210///
211/// Keyed Singletons capture an asynchronously updated mapping from keys of the `K` to values of
212/// type `V`, where the order of keys is non-deterministic. In addition to the standard boundedness
213/// variants ([`Bounded`] for finite and immutable, [`Unbounded`] for asynchronously changing),
214/// keyed singletons can use [`BoundedValue`] to declare that new keys may be added over time, but
215/// keys cannot be removed and the value for each key is immutable.
216///
217/// Type Parameters:
218/// - `K`: the type of the key for each entry
219/// - `V`: the type of the value for each entry
220/// - `Loc`: the [`Location`] where the keyed singleton is materialized
221/// - `Bound`: tracks whether the entries are:
222///     - [`Bounded`] (local and finite)
223///     - [`Unbounded`] (asynchronous with entries added / removed / changed over time)
224///     - [`BoundedValue`] (asynchronous with immutable values for each key and no removals)
225pub struct KeyedSingleton<K, V, Loc, Bound: KeyedSingletonBound> {
226    pub(crate) location: Loc,
227    pub(crate) ir_node: Rc<RefCell<HydroNode>>,
228    pub(crate) flow_state: FlowState,
229
230    _phantom: PhantomData<(K, V, Loc, Bound)>,
231}
232
233impl<K, V, L, B: KeyedSingletonBound> Drop for KeyedSingleton<K, V, L, B> {
234    fn drop(&mut self) {
235        let ir_node = self.ir_node.replace(HydroNode::Placeholder);
236        if !matches!(ir_node, HydroNode::Placeholder) && !ir_node.is_shared_with_others() {
237            self.flow_state.borrow_mut().try_push_root(HydroRoot::Null {
238                input: Box::new(ir_node),
239                op_metadata: HydroIrOpMetadata::new(),
240            });
241        }
242    }
243}
244
245impl<'a, K: Clone, V: Clone, Loc: Location<'a>, Bound: KeyedSingletonBound> Clone
246    for KeyedSingleton<K, V, Loc, Bound>
247{
248    fn clone(&self) -> Self {
249        if !matches!(self.ir_node.borrow().deref(), HydroNode::Tee { .. }) {
250            let orig_ir_node = self.ir_node.replace(HydroNode::Placeholder);
251            *self.ir_node.borrow_mut() = HydroNode::Tee {
252                inner: SharedNode(Rc::new(RefCell::new(orig_ir_node))),
253                metadata: self.location.new_node_metadata(Self::collection_kind()),
254            };
255        }
256
257        if let HydroNode::Tee { inner, metadata } = self.ir_node.borrow().deref() {
258            KeyedSingleton {
259                location: self.location.clone(),
260                flow_state: self.flow_state.clone(),
261                ir_node: super::tracked_ir_node(
262                    &self.flow_state,
263                    HydroNode::Tee {
264                        inner: SharedNode(inner.0.clone()),
265                        metadata: metadata.clone(),
266                    },
267                ),
268                _phantom: PhantomData,
269            }
270        } else {
271            unreachable!()
272        }
273    }
274}
275
276impl<'a, K, V, L, B: KeyedSingletonBound> CycleCollection<'a, ForwardRef>
277    for KeyedSingleton<K, V, L, B>
278where
279    L: Location<'a>,
280{
281    type Location = L;
282
283    fn create_source(cycle_id: CycleId, location: L) -> Self {
284        let flow_state = location.flow_state().clone();
285        KeyedSingleton {
286            ir_node: super::tracked_ir_node(
287                &flow_state,
288                HydroNode::CycleSource {
289                    cycle_id,
290                    metadata: location.new_node_metadata(Self::collection_kind()),
291                },
292            ),
293            flow_state,
294            location,
295            _phantom: PhantomData,
296        }
297    }
298}
299
300impl<'a, K, V, L> CycleCollection<'a, TickCycle> for KeyedSingleton<K, V, Tick<L>, Bounded>
301where
302    L: Location<'a>,
303{
304    type Location = Tick<L>;
305
306    fn create_source(cycle_id: CycleId, location: Tick<L>) -> Self {
307        KeyedSingleton::new(
308            location.clone(),
309            HydroNode::CycleSource {
310                cycle_id,
311                metadata: location.new_node_metadata(Self::collection_kind()),
312            },
313        )
314    }
315}
316
317impl<'a, K, V, L> DeferTick for KeyedSingleton<K, V, Tick<L>, Bounded>
318where
319    L: Location<'a>,
320{
321    fn defer_tick(self) -> Self {
322        KeyedSingleton::defer_tick(self)
323    }
324}
325
326impl<'a, K, V, L, B: KeyedSingletonBound> ReceiverComplete<'a, ForwardRef>
327    for KeyedSingleton<K, V, L, B>
328where
329    L: Location<'a>,
330{
331    fn complete(self, cycle_id: CycleId, expected_location: LocationId) {
332        assert_eq!(
333            Location::id(&self.location),
334            expected_location,
335            "locations do not match"
336        );
337        self.location
338            .flow_state()
339            .borrow_mut()
340            .push_root(HydroRoot::CycleSink {
341                cycle_id,
342                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
343                op_metadata: HydroIrOpMetadata::new(),
344            });
345    }
346}
347
348impl<'a, K, V, L> ReceiverComplete<'a, TickCycle> for KeyedSingleton<K, V, Tick<L>, Bounded>
349where
350    L: Location<'a>,
351{
352    fn complete(self, cycle_id: CycleId, expected_location: LocationId) {
353        assert_eq!(
354            Location::id(&self.location),
355            expected_location,
356            "locations do not match"
357        );
358        self.location
359            .flow_state()
360            .borrow_mut()
361            .push_root(HydroRoot::CycleSink {
362                cycle_id,
363                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
364                op_metadata: HydroIrOpMetadata::new(),
365            });
366    }
367}
368
369impl<'a, K, V, L: Location<'a>, B: KeyedSingletonBound> KeyedSingleton<K, V, L, B> {
370    pub(crate) fn new(location: L, ir_node: HydroNode) -> Self {
371        debug_assert_eq!(ir_node.metadata().location_id, Location::id(&location));
372        debug_assert_eq!(ir_node.metadata().collection_kind, Self::collection_kind());
373
374        let flow_state = location.flow_state().clone();
375        let ir_node = super::tracked_ir_node(&flow_state, ir_node);
376        KeyedSingleton {
377            location,
378            flow_state,
379            ir_node,
380            _phantom: PhantomData,
381        }
382    }
383
384    /// Returns the [`Location`] where this keyed singleton is being materialized.
385    pub fn location(&self) -> &L {
386        &self.location
387    }
388
389    /// Weakens the consistency of this live collection to not guarantee any consistency across
390    /// cluster members (if this collection is on a cluster).
391    pub fn weaken_consistency(self) -> KeyedSingleton<K, V, L::DropConsistency, B>
392    where
393        L: Location<'a>,
394    {
395        if L::consistency()
396            .is_none_or(|c| c == crate::location::dynamic::ClusterConsistency::NoConsistency)
397        {
398            // already no consistency
399            KeyedSingleton::new(
400                self.location.drop_consistency(),
401                self.ir_node.replace(HydroNode::Placeholder),
402            )
403        } else {
404            KeyedSingleton::new(
405                self.location.drop_consistency(),
406                HydroNode::Cast {
407                    inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
408                    metadata: self
409                        .location
410                        .drop_consistency()
411                        .new_node_metadata(
412                            KeyedSingleton::<K, V, L::DropConsistency, B>::collection_kind(),
413                        ),
414                },
415            )
416        }
417    }
418
419    /// Casts this live collection to have the consistency guarantees specified in the given
420    /// location type parameter. The developer must ensure that the strengthened consistency
421    /// is actually guaranteed, via the proof field (see [`crate::prelude::manual_proof`]).
422    pub fn assert_has_consistency_of<L2: Location<'a, DropConsistency = L::DropConsistency>>(
423        self,
424        _proof: impl crate::properties::ConsistencyProof,
425    ) -> KeyedSingleton<K, V, L2, B>
426    where
427        L: Location<'a>,
428    {
429        if L::consistency() == L2::consistency() {
430            // already consistent
431            KeyedSingleton::new(
432                self.location.with_consistency_of(),
433                self.ir_node.replace(HydroNode::Placeholder),
434            )
435        } else {
436            KeyedSingleton::new(
437                self.location.with_consistency_of(),
438                HydroNode::AssertIsConsistent {
439                    inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
440                    trusted: false,
441                    metadata: self
442                        .location
443                        .clone()
444                        .with_consistency_of::<L2>()
445                        .new_node_metadata(KeyedSingleton::<K, V, L2, B>::collection_kind()),
446                },
447            )
448        }
449    }
450}
451
452#[cfg(stageleft_runtime)]
453fn key_count_inside_tick<'a, K, V, L: Location<'a>>(
454    me: KeyedSingleton<K, V, L, Bounded>,
455) -> Singleton<usize, L, Bounded> {
456    me.entries().count()
457}
458
459#[cfg(stageleft_runtime)]
460fn into_singleton_inside_tick<'a, K, V, L: Location<'a>>(
461    me: KeyedSingleton<K, V, L, Bounded>,
462) -> Singleton<HashMap<K, V>, L, Bounded>
463where
464    K: Eq + Hash,
465{
466    me.entries()
467        .assume_ordering_trusted(nondet!(
468            /// There is only one element associated with each key. The closure technically
469            /// isn't commutative in the case where both passed entries have the same key
470            /// but different values.
471            ///
472            /// In the future, we may want to have an `assume!(...)` statement in the UDF that
473            /// the key is never already present in the map.
474        ))
475        .fold(
476            q!(|| HashMap::new()),
477            q!(|map, (k, v)| {
478                map.insert(k, v);
479            }),
480        )
481}
482
483impl<'a, K, V, L: Location<'a>, B: KeyedSingletonBound> KeyedSingleton<K, V, L, B> {
484    pub(crate) fn collection_kind() -> CollectionKind {
485        CollectionKind::KeyedSingleton {
486            bound: B::bound_kind(),
487            key_type: stageleft::quote_type::<K>().into(),
488            value_type: stageleft::quote_type::<V>().into(),
489        }
490    }
491
492    /// Exposes this collection's top-level update feed as a stream whose elements are exactly
493    /// the feed's updates, in the order they were emitted.
494    ///
495    /// **Contract.** Relative to "every version of the collection, exactly once, in order", the
496    /// stream may *stutter* (repeat the current version, consecutively per key) and *skip*
497    /// (omit non-final versions); the final version is always eventually delivered. Which
498    /// versions appear depends on timing, so the caller's `nondet` must justify that its use is
499    /// invariant to stuttering and skipping (e.g. an idempotent "latest value" fold, or a
500    /// monotone threshold).
501    ///
502    /// **Simulator soundness.** The simulator emits every version exactly once and does not
503    /// explore skips, so a caller must never expose these updates (or anything derived from
504    /// them update-by-update) to user code or an output. It must route them into logic that
505    /// keeps the full trajectory of versions available and then through a simulator hook that
506    /// picks among them nondeterministically: fold them back into a singleton-like state that
507    /// is later snapshotted, or batch them into a tick. When combining several feeds, batch each
508    /// one into the same tick rather than interleaving them deterministically (e.g. with
509    /// `chain`), so the simulator explores every pairing of their versions. See
510    /// [`HydroNode::CastUpdateStream`] for the full contract.
511    ///
512    /// The collection must be located at a root (process or cluster) location.
513    ///
514    /// Each update is a `(key, value)` entry whose value is a
515    /// [`KeyedSingletonBound::UpdateValue`]: `Option<V>` (with `None` a tombstone removing the
516    /// key) for an [`Unbounded`] keyed singleton, and plain `V` otherwise. Updates are ordered
517    /// within each key; there is no ordering across keys.
518    pub(crate) fn into_update_stream(
519        self,
520        _nondet: NonDet,
521    ) -> KeyedStream<K, B::UpdateValue<V>, L::DropConsistency, Unbounded, TotalOrder, ExactlyOnce>
522    {
523        assert!(
524            self.location.id().is_root(),
525            "`into_update_stream` requires a root location, got {:?}",
526            self.location.id()
527        );
528        let target_location = self.location.drop_consistency();
529        KeyedStream::new(
530            target_location.clone(),
531            HydroNode::CastUpdateStream {
532                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
533                metadata: target_location.new_node_metadata(KeyedStream::<
534                    K,
535                    B::UpdateValue<V>,
536                    L::DropConsistency,
537                    Unbounded,
538                    TotalOrder,
539                    ExactlyOnce,
540                >::collection_kind()),
541            },
542        )
543    }
544
545    /// Transforms each value by invoking `f` on each element, with keys staying the same
546    /// after transformation. If you need access to the key, see [`KeyedSingleton::map_with_key`].
547    ///
548    /// If you do not want to modify the stream and instead only want to view
549    /// each item use [`KeyedSingleton::inspect`] instead.
550    ///
551    /// # Example
552    /// ```rust
553    /// # #[cfg(feature = "deploy")] {
554    /// # use hydro_lang::prelude::*;
555    /// # use futures::StreamExt;
556    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
557    /// let keyed_singleton = // { 1: 2, 2: 4 }
558    /// # process
559    /// #     .source_iter(q!(vec![(1, 2), (2, 4)]))
560    /// #     .into_keyed()
561    /// #     .first();
562    /// keyed_singleton.map(q!(|v| v + 1))
563    /// #   .entries()
564    /// # }, |mut stream| async move {
565    /// // { 1: 3, 2: 5 }
566    /// # let mut results = Vec::new();
567    /// # for _ in 0..2 {
568    /// #     results.push(stream.next().await.unwrap());
569    /// # }
570    /// # results.sort();
571    /// # assert_eq!(results, vec![(1, 3), (2, 5)]);
572    /// # }));
573    /// # }
574    /// ```
575    pub fn map<U, F>(
576        self,
577        f: impl IntoQuotedMut<'a, F, OperatorContext<L, B::UnderlyingBound>> + Copy,
578    ) -> KeyedSingleton<K, U, L, B::EraseMonotonic>
579    where
580        F: Fn(V) -> U + 'a,
581    {
582        let f: ManualExpr<F, _> =
583            ManualExpr::new(move |ctx: &OperatorContext<L, B::UnderlyingBound>| {
584                f.splice_fn1_ctx(ctx)
585            });
586        let map_f = q!({
587            let orig = f;
588            move |(k, v)| (k, orig(v))
589        })
590        .splice_fn1_ctx::<(K, V), (K, U)>(&OperatorContext::<L, B::UnderlyingBound>::new(
591            &self.location,
592        ))
593        .into();
594
595        KeyedSingleton::new(
596            self.location.clone(),
597            HydroNode::Map {
598                f: map_f,
599                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
600                metadata: self.location.new_node_metadata(KeyedSingleton::<
601                    K,
602                    U,
603                    L,
604                    B::EraseMonotonic,
605                >::collection_kind()),
606            },
607        )
608    }
609
610    /// Transforms each value by invoking `f` on each key-value pair, with keys staying the same
611    /// after transformation. Unlike [`KeyedSingleton::map`], this gives access to both the key and value.
612    ///
613    /// The closure `f` receives a tuple `(K, V)` containing both the key and value, and returns
614    /// the new value `U`. The key remains unchanged in the output.
615    ///
616    /// # Example
617    /// ```rust
618    /// # #[cfg(feature = "deploy")] {
619    /// # use hydro_lang::prelude::*;
620    /// # use futures::StreamExt;
621    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
622    /// let keyed_singleton = // { 1: 2, 2: 4 }
623    /// # process
624    /// #     .source_iter(q!(vec![(1, 2), (2, 4)]))
625    /// #     .into_keyed()
626    /// #     .first();
627    /// keyed_singleton.map_with_key(q!(|(k, v)| k + v))
628    /// #   .entries()
629    /// # }, |mut stream| async move {
630    /// // { 1: 3, 2: 6 }
631    /// # let mut results = Vec::new();
632    /// # for _ in 0..2 {
633    /// #     results.push(stream.next().await.unwrap());
634    /// # }
635    /// # results.sort();
636    /// # assert_eq!(results, vec![(1, 3), (2, 6)]);
637    /// # }));
638    /// # }
639    /// ```
640    pub fn map_with_key<U, F>(
641        self,
642        f: impl IntoQuotedMut<'a, F, OperatorContext<L, B::UnderlyingBound>> + Copy,
643    ) -> KeyedSingleton<K, U, L, B::EraseMonotonic>
644    where
645        F: Fn((K, V)) -> U + 'a,
646        K: Clone,
647    {
648        let f: ManualExpr<F, _> =
649            ManualExpr::new(move |ctx: &OperatorContext<L, B::UnderlyingBound>| {
650                f.splice_fn1_ctx(ctx)
651            });
652        let map_f = q!({
653            let orig = f;
654            move |(k, v)| {
655                let out = orig((Clone::clone(&k), v));
656                (k, out)
657            }
658        })
659        .splice_fn1_ctx::<(K, V), (K, U)>(&OperatorContext::<L, B::UnderlyingBound>::new(
660            &self.location,
661        ))
662        .into();
663
664        KeyedSingleton::new(
665            self.location.clone(),
666            HydroNode::Map {
667                f: map_f,
668                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
669                metadata: self.location.new_node_metadata(KeyedSingleton::<
670                    K,
671                    U,
672                    L,
673                    B::EraseMonotonic,
674                >::collection_kind()),
675            },
676        )
677    }
678
679    /// Gets the number of keys in the keyed singleton.
680    ///
681    /// The output singleton will be unbounded if the input is [`Unbounded`] or [`BoundedValue`],
682    /// since keys may be added / removed over time. When the set of keys changes, the count will
683    /// be asynchronously updated.
684    ///
685    /// # Example
686    /// ```rust
687    /// # #[cfg(feature = "deploy")] {
688    /// # use hydro_lang::prelude::*;
689    /// # use futures::StreamExt;
690    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
691    /// # let tick = process.tick();
692    /// let keyed_singleton = // { 1: "a", 2: "b", 3: "c" }
693    /// # process
694    /// #     .source_iter(q!(vec![(1, "a"), (2, "b"), (3, "c")]))
695    /// #     .into_keyed()
696    /// #     .batch(&tick, nondet!(/** test */))
697    /// #     .first();
698    /// keyed_singleton.key_count()
699    /// # .all_ticks()
700    /// # }, |mut stream| async move {
701    /// // 3
702    /// # assert_eq!(stream.next().await.unwrap(), 3);
703    /// # }));
704    /// # }
705    /// ```
706    pub fn key_count(self) -> Singleton<usize, L, B::UnderlyingBound>
707    where
708        K: Clone + Eq + Hash + 'a,
709    {
710        if B::ValueBound::BOUNDED {
711            let me: KeyedSingleton<K, V, L, B::WithBoundedValue> = KeyedSingleton {
712                location: self.location.clone(),
713                flow_state: self.flow_state.clone(),
714                ir_node: super::tracked_ir_node(
715                    &self.flow_state,
716                    self.ir_node.replace(HydroNode::Placeholder),
717                ),
718                _phantom: PhantomData,
719            };
720
721            me.entries().count().ignore_monotonic()
722        } else if self.location.id().is_root() {
723            let location = self.location.clone();
724            let ir_node = self.ir_node.replace(HydroNode::Placeholder);
725            // Apply the updates, in order per key, to the set of current keys (removed keys are
726            // dropped, so it holds only the current keys), emitting its size after each update.
727            // The latest emitted size is the key count (0 before any updates).
728            let counts = if B::bound_kind() == KeyedSingletonBoundKind::Unbounded {
729                let me: KeyedSingleton<K, V, L, Unbounded> =
730                    KeyedSingleton::new(location.clone(), ir_node);
731                me.into_update_stream(nondet!(
732                    /// Applying an update to the set of current keys is idempotent, so
733                    /// stuttering does not change it, and the set only depends on each key's
734                    /// latest update, so skipping intermediate updates only skips intermediate
735                    /// counts.
736                ))
737                .entries_partially_ordered(nondet!(
738                    /// Updates are applied in order within each key; updates to different keys
739                    /// commute, so the interleaving across keys only affects intermediate counts.
740                ))
741                .scan(
742                    q!(|| std::collections::HashSet::new()),
743                    q!(|keys, (k, update)| {
744                        if update.is_some() {
745                            keys.insert(k);
746                        } else {
747                            keys.remove(&k);
748                        }
749                        Some(keys.len())
750                    }),
751                )
752            } else {
753                let me: KeyedSingleton<K, V, L, MonotonicKeys> =
754                    KeyedSingleton::new(location.clone(), ir_node);
755                me.into_update_stream(nondet!(
756                    /// Keys are never removed and only their presence is observed, which
757                    /// neither stuttering nor skipping intermediate updates can change.
758                ))
759                .entries_partially_ordered(nondet!(
760                    /// Set insertion commutes, so the interleaving across keys only affects
761                    /// intermediate counts.
762                ))
763                .scan(
764                    q!(|| std::collections::HashSet::new()),
765                    q!(|keys, (k, _)| {
766                        keys.insert(k);
767                        Some(keys.len())
768                    }),
769                )
770            };
771            let count: Singleton<usize, _, Unbounded> =
772                counts.fold(q!(|| 0usize), q!(|count, latest| *count = latest));
773            // Re-tag the node from the concrete `Unbounded` singleton to the `B::UnderlyingBound`
774            // that this method returns (equal at runtime for this branch).
775            Singleton::new(location, count.ir_node.replace(HydroNode::Placeholder))
776        } else if L::is_top_level()
777            && let Some(tick) = self.location.try_tick()
778            && (B::bound_kind() == KeyedSingletonBoundKind::Unbounded
779                || B::bound_kind() == KeyedSingletonBoundKind::MonotonicKeys
780                || B::bound_kind() == KeyedSingletonBoundKind::MonotonicValue)
781        {
782            // A non-root top-level location (an atomic region): snapshot into its own tick.
783            let location = self.location.clone();
784            let ir_node = self.ir_node.replace(HydroNode::Placeholder);
785            let me: KeyedSingleton<K, V, L, MonotonicKeys> =
786                KeyedSingleton::new(location.clone(), ir_node);
787
788            // The key count is folded with an initial value, so it is always present (0 when
789            // there are no keys). `latest()` is null until the producing tick first runs; fill
790            // that prefix with 0 to recover an always-present count. The atomic region is fused
791            // into its tick's loop, so this is a plain per-firing `or`.
792            let out = super::optional::unwrap_or_in_atomic(
793                key_count_inside_tick(me.snapshot(&tick, nondet!(/** eventually stabilizes */)))
794                    .latest(),
795                location.singleton(q!(0usize)),
796            );
797            // Re-tag the node from the concrete `Unbounded` singleton to the `B::UnderlyingBound`
798            // that this method returns (equal at runtime for this branch).
799            Singleton::new(location, out.ir_node.replace(HydroNode::Placeholder))
800        } else {
801            panic!("BoundedValue or Unbounded KeyedSingleton inside a tick, not supported");
802        }
803    }
804
805    /// Converts this keyed singleton into a [`Singleton`] containing a `HashMap` from keys to values.
806    ///
807    /// As the values for each key are updated asynchronously, the `HashMap` will be updated
808    /// asynchronously as well.
809    ///
810    /// # Example
811    /// ```rust
812    /// # #[cfg(feature = "deploy")] {
813    /// # use hydro_lang::prelude::*;
814    /// # use futures::StreamExt;
815    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
816    /// let keyed_singleton = // { 1: "a", 2: "b", 3: "c" }
817    /// # process
818    /// #     .source_iter(q!(vec![(1, "a".to_owned()), (2, "b".to_owned()), (3, "c".to_owned())]))
819    /// #     .into_keyed()
820    /// #     .batch(&process.tick(), nondet!(/** test */))
821    /// #     .first();
822    /// keyed_singleton.into_singleton()
823    /// # .all_ticks()
824    /// # }, |mut stream| async move {
825    /// // { 1: "a", 2: "b", 3: "c" }
826    /// # assert_eq!(stream.next().await.unwrap(), vec![(1, "a".to_owned()), (2, "b".to_owned()), (3, "c".to_owned())].into_iter().collect());
827    /// # }));
828    /// # }
829    /// ```
830    pub fn into_singleton(self) -> Singleton<HashMap<K, V>, L, B::UnderlyingBound>
831    where
832        K: Eq + Hash + Clone + 'a,
833        V: Clone + 'a,
834    {
835        if B::ValueBound::BOUNDED {
836            let me: KeyedSingleton<K, V, L, B::WithBoundedValue> = KeyedSingleton {
837                location: self.location.clone(),
838                flow_state: self.flow_state.clone(),
839                ir_node: super::tracked_ir_node(
840                    &self.flow_state,
841                    self.ir_node.replace(HydroNode::Placeholder),
842                ),
843                _phantom: PhantomData,
844            };
845
846            me.entries()
847                .assume_ordering_trusted(nondet!(
848                    /// There is only one element associated with each key. The closure technically
849                    /// isn't commutative in the case where both passed entries have the same key
850                    /// but different values.
851                    ///
852                    /// In the future, we may want to have an `assume!(...)` statement in the UDF that
853                    /// the key is never already present in the map.
854                ))
855                .fold(
856                    q!(|| HashMap::new()),
857                    q!(|map, (k, v)| {
858                        // TODO(shadaj): make this commutative but really-debug-assert that there is no key overlap
859                        map.insert(k, v);
860                    }),
861                )
862        } else if self.location.id().is_root() {
863            let location = self.location.clone();
864            let ir_node = self.ir_node.replace(HydroNode::Placeholder);
865            // Apply the updates, in order per key, to the current map (empty before any updates).
866            let map: Singleton<HashMap<K, V>, _, Unbounded> =
867                if B::bound_kind() == KeyedSingletonBoundKind::Unbounded {
868                    let me: KeyedSingleton<K, V, L, Unbounded> =
869                        KeyedSingleton::new(location.clone(), ir_node);
870                    me.into_update_stream(nondet!(
871                        /// Applying an update to the map is idempotent, so stuttering does not
872                        /// change it, and the map only depends on each key's latest update, so
873                        /// skipping intermediate updates only skips intermediate maps.
874                    ))
875                    .entries_partially_ordered(nondet!(
876                        /// Updates are applied in order within each key; updates to different
877                        /// keys commute, so the interleaving across keys only affects
878                        /// intermediate maps.
879                    ))
880                    .fold(
881                        q!(|| HashMap::new()),
882                        q!(|map, (k, update)| {
883                            match update {
884                                Some(v) => {
885                                    map.insert(k, v);
886                                }
887                                None => {
888                                    map.remove(&k);
889                                }
890                            }
891                        }),
892                    )
893                } else {
894                    let me: KeyedSingleton<K, V, L, MonotonicKeys> =
895                        KeyedSingleton::new(location.clone(), ir_node);
896                    me.into_update_stream(nondet!(
897                        /// Applying an update to the map is idempotent, so stuttering does not
898                        /// change it, and the map only depends on each key's latest update, so
899                        /// skipping intermediate updates only skips intermediate maps.
900                    ))
901                    .entries_partially_ordered(nondet!(
902                        /// Updates are applied in order within each key; updates to different
903                        /// keys commute, so the interleaving across keys only affects
904                        /// intermediate maps.
905                    ))
906                    .fold(
907                        q!(|| HashMap::new()),
908                        q!(|map, (k, v)| {
909                            map.insert(k, v);
910                        }),
911                    )
912                };
913            Singleton::new(location, map.ir_node.replace(HydroNode::Placeholder))
914        } else if L::is_top_level()
915            && let Some(tick) = self.location.try_tick()
916            && (B::bound_kind() == KeyedSingletonBoundKind::Unbounded
917                || B::bound_kind() == KeyedSingletonBoundKind::MonotonicKeys
918                || B::bound_kind() == KeyedSingletonBoundKind::MonotonicValue)
919        {
920            // A non-root top-level location (an atomic region): snapshot into its own tick.
921            let location = self.location.clone();
922            let ir_node = self.ir_node.replace(HydroNode::Placeholder);
923            let me: KeyedSingleton<K, V, L, MonotonicKeys> =
924                KeyedSingleton::new(location.clone(), ir_node);
925
926            // The map is folded with an initial value, so it is always present (empty when
927            // there are no keys). `latest()` is null until the producing tick first runs; fill
928            // that prefix with an empty map to recover an always-present map.
929            let out = super::optional::unwrap_or_in_atomic(
930                into_singleton_inside_tick(
931                    me.snapshot(&tick, nondet!(/** eventually stabilizes */)),
932                )
933                .latest(),
934                location.singleton(q!(HashMap::new())),
935            );
936            // Re-tag the node from the concrete `Unbounded` singleton to the `B::UnderlyingBound`
937            // that this method returns (equal at runtime for this branch).
938            Singleton::new(location, out.ir_node.replace(HydroNode::Placeholder))
939        } else {
940            panic!("BoundedValue or Unbounded KeyedSingleton inside a tick, not supported");
941        }
942    }
943
944    /// An operator which allows you to "name" a `HydroNode`.
945    /// This is only used for testing, to correlate certain `HydroNode`s with IDs.
946    pub fn ir_node_named(self, name: &str) -> KeyedSingleton<K, V, L, B> {
947        {
948            let mut node = self.ir_node.borrow_mut();
949            let metadata = node.metadata_mut();
950            metadata.tag = Some(name.to_owned());
951        }
952        self
953    }
954
955    /// Strengthens the boundedness guarantee to `Bounded`, given that `B: IsBounded`, which
956    /// implies that `B == Bounded`.
957    pub fn make_bounded(self) -> KeyedSingleton<K, V, L, Bounded>
958    where
959        B: IsBounded,
960    {
961        KeyedSingleton::new(
962            self.location.clone(),
963            self.ir_node.replace(HydroNode::Placeholder),
964        )
965    }
966
967    /// Gets the value associated with a specific key from the keyed singleton.
968    /// Returns `None` if the key is `None` or there is no associated value.
969    ///
970    /// # Example
971    /// ```rust
972    /// # #[cfg(feature = "deploy")] {
973    /// # use hydro_lang::prelude::*;
974    /// # use futures::StreamExt;
975    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
976    /// let tick = process.tick();
977    /// let keyed_data = process
978    ///     .source_iter(q!(vec![(1, 2), (2, 3)]))
979    ///     .into_keyed()
980    ///     .batch(&tick, nondet!(/** test */))
981    ///     .first();
982    /// let key = tick.singleton(q!(1));
983    /// keyed_data.get(key).all_ticks()
984    /// # }, |mut stream| async move {
985    /// // 2
986    /// # assert_eq!(stream.next().await.unwrap(), 2);
987    /// # }));
988    /// # }
989    /// ```
990    pub fn get(self, key: impl Into<Optional<K, L, Bounded>>) -> Optional<V, L, Bounded>
991    where
992        B: IsBounded,
993        K: Hash + Eq + Clone,
994        V: Clone,
995    {
996        self.make_bounded()
997            .into_keyed_stream()
998            .get(key)
999            .cast_at_most_one_element()
1000    }
1001
1002    /// Emit a keyed stream containing keys shared between the keyed singleton and the
1003    /// keyed stream, where each value in the output keyed stream is a tuple of
1004    /// (the keyed singleton's value, the keyed stream's value).
1005    ///
1006    /// # Example
1007    /// ```rust
1008    /// # #[cfg(feature = "deploy")] {
1009    /// # use hydro_lang::prelude::*;
1010    /// # use futures::StreamExt;
1011    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1012    /// let tick = process.tick();
1013    /// let keyed_data = process
1014    ///     .source_iter(q!(vec![(1, 10), (2, 20)]))
1015    ///     .into_keyed()
1016    ///     .batch(&tick, nondet!(/** test */))
1017    ///     .first();
1018    /// let other_data = process
1019    ///     .source_iter(q!(vec![(1, 100), (2, 200), (1, 101)]))
1020    ///     .into_keyed()
1021    ///     .batch(&tick, nondet!(/** test */));
1022    /// keyed_data.join_keyed_stream(other_data).entries().all_ticks()
1023    /// # }, |mut stream| async move {
1024    /// // { 1: [(10, 100), (10, 101)], 2: [(20, 200)] } in any order
1025    /// # let mut results = vec![];
1026    /// # for _ in 0..3 {
1027    /// #     results.push(stream.next().await.unwrap());
1028    /// # }
1029    /// # results.sort();
1030    /// # assert_eq!(results, vec![(1, (10, 100)), (1, (10, 101)), (2, (20, 200))]);
1031    /// # }));
1032    /// # }
1033    /// ```
1034    pub fn join_keyed_stream<O2: Ordering, R2: Retries, V2, B2: Boundedness>(
1035        self,
1036        other: KeyedStream<K, V2, L, B2, O2, R2>,
1037    ) -> KeyedStream<K, (V, V2), L, B2, O2, R2>
1038    where
1039        B: IsBounded,
1040        K: Eq + Hash + Clone,
1041        V: Clone,
1042        V2: Clone,
1043    {
1044        // TODO(shadaj): if DFIR guarantees that joining unbounded keyed stream x bounded keyed stream
1045        // always produces deterministic order per key (nested loop join), this could just use
1046        // `join_keyed_stream` without constructing IRs manually
1047        KeyedStream::new(
1048            self.location.clone(),
1049            HydroNode::Join {
1050                left: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1051                right: Box::new(other.ir_node.replace(HydroNode::Placeholder)),
1052                metadata: self
1053                    .location
1054                    .new_node_metadata(KeyedStream::<K, (V, V2), L, B2, O2, R2>::collection_kind()),
1055            },
1056        )
1057    }
1058
1059    /// Emit a keyed singleton containing all keys shared between two keyed singletons,
1060    /// where each value in the output keyed singleton is a tuple of
1061    /// (self.value, other.value).
1062    ///
1063    /// # Example
1064    /// ```rust
1065    /// # #[cfg(feature = "deploy")] {
1066    /// # use hydro_lang::prelude::*;
1067    /// # use futures::StreamExt;
1068    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1069    /// # let tick = process.tick();
1070    /// let requests = // { 1: 10, 2: 20, 3: 30 }
1071    /// # process
1072    /// #     .source_iter(q!(vec![(1, 10), (2, 20), (3, 30)]))
1073    /// #     .into_keyed()
1074    /// #     .batch(&tick, nondet!(/** test */))
1075    /// #     .first();
1076    /// let other = // { 1: 100, 2: 200, 4: 400 }
1077    /// # process
1078    /// #     .source_iter(q!(vec![(1, 100), (2, 200), (4, 400)]))
1079    /// #     .into_keyed()
1080    /// #     .batch(&tick, nondet!(/** test */))
1081    /// #     .first();
1082    /// requests.join_keyed_singleton(other)
1083    /// # .entries().all_ticks()
1084    /// # }, |mut stream| async move {
1085    /// // { 1: (10, 100), 2: (20, 200) }
1086    /// # let mut results = vec![];
1087    /// # for _ in 0..2 {
1088    /// #     results.push(stream.next().await.unwrap());
1089    /// # }
1090    /// # results.sort();
1091    /// # assert_eq!(results, vec![(1, (10, 100)), (2, (20, 200))]);
1092    /// # }));
1093    /// # }
1094    /// ```
1095    pub fn join_keyed_singleton<V2: Clone>(
1096        self,
1097        other: KeyedSingleton<K, V2, L, Bounded>,
1098    ) -> KeyedSingleton<K, (V, V2), L, Bounded>
1099    where
1100        B: IsBounded,
1101        K: Eq + Hash + Clone,
1102        V: Clone,
1103    {
1104        let result_stream = self
1105            .make_bounded()
1106            .entries()
1107            .join(other.entries())
1108            .into_keyed();
1109
1110        // The cast is guaranteed to succeed, since each key (in both `self` and `other`) has at most one value.
1111        result_stream.cast_at_most_one_entry_per_key()
1112    }
1113
1114    /// For each value in `self`, find the matching key in `lookup`.
1115    /// The output is a keyed singleton with the key from `self`, and a value
1116    /// that is a tuple of (`self`'s value, Option<`lookup`'s value>).
1117    /// If the key is not present in `lookup`, the option will be [`None`].
1118    ///
1119    /// # Example
1120    /// ```rust
1121    /// # #[cfg(feature = "deploy")] {
1122    /// # use hydro_lang::prelude::*;
1123    /// # use futures::StreamExt;
1124    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1125    /// # let tick = process.tick();
1126    /// let requests = // { 1: 10, 2: 20 }
1127    /// # process
1128    /// #     .source_iter(q!(vec![(1, 10), (2, 20)]))
1129    /// #     .into_keyed()
1130    /// #     .batch(&tick, nondet!(/** test */))
1131    /// #     .first();
1132    /// let other_data = // { 10: 100, 11: 110 }
1133    /// # process
1134    /// #     .source_iter(q!(vec![(10, 100), (11, 110)]))
1135    /// #     .into_keyed()
1136    /// #     .batch(&tick, nondet!(/** test */))
1137    /// #     .first();
1138    /// requests.lookup_keyed_singleton(other_data)
1139    /// # .entries().all_ticks()
1140    /// # }, |mut stream| async move {
1141    /// // { 1: (10, Some(100)), 2: (20, None) }
1142    /// # let mut results = vec![];
1143    /// # for _ in 0..2 {
1144    /// #     results.push(stream.next().await.unwrap());
1145    /// # }
1146    /// # results.sort();
1147    /// # assert_eq!(results, vec![(1, (10, Some(100))), (2, (20, None))]);
1148    /// # }));
1149    /// # }
1150    /// ```
1151    pub fn lookup_keyed_singleton<V2>(
1152        self,
1153        lookup: KeyedSingleton<V, V2, L, Bounded>,
1154    ) -> KeyedSingleton<K, (V, Option<V2>), L, Bounded>
1155    where
1156        B: IsBounded,
1157        K: Eq + Hash + Clone,
1158        V: Eq + Hash + Clone,
1159        V2: Clone,
1160    {
1161        let result_stream = self
1162            .make_bounded()
1163            .into_keyed_stream()
1164            .lookup_keyed_stream(lookup.into_keyed_stream());
1165
1166        // The cast is guaranteed to succeed since both lookup and self contain at most 1 value per key
1167        result_stream.cast_at_most_one_entry_per_key()
1168    }
1169
1170    /// For each value in `self`, find the matching key in `lookup`.
1171    /// The output is a keyed stream with the key from `self`, and a value
1172    /// that is a tuple of (`self`'s value, Option<`lookup`'s value>).
1173    /// If the key is not present in `lookup`, the option will be [`None`].
1174    ///
1175    /// # Example
1176    /// ```rust
1177    /// # #[cfg(feature = "deploy")] {
1178    /// # use hydro_lang::prelude::*;
1179    /// # use futures::StreamExt;
1180    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1181    /// # let tick = process.tick();
1182    /// let requests = // { 1: 10, 2: 20 }
1183    /// # process
1184    /// #     .source_iter(q!(vec![(1, 10), (2, 20)]))
1185    /// #     .into_keyed()
1186    /// #     .batch(&tick, nondet!(/** test */))
1187    /// #     .first();
1188    /// let other_data = // { 10: 100, 10: 110 }
1189    /// # process
1190    /// #     .source_iter(q!(vec![(10, 100), (10, 110)]))
1191    /// #     .into_keyed()
1192    /// #     .batch(&tick, nondet!(/** test */));
1193    /// requests.lookup_keyed_stream(other_data)
1194    /// # .entries().all_ticks()
1195    /// # }, |mut stream| async move {
1196    /// // { 1: [(10, Some(100)), (10, Some(110))], 2: (20, None) }
1197    /// # let mut results = vec![];
1198    /// # for _ in 0..3 {
1199    /// #     results.push(stream.next().await.unwrap());
1200    /// # }
1201    /// # results.sort();
1202    /// # assert_eq!(results, vec![(1, (10, Some(100))), (1, (10, Some(110))), (2, (20, None))]);
1203    /// # }));
1204    /// # }
1205    /// ```
1206    pub fn lookup_keyed_stream<V2, O: Ordering, R: Retries>(
1207        self,
1208        lookup: KeyedStream<V, V2, L, Bounded, O, R>,
1209    ) -> KeyedStream<K, (V, Option<V2>), L, Bounded, NoOrder, R>
1210    where
1211        B: IsBounded,
1212        K: Eq + Hash + Clone,
1213        V: Eq + Hash + Clone,
1214        V2: Clone,
1215    {
1216        self.make_bounded()
1217            .entries()
1218            .weaken_retries::<R>() // TODO: Once weaken_retries() is implemented for KeyedSingleton, remove entries() and into_keyed()
1219            .into_keyed()
1220            .lookup_keyed_stream(lookup)
1221    }
1222
1223    /// For each key present in both `self` and `thresholds`, emits a [`KeyedStream`] event the first
1224    /// time that key's value becomes greater than or equal to the corresponding threshold value.
1225    /// The emitted value for each key is the threshold value itself.
1226    ///
1227    /// This requires the keyed singleton to have monotonic values ([`MonotonicValue`] or [`Bounded`]),
1228    /// because otherwise the threshold detection would be non-deterministic.
1229    ///
1230    /// The `thresholds` parameter is a [`BoundedValue`] keyed singleton mapping each key to its
1231    /// threshold. Thresholds may arrive asynchronously (new keys appear over time), but once set
1232    /// for a key, the threshold value is fixed. Late-arriving thresholds are checked against the
1233    /// current snapshot value immediately.
1234    ///
1235    /// # Example
1236    /// ```rust,ignore
1237    /// use hydro_lang::prelude::*;
1238    ///
1239    /// // Given a monotonically increasing keyed singleton (e.g. from fold with monotone proof)
1240    /// let counts: KeyedSingleton<u32, usize, _, MonotonicValue> = events.into_keyed()
1241    ///     .fold(q!(|| 0), q!(|acc, _| *acc += 1, monotone = manual_proof!(/** +1 is monotone */)));
1242    ///
1243    /// // BoundedValue keyed singleton of thresholds (from .first())
1244    /// let thresholds = threshold_source.into_keyed().first();
1245    ///
1246    /// // Emits (key, threshold_value) the first time each key's value >= threshold
1247    /// let crossed = counts.threshold_greater_or_equal(thresholds);
1248    /// ```
1249    pub fn threshold_greater_or_equal(
1250        self,
1251        thresholds: KeyedSingleton<K, V, L, BoundedValue>,
1252    ) -> KeyedStream<K, V, L, B::UnderlyingBound, NoOrder, ExactlyOnce>
1253    where
1254        K: Clone + Eq + Hash,
1255        V: Clone + PartialOrd,
1256        B: IsKeyedMonotonic,
1257    {
1258        let self_location = self.location.clone();
1259        match B::bound_kind() {
1260            KeyedSingletonBoundKind::Bounded => {
1261                // Bounded case: self is already fixed, just join and filter
1262                let me: KeyedSingleton<K, V, L, Bounded> = KeyedSingleton::new(
1263                    self.location.clone(),
1264                    self.ir_node.replace(HydroNode::Placeholder),
1265                );
1266                let result = me
1267                    .entries()
1268                    .join(thresholds.entries())
1269                    .filter_map(q!(|(k, (val, thresh))| {
1270                        if val >= thresh {
1271                            Some((k, thresh))
1272                        } else {
1273                            None
1274                        }
1275                    }))
1276                    .into_keyed();
1277                KeyedStream::new(
1278                    result.location.clone(),
1279                    result.ir_node.replace(HydroNode::Placeholder),
1280                )
1281            }
1282            KeyedSingletonBoundKind::MonotonicValue if self.location.id().is_root() => {
1283                let me: KeyedSingleton<K, V, L, MonotonicValue> = KeyedSingleton::new(
1284                    self.location.clone(),
1285                    self.ir_node.replace(HydroNode::Placeholder),
1286                );
1287                let value_updates = me.into_update_stream(nondet!(
1288                    /// Each key's value is monotone, so a version crosses its threshold iff
1289                    /// every later version does: stuttering and skipping intermediate versions
1290                    /// cannot change whether a key is (eventually) emitted, and each key is
1291                    /// emitted at most once.
1292                ));
1293
1294                let result = sliced! {
1295                    let value_batch =
1296                        use::batch(value_updates, nondet!(/** thresholds are deterministic */));
1297                    let thresh_batch =
1298                        use::batch(thresholds, nondet!(/** thresholds are deterministic */));
1299                    // A key's threshold may arrive after its value has already crossed it, so the
1300                    // latest value of every key that has not crossed yet is held across ticks.
1301                    // Values are monotone, so the latest value is the maximum one. Each threshold
1302                    // arrives in exactly one batch, so it is held as pending until the key's
1303                    // value reaches it. Once a key has crossed, it is dropped from both pending
1304                    // sets (and its later value updates are ignored), so it is emitted once.
1305                    let mut pending_values =
1306                        use::state_null::<Stream<(K, V), Tick<_>, Bounded, NoOrder>>();
1307                    let mut pending_thresholds =
1308                        use::state_null::<Stream<(K, V), Tick<_>, Bounded, NoOrder>>();
1309                    let mut crossed_keys =
1310                        use::state_null::<Stream<K, Tick<_>, Bounded, NoOrder>>();
1311
1312                    pending_values = pending_values
1313                        .chain(value_batch.entries().anti_join(crossed_keys.clone()))
1314                        .into_keyed()
1315                        .reduce(q!(
1316                            |latest, value| {
1317                                if value > *latest {
1318                                    *latest = value;
1319                                }
1320                            },
1321                            commutative = manual_proof!(/** max is commutative */)
1322                        ))
1323                        .entries();
1324                    pending_thresholds = pending_thresholds.chain(thresh_batch.entries());
1325
1326                    let crossed = pending_thresholds
1327                        .clone()
1328                        .join(pending_values.clone())
1329                        .filter(q!(|(_, (thresh, val))| *val >= *thresh))
1330                        .map(q!(|(k, (thresh, _))| (k, thresh)));
1331                    let newly_crossed_keys = crossed.clone().map(q!(|(k, _)| k));
1332                    pending_values = pending_values.anti_join(newly_crossed_keys.clone());
1333                    pending_thresholds = pending_thresholds.anti_join(newly_crossed_keys.clone());
1334                    crossed_keys = crossed_keys.chain(newly_crossed_keys);
1335
1336                    crossed.into_keyed()
1337                };
1338
1339                KeyedStream::new(
1340                    self_location,
1341                    result.ir_node.replace(HydroNode::Placeholder),
1342                )
1343            }
1344            KeyedSingletonBoundKind::MonotonicValue => {
1345                let me: KeyedSingleton<K, V, L, MonotonicValue> = KeyedSingleton::new(
1346                    self.location.clone(),
1347                    self.ir_node.replace(HydroNode::Placeholder),
1348                );
1349
1350                let result = sliced! {
1351                    let snapshot = use::snapshot(me, nondet!(/** thresholds are deterministic */));
1352                    // Each threshold arrives in exactly one batch, so it is held as *pending*
1353                    // across ticks until the key's value reaches it. Because the value is
1354                    // monotone, a crossed threshold stays crossed forever, so it is dropped from
1355                    // the pending set, which also ensures each key is emitted exactly once.
1356                    let thresh_batch =
1357                        use::batch(thresholds, nondet!(/** thresholds are deterministic */));
1358                    let mut pending_thresholds =
1359                        use::state_null::<Stream<(K, V), Tick<_>, Bounded, NoOrder>>();
1360                    pending_thresholds = pending_thresholds.chain(thresh_batch.entries());
1361
1362                    let crossed = pending_thresholds
1363                        .clone()
1364                        .join(snapshot.entries())
1365                        .filter(q!(|(_, (thresh, val))| *val >= *thresh))
1366                        .map(q!(|(k, (thresh, _))| (k, thresh)));
1367                    pending_thresholds =
1368                        pending_thresholds.anti_join(crossed.clone().map(q!(|(k, _)| k)));
1369
1370                    crossed.into_keyed()
1371                };
1372
1373                KeyedStream::new(
1374                    self_location,
1375                    result.ir_node.replace(HydroNode::Placeholder),
1376                )
1377            }
1378            KeyedSingletonBoundKind::BoundedValue => {
1379                let me: KeyedSingleton<K, V, L, BoundedValue> = KeyedSingleton::new(
1380                    self.location.clone(),
1381                    self.ir_node.replace(HydroNode::Placeholder),
1382                );
1383
1384                let result = sliced! {
1385                    // Both the values and the thresholds arrive in exactly one batch each, and a
1386                    // key's value and threshold may arrive in different batches, so both sides
1387                    // are held as *pending* across ticks until they meet. Once a key has crossed
1388                    // its threshold, both its (final) value and threshold are dropped from the
1389                    // pending sets, which also ensures each key is emitted exactly once.
1390                    let value_batch = use::batch(me, nondet!(/** thresholds are deterministic */));
1391                    let thresh_batch =
1392                        use::batch(thresholds, nondet!(/** thresholds are deterministic */));
1393                    let mut pending_values =
1394                        use::state_null::<Stream<(K, V), Tick<_>, Bounded, NoOrder>>();
1395                    let mut pending_thresholds =
1396                        use::state_null::<Stream<(K, V), Tick<_>, Bounded, NoOrder>>();
1397                    pending_values = pending_values.chain(value_batch.entries());
1398                    pending_thresholds = pending_thresholds.chain(thresh_batch.entries());
1399
1400                    let crossed = pending_thresholds
1401                        .clone()
1402                        .join(pending_values.clone())
1403                        .filter(q!(|(_, (thresh, val))| *val >= *thresh))
1404                        .map(q!(|(k, (thresh, _))| (k, thresh)));
1405                    let crossed_keys = crossed.clone().map(q!(|(k, _)| k));
1406                    pending_values = pending_values.anti_join(crossed_keys.clone());
1407                    pending_thresholds = pending_thresholds.anti_join(crossed_keys);
1408
1409                    crossed.into_keyed()
1410                };
1411
1412                KeyedStream::new(
1413                    self_location,
1414                    result.ir_node.replace(HydroNode::Placeholder),
1415                )
1416            }
1417            _ => {
1418                unreachable!(
1419                    "IsKeyedMonotonic is only implemented for Bounded, BoundedValue, and MonotonicValue"
1420                )
1421            }
1422        }
1423    }
1424
1425    /// Like [`Self::threshold_greater_or_equal`], but uses a single [`Singleton`] threshold
1426    /// shared across all keys. Emits a `(K, V)` event for each key the first time that key's
1427    /// value becomes >= the threshold. The emitted value is the threshold itself.
1428    ///
1429    /// Because the threshold is a [`Bounded`] singleton, it is a compile-time constant and
1430    /// does not carry ongoing memory cost.
1431    ///
1432    /// # Example
1433    /// ```rust
1434    /// # #[cfg(feature = "deploy")] {
1435    /// # use hydro_lang::prelude::*;
1436    /// # use futures::StreamExt;
1437    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1438    /// // A keyed singleton of per-key values (in practice often a monotone counter): { 1: 6, 2: 4 }
1439    /// let counts = process
1440    ///     .source_iter(q!(vec![(1, 6), (2, 4)]))
1441    ///     .into_keyed()
1442    ///     .first();
1443    ///
1444    /// // A single threshold value shared across all keys
1445    /// let threshold = process.singleton(q!(5));
1446    ///
1447    /// // Emits (key, threshold) the first time each key's value >= threshold
1448    /// counts.threshold_greater_or_equal_uniform(threshold)
1449    /// #   .entries()
1450    /// # }, |mut stream| async move {
1451    /// // { 1: 5 } -- key 1's value 6 >= 5, but key 2's value 4 < 5
1452    /// # assert_eq!(stream.next().await.unwrap(), (1, 5));
1453    /// # }));
1454    /// # }
1455    /// ```
1456    pub fn threshold_greater_or_equal_uniform(
1457        self,
1458        threshold: Singleton<V, L, Bounded>,
1459    ) -> KeyedStream<K, V, L, B::UnderlyingBound, NoOrder, ExactlyOnce>
1460    where
1461        K: Clone + Eq + Hash,
1462        V: Clone + PartialOrd,
1463        B: IsKeyedMonotonic,
1464    {
1465        let self_location = self.location.clone();
1466        match B::bound_kind() {
1467            KeyedSingletonBoundKind::Bounded => {
1468                let me: KeyedSingleton<K, V, L, Bounded> = KeyedSingleton::new(
1469                    self.location.clone(),
1470                    self.ir_node.replace(HydroNode::Placeholder),
1471                );
1472                let result = me
1473                    .entries()
1474                    .cross_singleton(threshold)
1475                    .filter_map(q!(|((k, val), thresh)| {
1476                        if val >= thresh {
1477                            Some((k, thresh))
1478                        } else {
1479                            None
1480                        }
1481                    }))
1482                    .into_keyed();
1483                KeyedStream::new(
1484                    result.location.clone(),
1485                    result.ir_node.replace(HydroNode::Placeholder),
1486                )
1487            }
1488            KeyedSingletonBoundKind::MonotonicValue if self.location.id().is_root() => {
1489                let me: KeyedSingleton<K, V, L, MonotonicValue> = KeyedSingleton::new(
1490                    self.location.clone(),
1491                    self.ir_node.replace(HydroNode::Placeholder),
1492                );
1493                let value_updates = me.into_update_stream(nondet!(
1494                    /// Each key's value is monotone, so a version crosses the threshold iff
1495                    /// every later version does: stuttering and skipping intermediate versions
1496                    /// cannot change whether a key is (eventually) emitted, and each key is
1497                    /// emitted at most once.
1498                ));
1499
1500                let result = sliced! {
1501                    // Only the changed entries are checked against the threshold; no per-key
1502                    // values are held. A key may cross in several updates of one batch (or
1503                    // stutter), so crossing keys are de-duplicated, and keys that have already
1504                    // crossed are remembered so that each key is emitted once.
1505                    let value_batch =
1506                        use::batch(value_updates, nondet!(/** thresholds are deterministic */));
1507                    let mut already_crossed =
1508                        use::state_null::<Stream<K, Tick<_>, Bounded, NoOrder>>();
1509
1510                    let tick = value_batch.location().clone();
1511                    let thresh_in_tick = threshold.clone_into_tick(&tick);
1512
1513                    let newly_crossed_keys = value_batch
1514                        .entries()
1515                        .cross_singleton(thresh_in_tick.clone())
1516                        .filter_map(q!(|((k, val), thresh)| {
1517                            if val >= thresh {
1518                                Some(k)
1519                            } else {
1520                                None
1521                            }
1522                        }))
1523                        .unique()
1524                        .filter_not_in(already_crossed.clone());
1525                    already_crossed = already_crossed.chain(newly_crossed_keys.clone());
1526
1527                    newly_crossed_keys
1528                        .cross_singleton(thresh_in_tick)
1529                        .into_keyed()
1530                };
1531
1532                KeyedStream::new(
1533                    self_location,
1534                    result.ir_node.replace(HydroNode::Placeholder),
1535                )
1536            }
1537            KeyedSingletonBoundKind::MonotonicValue => {
1538                let me: KeyedSingleton<K, V, L, MonotonicValue> = KeyedSingleton::new(
1539                    self.location.clone(),
1540                    self.ir_node.replace(HydroNode::Placeholder),
1541                );
1542
1543                let result = sliced! {
1544                    let snapshot = use::snapshot(me, nondet!(/** thresholds are deterministic */));
1545                    let mut already_crossed =
1546                        use::state_null::<Stream<K, Tick<_>, Bounded, NoOrder>>();
1547
1548                    let tick = snapshot.location().clone();
1549                    let thresh_in_tick = threshold.clone_into_tick(&tick);
1550
1551                    let crossing = snapshot
1552                        .entries()
1553                        .cross_singleton(thresh_in_tick)
1554                        .filter_map(q!(|((k, val), thresh)| {
1555                            if val >= thresh {
1556                                Some((k, thresh))
1557                            } else {
1558                                None
1559                            }
1560                        }));
1561
1562                    let newly_crossed = crossing.anti_join(already_crossed.clone());
1563                    already_crossed =
1564                        already_crossed.chain(newly_crossed.clone().map(q!(|(k, _)| k)));
1565
1566                    newly_crossed.into_keyed()
1567                };
1568
1569                KeyedStream::new(
1570                    self_location,
1571                    result.ir_node.replace(HydroNode::Placeholder),
1572                )
1573            }
1574            KeyedSingletonBoundKind::BoundedValue => {
1575                let me: KeyedSingleton<K, V, L, BoundedValue> = KeyedSingleton::new(
1576                    self.location.clone(),
1577                    self.ir_node.replace(HydroNode::Placeholder),
1578                );
1579
1580                let result = sliced! {
1581                    let snapshot = use::batch(me, nondet!(/** thresholds are deterministic */));
1582                    let mut already_crossed =
1583                        use::state_null::<Stream<K, Tick<_>, Bounded, NoOrder>>();
1584
1585                    let tick = snapshot.location().clone();
1586                    let thresh_in_tick = threshold.clone_into_tick(&tick);
1587
1588                    let crossing = snapshot
1589                        .entries()
1590                        .cross_singleton(thresh_in_tick)
1591                        .filter_map(q!(|((k, val), thresh)| {
1592                            if val >= thresh {
1593                                Some((k, thresh))
1594                            } else {
1595                                None
1596                            }
1597                        }));
1598
1599                    let newly_crossed = crossing.anti_join(already_crossed.clone());
1600                    already_crossed =
1601                        already_crossed.chain(newly_crossed.clone().map(q!(|(k, _)| k)));
1602
1603                    newly_crossed.into_keyed()
1604                };
1605
1606                KeyedStream::new(
1607                    self_location,
1608                    result.ir_node.replace(HydroNode::Placeholder),
1609                )
1610            }
1611            _ => {
1612                unreachable!(
1613                    "IsKeyedMonotonic is only implemented for Bounded, BoundedValue, and MonotonicValue"
1614                )
1615            }
1616        }
1617    }
1618}
1619
1620impl<'a, K, V, L: Location<'a>, B: KeyedSingletonBound<ValueBound = Bounded>>
1621    KeyedSingleton<K, V, L, B>
1622{
1623    /// Flattens the keyed singleton into an unordered stream of key-value pairs.
1624    ///
1625    /// The value for each key must be bounded, otherwise the resulting stream elements would be
1626    /// non-deterministic. As new entries are added to the keyed singleton, they will be streamed
1627    /// into the output.
1628    ///
1629    /// # Example
1630    /// ```rust
1631    /// # #[cfg(feature = "deploy")] {
1632    /// # use hydro_lang::prelude::*;
1633    /// # use futures::StreamExt;
1634    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1635    /// let keyed_singleton = // { 1: 2, 2: 4 }
1636    /// # process
1637    /// #     .source_iter(q!(vec![(1, 2), (2, 4)]))
1638    /// #     .into_keyed()
1639    /// #     .first();
1640    /// keyed_singleton.entries()
1641    /// # }, |mut stream| async move {
1642    /// // (1, 2), (2, 4) in any order
1643    /// # let mut results = Vec::new();
1644    /// # for _ in 0..2 {
1645    /// #     results.push(stream.next().await.unwrap());
1646    /// # }
1647    /// # results.sort();
1648    /// # assert_eq!(results, vec![(1, 2), (2, 4)]);
1649    /// # }));
1650    /// # }
1651    /// ```
1652    pub fn entries(self) -> Stream<(K, V), L, B::UnderlyingBound, NoOrder, ExactlyOnce> {
1653        self.into_keyed_stream().entries()
1654    }
1655
1656    /// Flattens the keyed singleton into an unordered stream of just the values.
1657    ///
1658    /// The value for each key must be bounded, otherwise the resulting stream elements would be
1659    /// non-deterministic. As new entries are added to the keyed singleton, they will be streamed
1660    /// into the output.
1661    ///
1662    /// # Example
1663    /// ```rust
1664    /// # #[cfg(feature = "deploy")] {
1665    /// # use hydro_lang::prelude::*;
1666    /// # use futures::StreamExt;
1667    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1668    /// let keyed_singleton = // { 1: 2, 2: 4 }
1669    /// # process
1670    /// #     .source_iter(q!(vec![(1, 2), (2, 4)]))
1671    /// #     .into_keyed()
1672    /// #     .first();
1673    /// keyed_singleton.values()
1674    /// # }, |mut stream| async move {
1675    /// // 2, 4 in any order
1676    /// # let mut results = Vec::new();
1677    /// # for _ in 0..2 {
1678    /// #     results.push(stream.next().await.unwrap());
1679    /// # }
1680    /// # results.sort();
1681    /// # assert_eq!(results, vec![2, 4]);
1682    /// # }));
1683    /// # }
1684    /// ```
1685    pub fn values(self) -> Stream<V, L, B::UnderlyingBound, NoOrder, ExactlyOnce> {
1686        let map_f = q!(|(_, v)| v)
1687            .splice_fn1_ctx::<(K, V), V>(&OperatorContext::<L, B::UnderlyingBound>::new(
1688                &self.location,
1689            ))
1690            .into();
1691
1692        Stream::new(
1693            self.location.clone(),
1694            HydroNode::Map {
1695                f: map_f,
1696                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1697                metadata: self.location.new_node_metadata(Stream::<
1698                    V,
1699                    L,
1700                    B::UnderlyingBound,
1701                    NoOrder,
1702                    ExactlyOnce,
1703                >::collection_kind()),
1704            },
1705        )
1706    }
1707
1708    /// Flattens the keyed singleton into an unordered stream of just the keys.
1709    ///
1710    /// The value for each key must be bounded, otherwise the removal of keys would result in
1711    /// non-determinism. As new entries are added to the keyed singleton, they will be streamed
1712    /// into the output.
1713    ///
1714    /// # Example
1715    /// ```rust
1716    /// # #[cfg(feature = "deploy")] {
1717    /// # use hydro_lang::prelude::*;
1718    /// # use futures::StreamExt;
1719    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1720    /// let keyed_singleton = // { 1: 2, 2: 4 }
1721    /// # process
1722    /// #     .source_iter(q!(vec![(1, 2), (2, 4)]))
1723    /// #     .into_keyed()
1724    /// #     .first();
1725    /// keyed_singleton.keys()
1726    /// # }, |mut stream| async move {
1727    /// // 1, 2 in any order
1728    /// # let mut results = Vec::new();
1729    /// # for _ in 0..2 {
1730    /// #     results.push(stream.next().await.unwrap());
1731    /// # }
1732    /// # results.sort();
1733    /// # assert_eq!(results, vec![1, 2]);
1734    /// # }));
1735    /// # }
1736    /// ```
1737    pub fn keys(self) -> Stream<K, L, B::UnderlyingBound, NoOrder, ExactlyOnce> {
1738        self.entries().map(q!(|(k, _)| k))
1739    }
1740
1741    /// Given a bounded stream of keys `K`, returns a new keyed singleton containing only the
1742    /// entries whose keys are not in the provided stream.
1743    ///
1744    /// # Example
1745    /// ```rust
1746    /// # #[cfg(feature = "deploy")] {
1747    /// # use hydro_lang::prelude::*;
1748    /// # use futures::StreamExt;
1749    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1750    /// let tick = process.tick();
1751    /// let keyed_singleton = // { 1: 2, 2: 4 }
1752    /// # process
1753    /// #     .source_iter(q!(vec![(1, 2), (2, 4)]))
1754    /// #     .into_keyed()
1755    /// #     .first()
1756    /// #     .batch(&tick, nondet!(/** test */));
1757    /// let keys_to_remove = process
1758    ///     .source_iter(q!(vec![1]))
1759    ///     .batch(&tick, nondet!(/** test */));
1760    /// keyed_singleton.filter_key_not_in(keys_to_remove)
1761    /// #   .entries().all_ticks()
1762    /// # }, |mut stream| async move {
1763    /// // { 2: 4 }
1764    /// # for w in vec![(2, 4)] {
1765    /// #     assert_eq!(stream.next().await.unwrap(), w);
1766    /// # }
1767    /// # }));
1768    /// # }
1769    /// ```
1770    pub fn filter_key_not_in<O2: Ordering, R2: Retries>(
1771        self,
1772        other: Stream<K, L, Bounded, O2, R2>,
1773    ) -> Self
1774    where
1775        K: Hash + Eq,
1776    {
1777        check_matching_location(&self.location, &other.location);
1778
1779        KeyedSingleton::new(
1780            self.location.clone(),
1781            HydroNode::AntiJoin {
1782                pos: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1783                neg: Box::new(other.ir_node.replace(HydroNode::Placeholder)),
1784                metadata: self.location.new_node_metadata(Self::collection_kind()),
1785            },
1786        )
1787    }
1788
1789    /// An operator which allows you to "inspect" each value of a keyed singleton without
1790    /// modifying it. The closure `f` is called on a reference to each value. This is
1791    /// mainly useful for debugging, and should not be used to generate side-effects.
1792    ///
1793    /// # Example
1794    /// ```rust
1795    /// # #[cfg(feature = "deploy")] {
1796    /// # use hydro_lang::prelude::*;
1797    /// # use futures::StreamExt;
1798    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1799    /// let keyed_singleton = // { 1: 2, 2: 4 }
1800    /// # process
1801    /// #     .source_iter(q!(vec![(1, 2), (2, 4)]))
1802    /// #     .into_keyed()
1803    /// #     .first();
1804    /// keyed_singleton
1805    ///     .inspect(q!(|v| println!("{}", v)))
1806    /// #   .entries()
1807    /// # }, |mut stream| async move {
1808    /// // { 1: 2, 2: 4 }
1809    /// # for w in vec![(1, 2), (2, 4)] {
1810    /// #     assert_eq!(stream.next().await.unwrap(), w);
1811    /// # }
1812    /// # }));
1813    /// # }
1814    /// ```
1815    pub fn inspect<F>(
1816        self,
1817        f: impl IntoQuotedMut<'a, F, OperatorContext<L, B::UnderlyingBound>> + Copy,
1818    ) -> Self
1819    where
1820        F: Fn(&V) + 'a,
1821    {
1822        let f: ManualExpr<F, _> =
1823            ManualExpr::new(move |ctx: &OperatorContext<L, B::UnderlyingBound>| {
1824                f.splice_fn1_borrow_ctx(ctx)
1825            });
1826        let inspect_f = q!({
1827            let orig = f;
1828            move |t: &(_, _)| orig(&t.1)
1829        })
1830        .splice_fn1_borrow_ctx::<(K, V), ()>(&OperatorContext::<L, B::UnderlyingBound>::new(
1831            &self.location,
1832        ))
1833        .into();
1834
1835        KeyedSingleton::new(
1836            self.location.clone(),
1837            HydroNode::Inspect {
1838                f: inspect_f,
1839                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1840                metadata: self.location.new_node_metadata(Self::collection_kind()),
1841            },
1842        )
1843    }
1844
1845    /// An operator which allows you to "inspect" each entry of a keyed singleton without
1846    /// modifying it. The closure `f` is called on a reference to each key-value pair. This is
1847    /// mainly useful for debugging, and should not be used to generate side-effects.
1848    ///
1849    /// # Example
1850    /// ```rust
1851    /// # #[cfg(feature = "deploy")] {
1852    /// # use hydro_lang::prelude::*;
1853    /// # use futures::StreamExt;
1854    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1855    /// let keyed_singleton = // { 1: 2, 2: 4 }
1856    /// # process
1857    /// #     .source_iter(q!(vec![(1, 2), (2, 4)]))
1858    /// #     .into_keyed()
1859    /// #     .first();
1860    /// keyed_singleton
1861    ///     .inspect_with_key(q!(|(k, v)| println!("{}: {}", k, v)))
1862    /// #   .entries()
1863    /// # }, |mut stream| async move {
1864    /// // { 1: 2, 2: 4 }
1865    /// # for w in vec![(1, 2), (2, 4)] {
1866    /// #     assert_eq!(stream.next().await.unwrap(), w);
1867    /// # }
1868    /// # }));
1869    /// # }
1870    /// ```
1871    pub fn inspect_with_key<F>(
1872        self,
1873        f: impl IntoQuotedMut<'a, F, OperatorContext<L, B::UnderlyingBound>>,
1874    ) -> Self
1875    where
1876        F: Fn(&(K, V)) + 'a,
1877    {
1878        let inspect_f = f
1879            .splice_fn1_borrow_ctx::<(K, V), ()>(&OperatorContext::<L, B::UnderlyingBound>::new(
1880                &self.location,
1881            ))
1882            .into();
1883
1884        KeyedSingleton::new(
1885            self.location.clone(),
1886            HydroNode::Inspect {
1887                f: inspect_f,
1888                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1889                metadata: self.location.new_node_metadata(Self::collection_kind()),
1890            },
1891        )
1892    }
1893
1894    /// Gets the key-value tuple with the largest key among all entries in this [`KeyedSingleton`].
1895    ///
1896    /// Because this method requires values to be bounded, the output [`Optional`] will only be
1897    /// asynchronously updated if a new key is added that is higher than the previous max key.
1898    ///
1899    /// # 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    /// let tick = process.tick();
1906    /// let keyed_singleton = // { 1: 123, 2: 456, 0: 789 }
1907    /// # Stream::<_, _>::from(process.source_iter(q!(vec![(1, 123), (2, 456), (0, 789)])))
1908    /// #     .into_keyed()
1909    /// #     .first();
1910    /// keyed_singleton.get_max_key()
1911    /// # .into_singleton()
1912    /// # .sample_eager(nondet!(/** test */))
1913    /// # }, |mut stream| async move {
1914    /// // sampled as `Option<(K, V)>` snapshots, eventually Some((2, 456))
1915    /// # let mut recv = std::pin::pin!(stream.filter(|v| futures::future::ready(v.is_some())));
1916    /// # assert_eq!(recv.next().await.unwrap(), Some((2, 456)));
1917    /// # }));
1918    /// # }
1919    /// ```
1920    pub fn get_max_key(
1921        self,
1922    ) -> Optional<(K, V), L, <B::UnderlyingBound as Boundedness>::AggregatedOptional>
1923    where
1924        K: Ord,
1925    {
1926        self.entries()
1927            .assume_ordering_trusted(nondet!(
1928                /// There is only one element associated with each key, and the keys are totallly
1929                /// ordered so we will produce a deterministic value. The closure technically
1930                /// isn't commutative in the case where both passed entries have the same key
1931                /// but different values.
1932                ///
1933                /// In the future, we may want to have an `assume!(...)` statement in the UDF that
1934                /// the two inputs do not have the same key.
1935            ))
1936            .reduce(q!(
1937                move |curr, new| {
1938                    if new.0 > curr.0 {
1939                        *curr = new;
1940                    }
1941                },
1942                idempotent = manual_proof!(/** repeated elements are ignored */)
1943            ))
1944    }
1945
1946    /// Converts this keyed singleton into a [`KeyedStream`] with each group having a single
1947    /// element, the value.
1948    ///
1949    /// This is the equivalent of [`Singleton::into_stream`] but keyed.
1950    ///
1951    /// # Example
1952    /// ```rust
1953    /// # #[cfg(feature = "deploy")] {
1954    /// # use hydro_lang::prelude::*;
1955    /// # use futures::StreamExt;
1956    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1957    /// let keyed_singleton = // { 1: 2, 2: 4 }
1958    /// # Stream::<_, _>::from(process.source_iter(q!(vec![(1, 2), (2, 4)])))
1959    /// #     .into_keyed()
1960    /// #     .first();
1961    /// keyed_singleton
1962    ///     .clone()
1963    ///     .into_keyed_stream()
1964    ///     .merge_unordered(
1965    ///         keyed_singleton.into_keyed_stream()
1966    ///     )
1967    /// #   .entries()
1968    /// # }, |mut stream| async move {
1969    /// /// // { 1: [2, 2], 2: [4, 4] }
1970    /// # for w in vec![(1, 2), (2, 4), (1, 2), (2, 4)] {
1971    /// #     assert_eq!(stream.next().await.unwrap(), w);
1972    /// # }
1973    /// # }));
1974    /// # }
1975    /// ```
1976    pub fn into_keyed_stream(
1977        self,
1978    ) -> KeyedStream<K, V, L, B::UnderlyingBound, TotalOrder, ExactlyOnce> {
1979        KeyedStream::new(
1980            self.location.clone(),
1981            HydroNode::Cast {
1982                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
1983                metadata: self.location.new_node_metadata(KeyedStream::<
1984                    K,
1985                    V,
1986                    L,
1987                    B::UnderlyingBound,
1988                    TotalOrder,
1989                    ExactlyOnce,
1990                >::collection_kind()),
1991            },
1992        )
1993    }
1994}
1995
1996impl<'a, K, V, L, B> KeyedSingleton<K, V, L, B>
1997where
1998    L: Location<'a>,
1999    B: KeyedSingletonBound<ValueBound = Bounded>,
2000{
2001    /// Shifts this bounded-value keyed singleton into an atomic context, which guarantees that any downstream logic
2002    /// will all be executed synchronously before any outputs are yielded (in [`KeyedSingleton::end_atomic`]).
2003    ///
2004    /// This is useful to enforce local consistency constraints, such as ensuring that a write is
2005    /// processed before an acknowledgement is emitted.
2006    pub fn atomic(self) -> KeyedSingleton<K, V, Atomic<L>, B>
2007    where
2008        L: TopLevel<'a>,
2009    {
2010        let out_location = Atomic {
2011            tick: self.location.tick(),
2012        };
2013        KeyedSingleton::new(
2014            out_location.clone(),
2015            HydroNode::BeginAtomic {
2016                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2017                metadata: out_location
2018                    .new_node_metadata(KeyedSingleton::<K, V, Atomic<L>, B>::collection_kind()),
2019            },
2020        )
2021    }
2022}
2023
2024impl<'a, K, V, L, B: KeyedSingletonBound> KeyedSingleton<K, V, Atomic<L>, B>
2025where
2026    L: Location<'a>,
2027{
2028    /// Yields the elements of this keyed singleton back into a top-level, asynchronous execution context.
2029    /// See [`KeyedSingleton::atomic`] for more details.
2030    pub fn end_atomic(self) -> KeyedSingleton<K, V, L, B> {
2031        KeyedSingleton::new(
2032            self.location.tick.l.clone(),
2033            HydroNode::EndAtomic {
2034                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2035                metadata: self
2036                    .location
2037                    .tick
2038                    .l
2039                    .new_node_metadata(KeyedSingleton::<K, V, L, B>::collection_kind()),
2040            },
2041        )
2042    }
2043}
2044
2045impl<'a, K, V, L: Location<'a>> KeyedSingleton<K, V, Tick<L>, Bounded> {
2046    /// Shifts the state in `self` to the **next tick**, so that the returned keyed singleton at
2047    /// tick `T` always has the entries of `self` at tick `T - 1`.
2048    ///
2049    /// At tick `0`, the output has no entries, since there is no previous tick.
2050    ///
2051    /// This operator enables stateful iterative processing with ticks, by sending data from one
2052    /// tick to the next. For example, you can use it to compare state across consecutive batches.
2053    ///
2054    /// # Example
2055    /// ```rust
2056    /// # #[cfg(feature = "deploy")] {
2057    /// # use hydro_lang::prelude::*;
2058    /// # use futures::StreamExt;
2059    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
2060    /// let tick = process.tick();
2061    /// # // ticks are lazy by default, forces the second tick to run
2062    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
2063    /// # let batch_first_tick = process
2064    /// #   .source_iter(q!(vec![(1, 2), (2, 3)]))
2065    /// #   .batch(&tick, nondet!(/** test */))
2066    /// #   .into_keyed();
2067    /// # let batch_second_tick = process
2068    /// #   .source_iter(q!(vec![(2, 4), (3, 5)]))
2069    /// #   .batch(&tick, nondet!(/** test */))
2070    /// #   .into_keyed()
2071    /// #   .defer_tick(); // appears on the second tick
2072    /// let input_batch = // first tick: { 1: 2, 2: 3 }, second tick: { 2: 4, 3: 5 }
2073    /// # batch_first_tick.chain(batch_second_tick).first();
2074    /// input_batch.clone().filter_key_not_in(
2075    ///     input_batch.defer_tick().keys() // keys present in the previous tick
2076    /// )
2077    /// # .entries().all_ticks()
2078    /// # }, |mut stream| async move {
2079    /// // { 1: 2, 2: 3 } (first tick), { 3: 5 } (second tick)
2080    /// # for w in vec![(1, 2), (2, 3), (3, 5)] {
2081    /// #     assert_eq!(stream.next().await.unwrap(), w);
2082    /// # }
2083    /// # }));
2084    /// # }
2085    /// ```
2086    pub fn defer_tick(self) -> KeyedSingleton<K, V, Tick<L>, Bounded> {
2087        KeyedSingleton::new(
2088            self.location.clone(),
2089            HydroNode::DeferTick {
2090                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2091                metadata: self
2092                    .location
2093                    .new_node_metadata(KeyedSingleton::<K, V, Tick<L>, Bounded>::collection_kind()),
2094            },
2095        )
2096    }
2097}
2098
2099impl<'a, K, V, L, B: KeyedSingletonSnapshotBound> KeyedSingleton<K, V, L, B>
2100where
2101    L: Location<'a>,
2102{
2103    /// Returns a keyed singleton with a snapshot of each key-value entry at a non-deterministic
2104    /// point in time. Every key that has appeared so far is present in each snapshot, so an
2105    /// entry that has not changed since the previous snapshot is observed again.
2106    ///
2107    /// This is available for keyed singletons whose entries may change over time, and for
2108    /// fully [`Bounded`] keyed singletons (whose complete contents are observed on every tick
2109    /// once they are available). For a [`BoundedValue`] keyed singleton, where each entry is
2110    /// final once it appears, use [`KeyedSingleton::batch`] to observe just the *new* entries.
2111    ///
2112    /// # Non-Determinism
2113    /// Because this picks a snapshot of each entry, which is continuously changing, each output has a
2114    /// non-deterministic set of entries since each snapshot can be at an arbitrary point in time.
2115    ///
2116    /// In simulation tests, the snapshot decisions can be scripted by attaching a
2117    /// [`KeyedSnapshotHook`](crate::sim_hooks::KeyedSnapshotHook) to the guard via
2118    /// `nondet!(/** reason */ hook = my_hook)`.
2119    pub fn snapshot<L2: Location<'a, DropConsistency = L::DropConsistency>>(
2120        self,
2121        tick: &Tick<L2>,
2122        mut nondet: NonDet<Option<crate::sim_hooks::KeyedSnapshotHook<K, V, L::SimHookScope>>>,
2123    ) -> KeyedSingleton<K, V, Tick<L::DropConsistency>, Bounded> {
2124        assert_eq!(
2125            Location::id(tick.parent_location()),
2126            Location::id(&self.location)
2127        );
2128        let mut metadata =
2129            tick.new_node_metadata(KeyedSingleton::<K, V, Tick<L>, Bounded>::collection_kind());
2130        metadata.op.sim_hook_id = nondet.take_hook().map(|h| h.id);
2131        KeyedSingleton::new(
2132            tick.drop_consistency(),
2133            HydroNode::Snapshot {
2134                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2135                metadata,
2136            },
2137        )
2138    }
2139}
2140
2141impl<'a, K, V, L, B: KeyedSingletonSnapshotBound> KeyedSingleton<K, V, Atomic<L>, B>
2142where
2143    L: Location<'a>,
2144{
2145    /// Returns a keyed singleton with a snapshot of each key-value entry, consistent with the
2146    /// state of the keyed singleton being atomically processed.
2147    ///
2148    /// # Non-Determinism
2149    /// Because this picks a snapshot of each entry, which is continuously changing, each output has a
2150    /// non-deterministic set of entries since each snapshot can be at an arbitrary point in time.
2151    pub fn snapshot_atomic<L2: Location<'a, DropConsistency = L::DropConsistency>>(
2152        self,
2153        tick: &Tick<L2>,
2154        _nondet: NonDet,
2155    ) -> KeyedSingleton<K, V, Tick<L::DropConsistency>, Bounded> {
2156        assert_eq!(
2157            Location::id(tick.parent_location()),
2158            Location::id(self.location.tick.parent_location())
2159        );
2160        KeyedSingleton::new(
2161            tick.drop_consistency(),
2162            HydroNode::Snapshot {
2163                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2164                metadata: tick
2165                    .new_node_metadata(KeyedSingleton::<K, V, Tick<L>, Bounded>::collection_kind()),
2166            },
2167        )
2168    }
2169}
2170
2171impl<'a, K, V, L, B: KeyedSingletonBound<ValueBound = Bounded>> KeyedSingleton<K, V, L, B>
2172where
2173    L: Location<'a>,
2174{
2175    /// Creates a keyed singleton containing only the key-value pairs where the value satisfies a predicate `f`.
2176    ///
2177    /// The closure `f` receives a reference `&V` to each value and returns a boolean. If the predicate
2178    /// returns `true`, the key-value pair is included in the output. If it returns `false`, the pair
2179    /// is filtered out.
2180    ///
2181    /// The closure `f` receives a reference `&V` rather than an owned value `V` because filtering does
2182    /// not modify or take ownership of the values. If you need to modify the values while filtering
2183    /// use [`KeyedSingleton::filter_map`] instead.
2184    ///
2185    /// # Example
2186    /// ```rust
2187    /// # #[cfg(feature = "deploy")] {
2188    /// # use hydro_lang::prelude::*;
2189    /// # use futures::StreamExt;
2190    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
2191    /// let keyed_singleton = // { 1: 2, 2: 4, 3: 1 }
2192    /// # process
2193    /// #     .source_iter(q!(vec![(1, 2), (2, 4), (3, 1)]))
2194    /// #     .into_keyed()
2195    /// #     .first();
2196    /// keyed_singleton.filter(q!(|&v| v > 1))
2197    /// #   .entries()
2198    /// # }, |mut stream| async move {
2199    /// // { 1: 2, 2: 4 }
2200    /// # let mut results = Vec::new();
2201    /// # for _ in 0..2 {
2202    /// #     results.push(stream.next().await.unwrap());
2203    /// # }
2204    /// # results.sort();
2205    /// # assert_eq!(results, vec![(1, 2), (2, 4)]);
2206    /// # }));
2207    /// # }
2208    /// ```
2209    pub fn filter<F>(
2210        self,
2211        f: impl IntoQuotedMut<'a, F, OperatorContext<L, B::UnderlyingBound>> + Copy,
2212    ) -> KeyedSingleton<K, V, L, B>
2213    where
2214        F: Fn(&V) -> bool + 'a,
2215    {
2216        let f: ManualExpr<F, _> =
2217            ManualExpr::new(move |ctx: &OperatorContext<L, B::UnderlyingBound>| {
2218                f.splice_fn1_borrow_ctx(ctx)
2219            });
2220        let filter_f = q!({
2221            let orig = f;
2222            move |t: &(_, _)| orig(&t.1)
2223        })
2224        .splice_fn1_borrow_ctx::<(K, V), bool>(&OperatorContext::<L, B::UnderlyingBound>::new(
2225            &self.location,
2226        ))
2227        .into();
2228
2229        KeyedSingleton::new(
2230            self.location.clone(),
2231            HydroNode::Filter {
2232                f: filter_f,
2233                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2234                metadata: self
2235                    .location
2236                    .new_node_metadata(KeyedSingleton::<K, V, L, B>::collection_kind()),
2237            },
2238        )
2239    }
2240
2241    /// An operator that both filters and maps values. It yields only the key-value pairs where
2242    /// the supplied closure `f` returns `Some(value)`.
2243    ///
2244    /// The closure `f` receives each value `V` and returns `Option<U>`. If the closure returns
2245    /// `Some(new_value)`, the key-value pair `(key, new_value)` is included in the output.
2246    /// If it returns `None`, the key-value pair is filtered out.
2247    ///
2248    /// # Example
2249    /// ```rust
2250    /// # #[cfg(feature = "deploy")] {
2251    /// # use hydro_lang::prelude::*;
2252    /// # use futures::StreamExt;
2253    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
2254    /// let keyed_singleton = // { 1: "42", 2: "hello", 3: "100" }
2255    /// # process
2256    /// #     .source_iter(q!(vec![(1, "42"), (2, "hello"), (3, "100")]))
2257    /// #     .into_keyed()
2258    /// #     .first();
2259    /// keyed_singleton.filter_map(q!(|s| s.parse::<i32>().ok()))
2260    /// #   .entries()
2261    /// # }, |mut stream| async move {
2262    /// // { 1: 42, 3: 100 }
2263    /// # let mut results = Vec::new();
2264    /// # for _ in 0..2 {
2265    /// #     results.push(stream.next().await.unwrap());
2266    /// # }
2267    /// # results.sort();
2268    /// # assert_eq!(results, vec![(1, 42), (3, 100)]);
2269    /// # }));
2270    /// # }
2271    /// ```
2272    pub fn filter_map<F, U>(
2273        self,
2274        f: impl IntoQuotedMut<'a, F, OperatorContext<L, B::UnderlyingBound>> + Copy,
2275    ) -> KeyedSingleton<K, U, L, B::EraseMonotonic>
2276    where
2277        F: Fn(V) -> Option<U> + 'a,
2278    {
2279        let f: ManualExpr<F, _> =
2280            ManualExpr::new(move |ctx: &OperatorContext<L, B::UnderlyingBound>| {
2281                f.splice_fn1_ctx(ctx)
2282            });
2283        let filter_map_f = q!({
2284            let orig = f;
2285            move |(k, v)| orig(v).map(|o| (k, o))
2286        })
2287        .splice_fn1_ctx::<(K, V), Option<(K, U)>>(&OperatorContext::<L, B::UnderlyingBound>::new(
2288            &self.location,
2289        ))
2290        .into();
2291
2292        KeyedSingleton::new(
2293            self.location.clone(),
2294            HydroNode::FilterMap {
2295                f: filter_map_f,
2296                input: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2297                metadata: self.location.new_node_metadata(KeyedSingleton::<
2298                    K,
2299                    U,
2300                    L,
2301                    B::EraseMonotonic,
2302                >::collection_kind()),
2303            },
2304        )
2305    }
2306
2307    /// Returns a keyed singleton with entries consisting of _new_ key-value pairs that have
2308    /// arrived since the previous batch was released. Because each entry's value is final once
2309    /// it appears, every entry is released in exactly one batch and never observed again.
2310    ///
2311    /// To instead observe *every* entry that has appeared so far on each tick, a fully
2312    /// [`Bounded`] keyed singleton can use [`KeyedSingleton::snapshot`].
2313    ///
2314    /// Currently, there is no `all_ticks` dual on [`KeyedSingleton`], instead you may want to use
2315    /// [`KeyedSingleton::into_keyed_stream`] then yield with [`KeyedStream::all_ticks`].
2316    ///
2317    /// # Non-Determinism
2318    /// Because this picks a batch of asynchronously added entries, each output keyed singleton
2319    /// has a non-deterministic set of key-value pairs.
2320    ///
2321    /// In simulation tests, the batching decisions can be scripted by attaching a
2322    /// [`KeyedBatchHook`](crate::sim_hooks::KeyedBatchHook) to the guard via
2323    /// `nondet!(/** reason */ hook = my_hook)`.
2324    pub fn batch<L2: Location<'a, DropConsistency = L::DropConsistency>>(
2325        self,
2326        tick: &Tick<L2>,
2327        mut nondet: NonDet<
2328            Option<
2329                crate::sim_hooks::KeyedBatchHook<K, V, TotalOrder, ExactlyOnce, L::SimHookScope>,
2330            >,
2331        >,
2332    ) -> KeyedSingleton<K, V, Tick<L::DropConsistency>, Bounded> {
2333        assert_eq!(
2334            Location::id(tick.parent_location()),
2335            Location::id(&self.location)
2336        );
2337        let mut metadata =
2338            tick.new_node_metadata(KeyedSingleton::<K, V, Tick<L>, Bounded>::collection_kind());
2339        metadata.op.sim_hook_id = nondet.take_hook().map(|h| h.id);
2340        KeyedSingleton::new(
2341            tick.drop_consistency(),
2342            HydroNode::Batch {
2343                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2344                metadata,
2345            },
2346        )
2347    }
2348}
2349
2350impl<'a, K, V, L, B: KeyedSingletonBound<ValueBound = Bounded>> KeyedSingleton<K, V, Atomic<L>, B>
2351where
2352    L: Location<'a>,
2353{
2354    /// Returns a keyed singleton with entries consisting of _new_ key-value pairs that are being
2355    /// atomically processed.
2356    ///
2357    /// Currently, there is no dual to asynchronously yield back outside the tick, instead you
2358    /// should use [`KeyedSingleton::into_keyed_stream`] and yield a [`KeyedStream`].
2359    ///
2360    /// # Non-Determinism
2361    /// Because this picks a batch of asynchronously added entries, each output keyed singleton
2362    /// has a non-deterministic set of key-value pairs.
2363    pub fn batch_atomic<L2: Location<'a, DropConsistency = L::DropConsistency>>(
2364        self,
2365        tick: &Tick<L2>,
2366        nondet: NonDet,
2367    ) -> KeyedSingleton<K, V, Tick<L::DropConsistency>, Bounded> {
2368        let _ = nondet;
2369        assert_eq!(
2370            Location::id(tick.parent_location()),
2371            Location::id(self.location.tick.parent_location())
2372        );
2373        KeyedSingleton::new(
2374            tick.drop_consistency(),
2375            HydroNode::Batch {
2376                inner: Box::new(self.ir_node.replace(HydroNode::Placeholder)),
2377                metadata: tick
2378                    .new_node_metadata(KeyedSingleton::<K, V, Tick<L>, Bounded>::collection_kind()),
2379            },
2380        )
2381    }
2382}
2383
2384#[cfg(test)]
2385mod tests {
2386    #[cfg(feature = "deploy")]
2387    use futures::{SinkExt, StreamExt};
2388    #[cfg(feature = "deploy")]
2389    use hydro_deploy::Deployment;
2390    #[cfg(any(feature = "deploy", feature = "sim"))]
2391    use stageleft::q;
2392
2393    #[cfg(any(feature = "deploy", feature = "sim"))]
2394    use crate::compile::builder::FlowBuilder;
2395    #[cfg(any(feature = "deploy", feature = "sim"))]
2396    use crate::location::Location;
2397    #[cfg(any(feature = "deploy", feature = "sim"))]
2398    use crate::nondet::nondet;
2399
2400    #[cfg(feature = "deploy")]
2401    #[tokio::test]
2402    async fn key_count_bounded_value() {
2403        let mut deployment = Deployment::new();
2404
2405        let mut flow = FlowBuilder::new();
2406        let node = flow.process::<()>();
2407        let external = flow.external::<()>();
2408
2409        let (input_port, input) = node.source_external_bincode(&external);
2410        let out = input
2411            .into_keyed()
2412            .first()
2413            .key_count()
2414            .sample_eager(nondet!(/** test */))
2415            .send_bincode_external(&external);
2416
2417        let nodes = flow
2418            .with_process(&node, deployment.Localhost())
2419            .with_external(&external, deployment.Localhost())
2420            .deploy(&mut deployment);
2421
2422        deployment.deploy().await.unwrap();
2423
2424        let mut external_in = nodes.connect(input_port).await;
2425        let mut external_out = nodes.connect(out).await;
2426
2427        deployment.start().await.unwrap();
2428
2429        assert_eq!(external_out.next().await.unwrap(), 0);
2430
2431        external_in.send((1, 1)).await.unwrap();
2432        assert_eq!(external_out.next().await.unwrap(), 1);
2433
2434        external_in.send((2, 2)).await.unwrap();
2435        assert_eq!(external_out.next().await.unwrap(), 2);
2436    }
2437
2438    #[cfg(feature = "deploy")]
2439    #[tokio::test]
2440    async fn key_count_unbounded_value() {
2441        let mut deployment = Deployment::new();
2442
2443        let mut flow = FlowBuilder::new();
2444        let node = flow.process::<()>();
2445        let external = flow.external::<()>();
2446
2447        let (input_port, input) = node.source_external_bincode(&external);
2448        let out = input
2449            .into_keyed()
2450            .fold(q!(|| 0), q!(|acc, _| *acc += 1))
2451            .key_count()
2452            .sample_eager(nondet!(/** test */))
2453            .send_bincode_external(&external);
2454
2455        let nodes = flow
2456            .with_process(&node, deployment.Localhost())
2457            .with_external(&external, deployment.Localhost())
2458            .deploy(&mut deployment);
2459
2460        deployment.deploy().await.unwrap();
2461
2462        let mut external_in = nodes.connect(input_port).await;
2463        let mut external_out = nodes.connect(out).await;
2464
2465        deployment.start().await.unwrap();
2466
2467        assert_eq!(external_out.next().await.unwrap(), 0);
2468
2469        external_in.send((1, 1)).await.unwrap();
2470        assert_eq!(external_out.next().await.unwrap(), 1);
2471
2472        external_in.send((1, 2)).await.unwrap();
2473        assert_eq!(external_out.next().await.unwrap(), 1);
2474
2475        external_in.send((2, 2)).await.unwrap();
2476        assert_eq!(external_out.next().await.unwrap(), 2);
2477
2478        external_in.send((1, 1)).await.unwrap();
2479        assert_eq!(external_out.next().await.unwrap(), 2);
2480
2481        external_in.send((3, 1)).await.unwrap();
2482        assert_eq!(external_out.next().await.unwrap(), 3);
2483    }
2484
2485    #[cfg(feature = "deploy")]
2486    #[tokio::test]
2487    async fn into_singleton_bounded_value() {
2488        let mut deployment = Deployment::new();
2489
2490        let mut flow = FlowBuilder::new();
2491        let node = flow.process::<()>();
2492        let external = flow.external::<()>();
2493
2494        let (input_port, input) = node.source_external_bincode(&external);
2495        let out = input
2496            .into_keyed()
2497            .first()
2498            .into_singleton()
2499            .sample_eager(nondet!(/** test */))
2500            .send_bincode_external(&external);
2501
2502        let nodes = flow
2503            .with_process(&node, deployment.Localhost())
2504            .with_external(&external, deployment.Localhost())
2505            .deploy(&mut deployment);
2506
2507        deployment.deploy().await.unwrap();
2508
2509        let mut external_in = nodes.connect(input_port).await;
2510        let mut external_out = nodes.connect(out).await;
2511
2512        deployment.start().await.unwrap();
2513
2514        assert_eq!(
2515            external_out.next().await.unwrap(),
2516            std::collections::HashMap::new()
2517        );
2518
2519        external_in.send((1, 1)).await.unwrap();
2520        assert_eq!(
2521            external_out.next().await.unwrap(),
2522            vec![(1, 1)].into_iter().collect()
2523        );
2524
2525        external_in.send((2, 2)).await.unwrap();
2526        assert_eq!(
2527            external_out.next().await.unwrap(),
2528            vec![(1, 1), (2, 2)].into_iter().collect()
2529        );
2530    }
2531
2532    #[cfg(feature = "deploy")]
2533    #[tokio::test]
2534    async fn into_singleton_unbounded_value() {
2535        let mut deployment = Deployment::new();
2536
2537        let mut flow = FlowBuilder::new();
2538        let node = flow.process::<()>();
2539        let external = flow.external::<()>();
2540
2541        let (input_port, input) = node.source_external_bincode(&external);
2542        let out = input
2543            .into_keyed()
2544            .fold(q!(|| 0), q!(|acc, _| *acc += 1))
2545            .into_singleton()
2546            .sample_eager(nondet!(/** test */))
2547            .send_bincode_external(&external);
2548
2549        let nodes = flow
2550            .with_process(&node, deployment.Localhost())
2551            .with_external(&external, deployment.Localhost())
2552            .deploy(&mut deployment);
2553
2554        deployment.deploy().await.unwrap();
2555
2556        let mut external_in = nodes.connect(input_port).await;
2557        let mut external_out = nodes.connect(out).await;
2558
2559        deployment.start().await.unwrap();
2560
2561        assert_eq!(
2562            external_out.next().await.unwrap(),
2563            std::collections::HashMap::new()
2564        );
2565
2566        external_in.send((1, 1)).await.unwrap();
2567        assert_eq!(
2568            external_out.next().await.unwrap(),
2569            vec![(1, 1)].into_iter().collect()
2570        );
2571
2572        external_in.send((1, 2)).await.unwrap();
2573        assert_eq!(
2574            external_out.next().await.unwrap(),
2575            vec![(1, 2)].into_iter().collect()
2576        );
2577
2578        external_in.send((2, 2)).await.unwrap();
2579        assert_eq!(
2580            external_out.next().await.unwrap(),
2581            vec![(1, 2), (2, 1)].into_iter().collect()
2582        );
2583
2584        external_in.send((1, 1)).await.unwrap();
2585        assert_eq!(
2586            external_out.next().await.unwrap(),
2587            vec![(1, 3), (2, 1)].into_iter().collect()
2588        );
2589
2590        external_in.send((3, 1)).await.unwrap();
2591        assert_eq!(
2592            external_out.next().await.unwrap(),
2593            vec![(1, 3), (2, 1), (3, 1)].into_iter().collect()
2594        );
2595    }
2596
2597    #[cfg(feature = "sim")]
2598    #[test]
2599    fn sim_unbounded_singleton_snapshot() {
2600        let mut flow = FlowBuilder::new();
2601        let node = flow.process::<()>();
2602
2603        let (input_port, input) = node.sim_input();
2604        // Snapshot ingress is lazy and never wakes the tick on its own, so an auxiliary
2605        // trigger stream drives the tick.
2606        let (trigger_port, trigger) = node.sim_input::<i32, _, _>();
2607
2608        let tick = node.tick();
2609        let output = input
2610            .into_keyed()
2611            .fold(q!(|| 0), q!(|acc, _| *acc += 1))
2612            .snapshot(&tick, nondet!(/** test */))
2613            .entries()
2614            .cross_singleton(trigger.batch(&tick, nondet!(/** test */)).count())
2615            .map(q!(|(entry, _)| entry))
2616            .all_ticks()
2617            .sim_output();
2618
2619        let mut saw_final_state = false;
2620
2621        let count = flow.sim().exhaustive(async || {
2622            input_port.send((1, 123));
2623            input_port.send((1, 456));
2624            input_port.send((2, 123));
2625            trigger_port.send(1);
2626
2627            // The single trigger drives exactly one tick, which observes a per-key
2628            // snapshot of the keyed fold (each key may be withheld or revealed at any
2629            // of its buffered versions).
2630            let all = output.collect_sorted::<Vec<_>>().await;
2631            let mut last_by_key = std::collections::HashMap::new();
2632            for (k, v) in all {
2633                match k {
2634                    1 => assert!([1, 2].contains(&v), "invalid version for key 1: {v}"),
2635                    2 => assert_eq!(v, 1, "invalid version for key 2"),
2636                    _ => panic!("unexpected key: {k}"),
2637                }
2638                last_by_key.insert(k, v);
2639            }
2640            if last_by_key.get(&1) == Some(&2) && last_by_key.get(&2) == Some(&1) {
2641                saw_final_state = true;
2642            }
2643        });
2644
2645        // Some schedule must reveal the fully folded value for every key.
2646        assert!(saw_final_state);
2647        // 3 choices for key 1 (withheld, reveal 1, reveal 2) × 2 choices for key 2
2648        // (withheld, reveal 1).
2649        assert_eq!(count, 6);
2650    }
2651
2652    #[cfg(feature = "deploy")]
2653    #[tokio::test]
2654    async fn join_keyed_stream() {
2655        let mut deployment = Deployment::new();
2656
2657        let mut flow = FlowBuilder::new();
2658        let node = flow.process::<()>();
2659        let external = flow.external::<()>();
2660
2661        let tick = node.tick();
2662        let keyed_data = node
2663            .source_iter(q!(vec![(1, 10), (2, 20)]))
2664            .into_keyed()
2665            .batch(&tick, nondet!(/** test */))
2666            .first();
2667        let requests = node
2668            .source_iter(q!(vec![(1, 100), (2, 200), (3, 300)]))
2669            .into_keyed()
2670            .batch(&tick, nondet!(/** test */));
2671
2672        let out = keyed_data
2673            .join_keyed_stream(requests)
2674            .entries()
2675            .all_ticks()
2676            .send_bincode_external(&external);
2677
2678        let nodes = flow
2679            .with_process(&node, deployment.Localhost())
2680            .with_external(&external, deployment.Localhost())
2681            .deploy(&mut deployment);
2682
2683        deployment.deploy().await.unwrap();
2684
2685        let mut external_out = nodes.connect(out).await;
2686
2687        deployment.start().await.unwrap();
2688
2689        let mut results = vec![];
2690        for _ in 0..2 {
2691            results.push(external_out.next().await.unwrap());
2692        }
2693        results.sort();
2694
2695        assert_eq!(results, vec![(1, (10, 100)), (2, (20, 200))]);
2696    }
2697
2698    #[cfg(feature = "sim")]
2699    #[test]
2700    fn threshold_greater_or_equal_monotonic() {
2701        let mut flow = FlowBuilder::new();
2702        let node = flow.process::<()>();
2703
2704        let (input_port, input) = node.sim_input::<(u32, usize), _, _>();
2705        let (thresh_port, thresh_input) = node.sim_input::<(u32, usize), _, _>();
2706
2707        // Create a monotonically increasing keyed singleton via fold with monotone proof
2708        let counts: super::KeyedSingleton<u32, usize, _, super::MonotonicValue> =
2709            input.into_keyed().fold(
2710                q!(|| 0usize),
2711                q!(
2712                    |acc, v| *acc += v,
2713                    monotone = crate::properties::manual_proof!(/** += is monotonic */)
2714                ),
2715            );
2716
2717        // BoundedValue keyed singleton of thresholds (from .first() on unbounded stream)
2718        let thresholds = thresh_input.into_keyed().first();
2719
2720        let output = counts
2721            .threshold_greater_or_equal(thresholds)
2722            .entries()
2723            .sim_output();
2724
2725        let count = flow.sim().exhaustive(async || {
2726            // Set thresholds: key 1 needs value >= 5, key 2 needs value >= 10
2727            thresh_port.send((1, 5));
2728            thresh_port.send((2, 10));
2729
2730            // key 1 gets increments: 3 + 3 = 6, which is >= 5 ✓
2731            input_port.send((1, 3));
2732            input_port.send((1, 3));
2733            // key 2 gets increments: 3 + 3 = 6, which is < 10 ✗
2734            input_port.send((2, 3));
2735            input_port.send((2, 3));
2736
2737            let results = output.collect_sorted::<Vec<_>>().await;
2738            assert_eq!(results, vec![(1, 5)]);
2739        });
2740
2741        assert!(count > 0);
2742    }
2743
2744    #[cfg(feature = "sim")]
2745    #[test]
2746    fn threshold_greater_or_equal_uniform() {
2747        let mut flow = FlowBuilder::new();
2748        let node = flow.process::<()>();
2749
2750        let (input_port, input) = node.sim_input::<(u32, usize), _, _>();
2751
2752        let counts: super::KeyedSingleton<u32, usize, _, super::MonotonicValue> =
2753            input.into_keyed().fold(
2754                q!(|| 0usize),
2755                q!(
2756                    |acc, v| *acc += v,
2757                    monotone = crate::properties::manual_proof!(/** += is monotonic */)
2758                ),
2759            );
2760
2761        // Uniform threshold: all keys need value >= 5
2762        let threshold = node.singleton(q!(5usize));
2763
2764        let output = counts
2765            .threshold_greater_or_equal_uniform(threshold)
2766            .entries()
2767            .sim_output();
2768
2769        let count = flow.sim().exhaustive(async || {
2770            // key 1: 3 + 3 = 6 >= 5 ✓
2771            input_port.send((1, 3));
2772            input_port.send((1, 3));
2773            // key 2: 2 + 2 = 4 < 5 ✗
2774            input_port.send((2, 2));
2775            input_port.send((2, 2));
2776
2777            let results = output.collect_sorted::<Vec<_>>().await;
2778            assert_eq!(results, vec![(1, 5)]);
2779        });
2780
2781        assert!(count > 0);
2782    }
2783
2784    #[cfg(feature = "sim")]
2785    #[test]
2786    fn threshold_greater_or_equal_bounded_value() {
2787        let mut flow = FlowBuilder::new();
2788        let node = flow.process::<()>();
2789
2790        let (input_port, input) = node.sim_input::<(u32, usize), _, _>();
2791        let (thresh_port, thresh_input) = node.sim_input::<(u32, usize), _, _>();
2792
2793        // BoundedValue keyed singleton (values fixed once per key via .first())
2794        let values = input.into_keyed().first();
2795
2796        // BoundedValue keyed singleton of thresholds
2797        let thresholds = thresh_input.into_keyed().first();
2798
2799        let output = values
2800            .threshold_greater_or_equal(thresholds)
2801            .entries()
2802            .sim_output();
2803
2804        let count = flow.sim().exhaustive(async || {
2805            // Set thresholds: key 1 needs >= 3, key 2 needs >= 10
2806            thresh_port.send((1, 3));
2807            thresh_port.send((2, 10));
2808
2809            // key 1 gets value 5 >= 3 ✓, key 2 gets value 4 < 10 ✗
2810            input_port.send((1, 5));
2811            input_port.send((2, 4));
2812
2813            let results = output.collect_sorted::<Vec<_>>().await;
2814            assert_eq!(results, vec![(1, 3)]);
2815        });
2816
2817        assert!(count > 0);
2818    }
2819
2820    #[cfg(feature = "sim")]
2821    #[test]
2822    fn threshold_greater_or_equal_uniform_bounded_value() {
2823        let mut flow = FlowBuilder::new();
2824        let node = flow.process::<()>();
2825
2826        let (input_port, input) = node.sim_input::<(u32, usize), _, _>();
2827
2828        // BoundedValue keyed singleton (values fixed once per key via .first())
2829        let values = input.into_keyed().first();
2830
2831        // Uniform threshold: all keys need value >= 5
2832        let threshold = node.singleton(q!(5usize));
2833
2834        let output = values
2835            .threshold_greater_or_equal_uniform(threshold)
2836            .entries()
2837            .sim_output();
2838
2839        let count = flow.sim().exhaustive(async || {
2840            // key 1 gets value 7 >= 5 ✓, key 2 gets value 3 < 5 ✗
2841            input_port.send((1, 7));
2842            input_port.send((2, 3));
2843
2844            let results = output.collect_sorted::<Vec<_>>().await;
2845            assert_eq!(results, vec![(1, 5)]);
2846        });
2847
2848        assert!(count > 0);
2849    }
2850
2851    #[cfg(feature = "sim")]
2852    #[test]
2853    fn threshold_greater_or_equal_bounded() {
2854        let mut flow = FlowBuilder::new();
2855        let node = flow.process::<()>();
2856
2857        // Bounded keyed singleton (fully known upfront)
2858        let values = node
2859            .source_iter(q!(vec![(1, 6usize), (2, 4usize)]))
2860            .into_keyed()
2861            .first();
2862
2863        // BoundedValue thresholds (from async source)
2864        let (thresh_port, thresh_input) = node.sim_input::<(u32, usize), _, _>();
2865        let thresholds = thresh_input.into_keyed().first();
2866
2867        let output = values
2868            .threshold_greater_or_equal(thresholds)
2869            .entries()
2870            .sim_output();
2871
2872        let count = flow.sim().exhaustive(async || {
2873            thresh_port.send((1, 5));
2874            thresh_port.send((2, 10));
2875
2876            // key 1: 6 >= 5 ✓, key 2: 4 < 10 ✗
2877            let results = output.collect_sorted::<Vec<_>>().await;
2878            assert_eq!(results, vec![(1, 5)]);
2879        });
2880
2881        assert!(count > 0);
2882    }
2883
2884    #[cfg(feature = "sim")]
2885    #[test]
2886    fn threshold_greater_or_equal_uniform_bounded() {
2887        let mut flow = FlowBuilder::new();
2888        let node = flow.process::<()>();
2889
2890        let values = node
2891            .source_iter(q!(vec![(1, 6usize), (2, 4usize)]))
2892            .into_keyed()
2893            .first();
2894        let threshold = node.singleton(q!(5usize));
2895
2896        let output = values
2897            .threshold_greater_or_equal_uniform(threshold)
2898            .entries()
2899            .sim_output();
2900
2901        let count = flow.sim().exhaustive(async || {
2902            // key 1: 6 >= 5 ✓, key 2: 4 < 5 ✗
2903            let results = output.collect_sorted::<Vec<_>>().await;
2904            assert_eq!(results, vec![(1, 5)]);
2905        });
2906
2907        assert!(count > 0);
2908    }
2909
2910    /// A root `MonotonicKeys` keyed singleton's update stream re-sends a key's value whenever it
2911    /// changes. `key_count` must count each key once (repeated updates must not inflate it), and
2912    /// every intermediate count is a valid count of a prefix of the inputs.
2913    #[cfg(feature = "sim")]
2914    #[test]
2915    fn sim_top_level_key_count_monotonic() {
2916        use crate::live_collections::stream::{ExactlyOnce, TotalOrder};
2917
2918        let mut flow = FlowBuilder::new();
2919        let node = flow.process::<()>();
2920
2921        let (input_port, input) = node.sim_input::<(u32, u32), TotalOrder, ExactlyOnce>();
2922        let (trigger_port, trigger) = node.sim_input::<(), TotalOrder, ExactlyOnce>();
2923
2924        let count = input
2925            .into_keyed()
2926            .fold(q!(|| 0u32), q!(|acc, v| *acc += v))
2927            .key_count();
2928
2929        let tick = node.tick();
2930        let output = trigger
2931            .batch(&tick, nondet!(/** test */))
2932            .cross_singleton(count.snapshot(&tick, nondet!(/** test */)))
2933            .map(q!(|(_, count)| count))
2934            .all_ticks()
2935            .sim_output();
2936
2937        let mut observed = std::collections::HashSet::new();
2938        flow.sim().exhaustive(async || {
2939            input_port.send((1, 10));
2940            input_port.send((1, 20));
2941            input_port.send((1, 30));
2942            input_port.send((2, 40));
2943            trigger_port.send(());
2944
2945            let out = output.collect::<Vec<_>>().await;
2946            assert_eq!(out.len(), 1);
2947            assert!(
2948                out[0] <= 2,
2949                "key count inflated by repeated updates: {}",
2950                out[0]
2951            );
2952            observed.insert(out[0]);
2953        });
2954
2955        assert_eq!(observed, [0, 1, 2].into_iter().collect());
2956    }
2957
2958    /// `into_singleton` of a root `MonotonicKeys` keyed singleton applies each key's updates in
2959    /// order: every observed map holds, for each key, some version of that key's value, and the
2960    /// final map is reachable.
2961    #[cfg(feature = "sim")]
2962    #[test]
2963    fn sim_top_level_into_singleton_monotonic() {
2964        use crate::live_collections::stream::{ExactlyOnce, TotalOrder};
2965
2966        let mut flow = FlowBuilder::new();
2967        let node = flow.process::<()>();
2968
2969        let (input_port, input) = node.sim_input::<(u32, u32), TotalOrder, ExactlyOnce>();
2970        let (trigger_port, trigger) = node.sim_input::<(), TotalOrder, ExactlyOnce>();
2971
2972        let map = input
2973            .into_keyed()
2974            .fold(q!(|| 0u32), q!(|acc, v| *acc += v))
2975            .into_singleton();
2976
2977        let tick = node.tick();
2978        let output = trigger
2979            .batch(&tick, nondet!(/** test */))
2980            .cross_singleton(map.snapshot(&tick, nondet!(/** test */)))
2981            .map(q!(|(_, map)| {
2982                let mut entries = map.into_iter().collect::<Vec<_>>();
2983                entries.sort();
2984                entries
2985            }))
2986            .all_ticks()
2987            .sim_output();
2988
2989        let mut saw_final = false;
2990        flow.sim().exhaustive(async || {
2991            input_port.send((1, 10));
2992            input_port.send((1, 20));
2993            input_port.send((2, 5));
2994            trigger_port.send(());
2995
2996            let out = output.collect::<Vec<_>>().await;
2997            assert_eq!(out.len(), 1);
2998            for (k, v) in &out[0] {
2999                match k {
3000                    1 => assert!([10, 30].contains(v), "invalid version for key 1: {v}"),
3001                    2 => assert_eq!(*v, 5, "invalid version for key 2"),
3002                    _ => panic!("unexpected key {k}"),
3003                }
3004            }
3005            if out[0] == vec![(1, 30), (2, 5)] {
3006                saw_final = true;
3007            }
3008        });
3009
3010        assert!(saw_final);
3011    }
3012
3013    /// A root `Unbounded` keyed singleton (a tombstoned update feed) that holds the latest entry
3014    /// sent on `input`: when the entry moves to a different key, `into_keyed_singleton`
3015    /// tombstones the previous key. Built from a `sliced!` state singleton so that it can be
3016    /// simulated.
3017    #[cfg(feature = "sim")]
3018    fn sim_unbounded_keyed_singleton<'a>(
3019        input: crate::live_collections::Stream<
3020            Option<(u32, u32)>,
3021            crate::location::Process<'a>,
3022            crate::live_collections::boundedness::Unbounded,
3023        >,
3024    ) -> super::KeyedSingleton<
3025        u32,
3026        u32,
3027        crate::location::Process<'a>,
3028        crate::live_collections::boundedness::Unbounded,
3029    > {
3030        crate::live_collections::sliced::sliced! {
3031            let batch = use::batch(input, nondet!(/** test */));
3032            let mut latest = use::state(|l| l.singleton(q!(None)));
3033            latest = batch.last().unwrap_or(latest);
3034            latest.clone()
3035        }
3036        .filter_map(q!(|v| v))
3037        .into_keyed_singleton()
3038    }
3039
3040    /// `key_count` of a root `Unbounded` keyed singleton applies removals (tombstones): moving
3041    /// the only entry from key 1 to key 2 never counts more than both keys, and a count of 1 is
3042    /// reached after the removal.
3043    #[cfg(feature = "sim")]
3044    #[test]
3045    fn sim_top_level_key_count_unbounded() {
3046        use crate::live_collections::stream::{ExactlyOnce, TotalOrder};
3047
3048        let mut flow = FlowBuilder::new();
3049        let node = flow.process::<()>();
3050
3051        let (input_port, input) = node.sim_input::<Option<(u32, u32)>, TotalOrder, ExactlyOnce>();
3052        let (trigger_port, trigger) = node.sim_input::<(), TotalOrder, ExactlyOnce>();
3053
3054        let count = sim_unbounded_keyed_singleton(input).key_count();
3055
3056        let tick = node.tick();
3057        let output = trigger
3058            .batch(&tick, nondet!(/** test */))
3059            .cross_singleton(count.snapshot(&tick, nondet!(/** test */)))
3060            .map(q!(|(_, count)| count))
3061            .all_ticks()
3062            .sim_output();
3063
3064        let mut observed = std::collections::HashSet::new();
3065        flow.sim().exhaustive(async || {
3066            input_port.send(Some((1, 10)));
3067            // Moves to key 2, tombstoning key 1.
3068            input_port.send(Some((2, 20)));
3069            trigger_port.send(());
3070
3071            let out = output.collect::<Vec<_>>().await;
3072            assert!(out.len() <= 1);
3073            for count in out {
3074                // Keys evolve independently (updates are only ordered per key), so both keys
3075                // may be counted at once, but never more.
3076                assert!(count <= 2, "key count inflated: {count}");
3077                observed.insert(count);
3078            }
3079        });
3080
3081        assert!(observed.contains(&1));
3082    }
3083
3084    /// `into_singleton` of a root `Unbounded` keyed singleton applies removals (tombstones):
3085    /// every observed map holds valid versions of each key, and the final map (with key 1
3086    /// removed) is reachable.
3087    #[cfg(feature = "sim")]
3088    #[test]
3089    fn sim_top_level_into_singleton_unbounded() {
3090        use crate::live_collections::stream::{ExactlyOnce, TotalOrder};
3091
3092        let mut flow = FlowBuilder::new();
3093        let node = flow.process::<()>();
3094
3095        let (input_port, input) = node.sim_input::<Option<(u32, u32)>, TotalOrder, ExactlyOnce>();
3096        let (trigger_port, trigger) = node.sim_input::<(), TotalOrder, ExactlyOnce>();
3097
3098        let map = sim_unbounded_keyed_singleton(input).into_singleton();
3099
3100        let tick = node.tick();
3101        let output = trigger
3102            .batch(&tick, nondet!(/** test */))
3103            .cross_singleton(map.snapshot(&tick, nondet!(/** test */)))
3104            .map(q!(|(_, map)| {
3105                let mut entries = map.into_iter().collect::<Vec<_>>();
3106                entries.sort();
3107                entries
3108            }))
3109            .all_ticks()
3110            .sim_output();
3111
3112        let mut saw_final = false;
3113        flow.sim().exhaustive(async || {
3114            input_port.send(Some((1, 10)));
3115            // Moves to key 2, tombstoning key 1.
3116            input_port.send(Some((2, 20)));
3117            trigger_port.send(());
3118
3119            let out = output.collect::<Vec<_>>().await;
3120            assert!(out.len() <= 1);
3121            for entries in out {
3122                for (k, v) in &entries {
3123                    assert_eq!(*v, *k * 10, "invalid value for key {k}");
3124                }
3125                if entries == vec![(2, 20)] {
3126                    saw_final = true;
3127                }
3128            }
3129        });
3130
3131        assert!(saw_final);
3132    }
3133}