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 stageleft::{IntoQuotedMut, QuotedWithContext, q};
11
12use super::boundedness::{Bounded, Boundedness, Unbounded};
13use super::keyed_stream::KeyedStream;
14use super::optional::Optional;
15use super::singleton::Singleton;
16use super::stream::{ExactlyOnce, NoOrder, Stream, TotalOrder};
17use crate::compile::ir::{
18    CollectionKind, HydroIrOpMetadata, HydroNode, HydroRoot, KeyedSingletonBoundKind, TeeNode,
19};
20#[cfg(stageleft_runtime)]
21use crate::forward_handle::{CycleCollection, ReceiverComplete};
22use crate::forward_handle::{ForwardRef, TickCycle};
23use crate::live_collections::stream::{Ordering, Retries};
24#[cfg(stageleft_runtime)]
25use crate::location::dynamic::{DynLocation, LocationId};
26use crate::location::tick::DeferTick;
27use crate::location::{Atomic, Location, NoTick, Tick, check_matching_location};
28use crate::manual_expr::ManualExpr;
29use crate::nondet::{NonDet, nondet};
30use crate::properties::ManualProof;
31
32/// A marker trait indicating which components of a [`KeyedSingleton`] may change.
33///
34/// In addition to [`Bounded`] (all entries are fixed) and [`Unbounded`] (entries may be added /
35/// changed, but not removed), this also includes an additional variant [`BoundedValue`], which
36/// indicates that entries may be added over time, but once an entry is added it will never be
37/// removed and its value will never change.
38pub trait KeyedSingletonBound {
39    /// The [`Boundedness`] of the [`Stream`] underlying the keyed singleton.
40    type UnderlyingBound: Boundedness;
41    /// The [`Boundedness`] of each entry's value; [`Bounded`] means it is immutable.
42    type ValueBound: Boundedness;
43
44    /// The type of the keyed singleton if the value for each key is immutable.
45    type WithBoundedValue: KeyedSingletonBound<UnderlyingBound = Self::UnderlyingBound, ValueBound = Bounded>;
46
47    /// The type of the keyed singleton if the value for each key may change asynchronously.
48    type WithUnboundedValue: KeyedSingletonBound<UnderlyingBound = Self::UnderlyingBound, ValueBound = Unbounded>;
49
50    /// Returns the [`KeyedSingletonBoundKind`] corresponding to this type.
51    fn bound_kind() -> KeyedSingletonBoundKind;
52}
53
54impl KeyedSingletonBound for Unbounded {
55    type UnderlyingBound = Unbounded;
56    type ValueBound = Unbounded;
57    type WithBoundedValue = BoundedValue;
58    type WithUnboundedValue = Unbounded;
59
60    fn bound_kind() -> KeyedSingletonBoundKind {
61        KeyedSingletonBoundKind::Unbounded
62    }
63}
64
65impl KeyedSingletonBound for Bounded {
66    type UnderlyingBound = Bounded;
67    type ValueBound = Bounded;
68    type WithBoundedValue = Bounded;
69    type WithUnboundedValue = UnreachableBound;
70
71    fn bound_kind() -> KeyedSingletonBoundKind {
72        KeyedSingletonBoundKind::Bounded
73    }
74}
75
76/// A variation of boundedness specific to [`KeyedSingleton`], which indicates that once a key appears,
77/// its value is bounded and will never change. If the `KeyBound` is [`Bounded`], then the entire set of entries
78/// is bounded, but if it is [`Unbounded`], then new entries may appear asynchronously.
79pub struct BoundedValue;
80
81impl KeyedSingletonBound for BoundedValue {
82    type UnderlyingBound = Unbounded;
83    type ValueBound = Bounded;
84    type WithBoundedValue = BoundedValue;
85    type WithUnboundedValue = Unbounded;
86
87    fn bound_kind() -> KeyedSingletonBoundKind {
88        KeyedSingletonBoundKind::BoundedValue
89    }
90}
91
92#[doc(hidden)]
93pub struct UnreachableBound;
94
95impl KeyedSingletonBound for UnreachableBound {
96    type UnderlyingBound = Bounded;
97    type ValueBound = Unbounded;
98
99    type WithBoundedValue = Bounded;
100    type WithUnboundedValue = UnreachableBound;
101
102    fn bound_kind() -> KeyedSingletonBoundKind {
103        unreachable!("UnreachableBound cannot be instantiated")
104    }
105}
106
107/// Mapping from keys of type `K` to values of type `V`.
108///
109/// Keyed Singletons capture an asynchronously updated mapping from keys of the `K` to values of
110/// type `V`, where the order of keys is non-deterministic. In addition to the standard boundedness
111/// variants ([`Bounded`] for finite and immutable, [`Unbounded`] for asynchronously changing),
112/// keyed singletons can use [`BoundedValue`] to declare that new keys may be added over time, but
113/// keys cannot be removed and the value for each key is immutable.
114///
115/// Type Parameters:
116/// - `K`: the type of the key for each entry
117/// - `V`: the type of the value for each entry
118/// - `Loc`: the [`Location`] where the keyed singleton is materialized
119/// - `Bound`: tracks whether the entries are:
120///     - [`Bounded`] (local and finite)
121///     - [`Unbounded`] (asynchronous with entries added / removed / changed over time)
122///     - [`BoundedValue`] (asynchronous with immutable values for each key and no removals)
123pub struct KeyedSingleton<K, V, Loc, Bound: KeyedSingletonBound> {
124    pub(crate) location: Loc,
125    pub(crate) ir_node: RefCell<HydroNode>,
126
127    _phantom: PhantomData<(K, V, Loc, Bound)>,
128}
129
130impl<'a, K: Clone, V: Clone, Loc: Location<'a>, Bound: KeyedSingletonBound> Clone
131    for KeyedSingleton<K, V, Loc, Bound>
132{
133    fn clone(&self) -> Self {
134        if !matches!(self.ir_node.borrow().deref(), HydroNode::Tee { .. }) {
135            let orig_ir_node = self.ir_node.replace(HydroNode::Placeholder);
136            *self.ir_node.borrow_mut() = HydroNode::Tee {
137                inner: TeeNode(Rc::new(RefCell::new(orig_ir_node))),
138                metadata: self.location.new_node_metadata(Self::collection_kind()),
139            };
140        }
141
142        if let HydroNode::Tee { inner, metadata } = self.ir_node.borrow().deref() {
143            KeyedSingleton {
144                location: self.location.clone(),
145                ir_node: HydroNode::Tee {
146                    inner: TeeNode(inner.0.clone()),
147                    metadata: metadata.clone(),
148                }
149                .into(),
150                _phantom: PhantomData,
151            }
152        } else {
153            unreachable!()
154        }
155    }
156}
157
158impl<'a, K, V, L, B: KeyedSingletonBound> CycleCollection<'a, ForwardRef>
159    for KeyedSingleton<K, V, L, B>
160where
161    L: Location<'a> + NoTick,
162{
163    type Location = L;
164
165    fn create_source(ident: syn::Ident, location: L) -> Self {
166        KeyedSingleton {
167            location: location.clone(),
168            ir_node: RefCell::new(HydroNode::CycleSource {
169                ident,
170                metadata: location.new_node_metadata(Self::collection_kind()),
171            }),
172            _phantom: PhantomData,
173        }
174    }
175}
176
177impl<'a, K, V, L> CycleCollection<'a, TickCycle> for KeyedSingleton<K, V, Tick<L>, Bounded>
178where
179    L: Location<'a>,
180{
181    type Location = Tick<L>;
182
183    fn create_source(ident: syn::Ident, location: Tick<L>) -> Self {
184        KeyedSingleton::new(
185            location.clone(),
186            HydroNode::CycleSource {
187                ident,
188                metadata: location.new_node_metadata(Self::collection_kind()),
189            },
190        )
191    }
192}
193
194impl<'a, K, V, L> DeferTick for KeyedSingleton<K, V, Tick<L>, Bounded>
195where
196    L: Location<'a>,
197{
198    fn defer_tick(self) -> Self {
199        KeyedSingleton::defer_tick(self)
200    }
201}
202
203impl<'a, K, V, L, B: KeyedSingletonBound> ReceiverComplete<'a, ForwardRef>
204    for KeyedSingleton<K, V, L, B>
205where
206    L: Location<'a> + NoTick,
207{
208    fn complete(self, ident: syn::Ident, expected_location: LocationId) {
209        assert_eq!(
210            Location::id(&self.location),
211            expected_location,
212            "locations do not match"
213        );
214        self.location
215            .flow_state()
216            .borrow_mut()
217            .push_root(HydroRoot::CycleSink {
218                ident,
219                input: Box::new(self.ir_node.into_inner()),
220                op_metadata: HydroIrOpMetadata::new(),
221            });
222    }
223}
224
225impl<'a, K, V, L> ReceiverComplete<'a, TickCycle> for KeyedSingleton<K, V, Tick<L>, Bounded>
226where
227    L: Location<'a>,
228{
229    fn complete(self, ident: syn::Ident, expected_location: LocationId) {
230        assert_eq!(
231            Location::id(&self.location),
232            expected_location,
233            "locations do not match"
234        );
235        self.location
236            .flow_state()
237            .borrow_mut()
238            .push_root(HydroRoot::CycleSink {
239                ident,
240                input: Box::new(self.ir_node.into_inner()),
241                op_metadata: HydroIrOpMetadata::new(),
242            });
243    }
244}
245
246impl<'a, K, V, L: Location<'a>, B: KeyedSingletonBound> KeyedSingleton<K, V, L, B> {
247    pub(crate) fn new(location: L, ir_node: HydroNode) -> Self {
248        debug_assert_eq!(ir_node.metadata().location_kind, Location::id(&location));
249        debug_assert_eq!(ir_node.metadata().collection_kind, Self::collection_kind());
250
251        KeyedSingleton {
252            location,
253            ir_node: RefCell::new(ir_node),
254            _phantom: PhantomData,
255        }
256    }
257
258    /// Returns the [`Location`] where this keyed singleton is being materialized.
259    pub fn location(&self) -> &L {
260        &self.location
261    }
262}
263
264#[cfg(stageleft_runtime)]
265fn key_count_inside_tick<'a, K, V, L: Location<'a>>(
266    me: KeyedSingleton<K, V, L, Bounded>,
267) -> Singleton<usize, L, Bounded> {
268    me.entries().count()
269}
270
271#[cfg(stageleft_runtime)]
272fn into_singleton_inside_tick<'a, K, V, L: Location<'a>>(
273    me: KeyedSingleton<K, V, L, Bounded>,
274) -> Singleton<HashMap<K, V>, L, Bounded>
275where
276    K: Eq + Hash,
277{
278    me.entries()
279        .assume_ordering(nondet!(
280            /// Because this is a keyed singleton, there is only one value per key.
281        ))
282        .fold(
283            q!(|| HashMap::new()),
284            q!(|map, (k, v)| {
285                map.insert(k, v);
286            }),
287        )
288}
289
290impl<'a, K, V, L: Location<'a>, B: KeyedSingletonBound> KeyedSingleton<K, V, L, B> {
291    pub(crate) fn collection_kind() -> CollectionKind {
292        CollectionKind::KeyedSingleton {
293            bound: B::bound_kind(),
294            key_type: stageleft::quote_type::<K>().into(),
295            value_type: stageleft::quote_type::<V>().into(),
296        }
297    }
298
299    /// Transforms each value by invoking `f` on each element, with keys staying the same
300    /// after transformation. If you need access to the key, see [`KeyedSingleton::map_with_key`].
301    ///
302    /// If you do not want to modify the stream and instead only want to view
303    /// each item use [`KeyedSingleton::inspect`] instead.
304    ///
305    /// # Example
306    /// ```rust
307    /// # #[cfg(feature = "deploy")] {
308    /// # use hydro_lang::prelude::*;
309    /// # use futures::StreamExt;
310    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
311    /// let keyed_singleton = // { 1: 2, 2: 4 }
312    /// # process
313    /// #     .source_iter(q!(vec![(1, 2), (2, 4)]))
314    /// #     .into_keyed()
315    /// #     .first();
316    /// keyed_singleton.map(q!(|v| v + 1))
317    /// #   .entries()
318    /// # }, |mut stream| async move {
319    /// // { 1: 3, 2: 5 }
320    /// # let mut results = Vec::new();
321    /// # for _ in 0..2 {
322    /// #     results.push(stream.next().await.unwrap());
323    /// # }
324    /// # results.sort();
325    /// # assert_eq!(results, vec![(1, 3), (2, 5)]);
326    /// # }));
327    /// # }
328    /// ```
329    pub fn map<U, F>(self, f: impl IntoQuotedMut<'a, F, L> + Copy) -> KeyedSingleton<K, U, L, B>
330    where
331        F: Fn(V) -> U + 'a,
332    {
333        let f: ManualExpr<F, _> = ManualExpr::new(move |ctx: &L| f.splice_fn1_ctx(ctx));
334        let map_f = q!({
335            let orig = f;
336            move |(k, v)| (k, orig(v))
337        })
338        .splice_fn1_ctx::<(K, V), (K, U)>(&self.location)
339        .into();
340
341        KeyedSingleton::new(
342            self.location.clone(),
343            HydroNode::Map {
344                f: map_f,
345                input: Box::new(self.ir_node.into_inner()),
346                metadata: self
347                    .location
348                    .new_node_metadata(KeyedSingleton::<K, U, L, B>::collection_kind()),
349            },
350        )
351    }
352
353    /// Transforms each value by invoking `f` on each key-value pair, with keys staying the same
354    /// after transformation. Unlike [`KeyedSingleton::map`], this gives access to both the key and value.
355    ///
356    /// The closure `f` receives a tuple `(K, V)` containing both the key and value, and returns
357    /// the new value `U`. The key remains unchanged in the output.
358    ///
359    /// # Example
360    /// ```rust
361    /// # #[cfg(feature = "deploy")] {
362    /// # use hydro_lang::prelude::*;
363    /// # use futures::StreamExt;
364    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
365    /// let keyed_singleton = // { 1: 2, 2: 4 }
366    /// # process
367    /// #     .source_iter(q!(vec![(1, 2), (2, 4)]))
368    /// #     .into_keyed()
369    /// #     .first();
370    /// keyed_singleton.map_with_key(q!(|(k, v)| k + v))
371    /// #   .entries()
372    /// # }, |mut stream| async move {
373    /// // { 1: 3, 2: 6 }
374    /// # let mut results = Vec::new();
375    /// # for _ in 0..2 {
376    /// #     results.push(stream.next().await.unwrap());
377    /// # }
378    /// # results.sort();
379    /// # assert_eq!(results, vec![(1, 3), (2, 6)]);
380    /// # }));
381    /// # }
382    /// ```
383    pub fn map_with_key<U, F>(
384        self,
385        f: impl IntoQuotedMut<'a, F, L> + Copy,
386    ) -> KeyedSingleton<K, U, L, B>
387    where
388        F: Fn((K, V)) -> U + 'a,
389        K: Clone,
390    {
391        let f: ManualExpr<F, _> = ManualExpr::new(move |ctx: &L| f.splice_fn1_ctx(ctx));
392        let map_f = q!({
393            let orig = f;
394            move |(k, v)| {
395                let out = orig((Clone::clone(&k), v));
396                (k, out)
397            }
398        })
399        .splice_fn1_ctx::<(K, V), (K, U)>(&self.location)
400        .into();
401
402        KeyedSingleton::new(
403            self.location.clone(),
404            HydroNode::Map {
405                f: map_f,
406                input: Box::new(self.ir_node.into_inner()),
407                metadata: self
408                    .location
409                    .new_node_metadata(KeyedSingleton::<K, U, L, B>::collection_kind()),
410            },
411        )
412    }
413
414    /// Gets the number of keys in the keyed singleton.
415    ///
416    /// The output singleton will be unbounded if the input is [`Unbounded`] or [`BoundedValue`],
417    /// since keys may be added / removed over time. When the set of keys changes, the count will
418    /// be asynchronously updated.
419    ///
420    /// # Example
421    /// ```rust
422    /// # #[cfg(feature = "deploy")] {
423    /// # use hydro_lang::prelude::*;
424    /// # use futures::StreamExt;
425    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
426    /// # let tick = process.tick();
427    /// let keyed_singleton = // { 1: "a", 2: "b", 3: "c" }
428    /// # process
429    /// #     .source_iter(q!(vec![(1, "a"), (2, "b"), (3, "c")]))
430    /// #     .into_keyed()
431    /// #     .batch(&tick, nondet!(/** test */))
432    /// #     .first();
433    /// keyed_singleton.key_count()
434    /// # .all_ticks()
435    /// # }, |mut stream| async move {
436    /// // 3
437    /// # assert_eq!(stream.next().await.unwrap(), 3);
438    /// # }));
439    /// # }
440    /// ```
441    pub fn key_count(self) -> Singleton<usize, L, B::UnderlyingBound> {
442        if B::ValueBound::BOUNDED {
443            let me: KeyedSingleton<K, V, L, B::WithBoundedValue> = KeyedSingleton {
444                location: self.location,
445                ir_node: self.ir_node,
446                _phantom: PhantomData,
447            };
448
449            me.entries().count()
450        } else if L::is_top_level()
451            && let Some(tick) = self.location.try_tick()
452        {
453            let me: KeyedSingleton<K, V, L, B::WithUnboundedValue> = KeyedSingleton {
454                location: self.location,
455                ir_node: self.ir_node,
456                _phantom: PhantomData,
457            };
458
459            let out =
460                key_count_inside_tick(me.snapshot(&tick, nondet!(/** eventually stabilizes */)))
461                    .latest();
462            Singleton::new(out.location, out.ir_node.into_inner())
463        } else {
464            panic!("Unbounded KeyedSingleton inside a tick");
465        }
466    }
467
468    /// Converts this keyed singleton into a [`Singleton`] containing a `HashMap` from keys to values.
469    ///
470    /// As the values for each key are updated asynchronously, the `HashMap` will be updated
471    /// asynchronously as well.
472    ///
473    /// # Example
474    /// ```rust
475    /// # #[cfg(feature = "deploy")] {
476    /// # use hydro_lang::prelude::*;
477    /// # use futures::StreamExt;
478    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
479    /// let keyed_singleton = // { 1: "a", 2: "b", 3: "c" }
480    /// # process
481    /// #     .source_iter(q!(vec![(1, "a".to_string()), (2, "b".to_string()), (3, "c".to_string())]))
482    /// #     .into_keyed()
483    /// #     .batch(&process.tick(), nondet!(/** test */))
484    /// #     .first();
485    /// keyed_singleton.into_singleton()
486    /// # .all_ticks()
487    /// # }, |mut stream| async move {
488    /// // { 1: "a", 2: "b", 3: "c" }
489    /// # assert_eq!(stream.next().await.unwrap(), vec![(1, "a".to_string()), (2, "b".to_string()), (3, "c".to_string())].into_iter().collect());
490    /// # }));
491    /// # }
492    /// ```
493    pub fn into_singleton(self) -> Singleton<HashMap<K, V>, L, B::UnderlyingBound>
494    where
495        K: Eq + Hash,
496    {
497        if B::ValueBound::BOUNDED {
498            let me: KeyedSingleton<K, V, L, B::WithBoundedValue> = KeyedSingleton {
499                location: self.location,
500                ir_node: self.ir_node,
501                _phantom: PhantomData,
502            };
503
504            me.entries()
505                .assume_ordering(nondet!(
506                    /// Because this is a keyed singleton, there is only one value per key.
507                ))
508                .fold(
509                    q!(|| HashMap::new()),
510                    q!(|map, (k, v)| {
511                        // TODO(shadaj): make this commutative but really-debug-assert that there is no key overlap
512                        map.insert(k, v);
513                    }),
514                )
515        } else if L::is_top_level()
516            && let Some(tick) = self.location.try_tick()
517        {
518            let me: KeyedSingleton<K, V, L, B::WithUnboundedValue> = KeyedSingleton {
519                location: self.location,
520                ir_node: self.ir_node,
521                _phantom: PhantomData,
522            };
523
524            let out = into_singleton_inside_tick(
525                me.snapshot(&tick, nondet!(/** eventually stabilizes */)),
526            )
527            .latest();
528            Singleton::new(out.location, out.ir_node.into_inner())
529        } else {
530            panic!("Unbounded KeyedSingleton inside a tick");
531        }
532    }
533
534    /// An operator which allows you to "name" a `HydroNode`.
535    /// This is only used for testing, to correlate certain `HydroNode`s with IDs.
536    pub fn ir_node_named(self, name: &str) -> KeyedSingleton<K, V, L, B> {
537        {
538            let mut node = self.ir_node.borrow_mut();
539            let metadata = node.metadata_mut();
540            metadata.tag = Some(name.to_string());
541        }
542        self
543    }
544}
545
546impl<'a, K, V, L: Location<'a>, B: KeyedSingletonBound<ValueBound = Bounded>>
547    KeyedSingleton<K, V, L, B>
548{
549    /// Flattens the keyed singleton into an unordered stream of key-value pairs.
550    ///
551    /// The value for each key must be bounded, otherwise the resulting stream elements would be
552    /// non-determinstic. As new entries are added to the keyed singleton, they will be streamed
553    /// into the output.
554    ///
555    /// # Example
556    /// ```rust
557    /// # #[cfg(feature = "deploy")] {
558    /// # use hydro_lang::prelude::*;
559    /// # use futures::StreamExt;
560    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
561    /// let keyed_singleton = // { 1: 2, 2: 4 }
562    /// # process
563    /// #     .source_iter(q!(vec![(1, 2), (2, 4)]))
564    /// #     .into_keyed()
565    /// #     .first();
566    /// keyed_singleton.entries()
567    /// # }, |mut stream| async move {
568    /// // (1, 2), (2, 4) in any order
569    /// # let mut results = Vec::new();
570    /// # for _ in 0..2 {
571    /// #     results.push(stream.next().await.unwrap());
572    /// # }
573    /// # results.sort();
574    /// # assert_eq!(results, vec![(1, 2), (2, 4)]);
575    /// # }));
576    /// # }
577    /// ```
578    pub fn entries(self) -> Stream<(K, V), L, B::UnderlyingBound, NoOrder, ExactlyOnce> {
579        self.into_keyed_stream().entries()
580    }
581
582    /// Flattens the keyed singleton into an unordered stream of just the values.
583    ///
584    /// The value for each key must be bounded, otherwise the resulting stream elements would be
585    /// non-determinstic. As new entries are added to the keyed singleton, they will be streamed
586    /// into the output.
587    ///
588    /// # Example
589    /// ```rust
590    /// # #[cfg(feature = "deploy")] {
591    /// # use hydro_lang::prelude::*;
592    /// # use futures::StreamExt;
593    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
594    /// let keyed_singleton = // { 1: 2, 2: 4 }
595    /// # process
596    /// #     .source_iter(q!(vec![(1, 2), (2, 4)]))
597    /// #     .into_keyed()
598    /// #     .first();
599    /// keyed_singleton.values()
600    /// # }, |mut stream| async move {
601    /// // 2, 4 in any order
602    /// # let mut results = Vec::new();
603    /// # for _ in 0..2 {
604    /// #     results.push(stream.next().await.unwrap());
605    /// # }
606    /// # results.sort();
607    /// # assert_eq!(results, vec![2, 4]);
608    /// # }));
609    /// # }
610    /// ```
611    pub fn values(self) -> Stream<V, L, B::UnderlyingBound, NoOrder, ExactlyOnce> {
612        let map_f = q!(|(_, v)| v)
613            .splice_fn1_ctx::<(K, V), V>(&self.location)
614            .into();
615
616        Stream::new(
617            self.location.clone(),
618            HydroNode::Map {
619                f: map_f,
620                input: Box::new(self.ir_node.into_inner()),
621                metadata: self.location.new_node_metadata(Stream::<
622                    V,
623                    L,
624                    B::UnderlyingBound,
625                    NoOrder,
626                    ExactlyOnce,
627                >::collection_kind()),
628            },
629        )
630    }
631
632    /// Flattens the keyed singleton into an unordered stream of just the keys.
633    ///
634    /// The value for each key must be bounded, otherwise the removal of keys would result in
635    /// non-determinism. As new entries are added to the keyed singleton, they will be streamed
636    /// into the output.
637    ///
638    /// # Example
639    /// ```rust
640    /// # #[cfg(feature = "deploy")] {
641    /// # use hydro_lang::prelude::*;
642    /// # use futures::StreamExt;
643    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
644    /// let keyed_singleton = // { 1: 2, 2: 4 }
645    /// # process
646    /// #     .source_iter(q!(vec![(1, 2), (2, 4)]))
647    /// #     .into_keyed()
648    /// #     .first();
649    /// keyed_singleton.keys()
650    /// # }, |mut stream| async move {
651    /// // 1, 2 in any order
652    /// # let mut results = Vec::new();
653    /// # for _ in 0..2 {
654    /// #     results.push(stream.next().await.unwrap());
655    /// # }
656    /// # results.sort();
657    /// # assert_eq!(results, vec![1, 2]);
658    /// # }));
659    /// # }
660    /// ```
661    pub fn keys(self) -> Stream<K, L, B::UnderlyingBound, NoOrder, ExactlyOnce> {
662        self.entries().map(q!(|(k, _)| k))
663    }
664
665    /// Given a bounded stream of keys `K`, returns a new keyed singleton containing only the
666    /// entries whose keys are not in the provided stream.
667    ///
668    /// # Example
669    /// ```rust
670    /// # #[cfg(feature = "deploy")] {
671    /// # use hydro_lang::prelude::*;
672    /// # use futures::StreamExt;
673    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
674    /// let tick = process.tick();
675    /// let keyed_singleton = // { 1: 2, 2: 4 }
676    /// # process
677    /// #     .source_iter(q!(vec![(1, 2), (2, 4)]))
678    /// #     .into_keyed()
679    /// #     .first()
680    /// #     .batch(&tick, nondet!(/** test */));
681    /// let keys_to_remove = process
682    ///     .source_iter(q!(vec![1]))
683    ///     .batch(&tick, nondet!(/** test */));
684    /// keyed_singleton.filter_key_not_in(keys_to_remove)
685    /// #   .entries().all_ticks()
686    /// # }, |mut stream| async move {
687    /// // { 2: 4 }
688    /// # for w in vec![(2, 4)] {
689    /// #     assert_eq!(stream.next().await.unwrap(), w);
690    /// # }
691    /// # }));
692    /// # }
693    /// ```
694    pub fn filter_key_not_in<O2: Ordering, R2: Retries>(
695        self,
696        other: Stream<K, L, Bounded, O2, R2>,
697    ) -> Self
698    where
699        K: Hash + Eq,
700    {
701        check_matching_location(&self.location, &other.location);
702
703        KeyedSingleton::new(
704            self.location.clone(),
705            HydroNode::AntiJoin {
706                pos: Box::new(self.ir_node.into_inner()),
707                neg: Box::new(other.ir_node.into_inner()),
708                metadata: self.location.new_node_metadata(Self::collection_kind()),
709            },
710        )
711    }
712
713    /// An operator which allows you to "inspect" each value of a keyed singleton without
714    /// modifying it. The closure `f` is called on a reference to each value. This is
715    /// mainly useful for debugging, and should not be used to generate side-effects.
716    ///
717    /// # Example
718    /// ```rust
719    /// # #[cfg(feature = "deploy")] {
720    /// # use hydro_lang::prelude::*;
721    /// # use futures::StreamExt;
722    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
723    /// let keyed_singleton = // { 1: 2, 2: 4 }
724    /// # process
725    /// #     .source_iter(q!(vec![(1, 2), (2, 4)]))
726    /// #     .into_keyed()
727    /// #     .first();
728    /// keyed_singleton
729    ///     .inspect(q!(|v| println!("{}", v)))
730    /// #   .entries()
731    /// # }, |mut stream| async move {
732    /// // { 1: 2, 2: 4 }
733    /// # for w in vec![(1, 2), (2, 4)] {
734    /// #     assert_eq!(stream.next().await.unwrap(), w);
735    /// # }
736    /// # }));
737    /// # }
738    /// ```
739    pub fn inspect<F>(self, f: impl IntoQuotedMut<'a, F, L> + Copy) -> Self
740    where
741        F: Fn(&V) + 'a,
742    {
743        let f: ManualExpr<F, _> = ManualExpr::new(move |ctx: &L| f.splice_fn1_borrow_ctx(ctx));
744        let inspect_f = q!({
745            let orig = f;
746            move |t: &(_, _)| orig(&t.1)
747        })
748        .splice_fn1_borrow_ctx::<(K, V), ()>(&self.location)
749        .into();
750
751        KeyedSingleton::new(
752            self.location.clone(),
753            HydroNode::Inspect {
754                f: inspect_f,
755                input: Box::new(self.ir_node.into_inner()),
756                metadata: self.location.new_node_metadata(Self::collection_kind()),
757            },
758        )
759    }
760
761    /// An operator which allows you to "inspect" each entry of a keyed singleton without
762    /// modifying it. The closure `f` is called on a reference to each key-value pair. This is
763    /// mainly useful for debugging, and should not be used to generate side-effects.
764    ///
765    /// # Example
766    /// ```rust
767    /// # #[cfg(feature = "deploy")] {
768    /// # use hydro_lang::prelude::*;
769    /// # use futures::StreamExt;
770    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
771    /// let keyed_singleton = // { 1: 2, 2: 4 }
772    /// # process
773    /// #     .source_iter(q!(vec![(1, 2), (2, 4)]))
774    /// #     .into_keyed()
775    /// #     .first();
776    /// keyed_singleton
777    ///     .inspect_with_key(q!(|(k, v)| println!("{}: {}", k, v)))
778    /// #   .entries()
779    /// # }, |mut stream| async move {
780    /// // { 1: 2, 2: 4 }
781    /// # for w in vec![(1, 2), (2, 4)] {
782    /// #     assert_eq!(stream.next().await.unwrap(), w);
783    /// # }
784    /// # }));
785    /// # }
786    /// ```
787    pub fn inspect_with_key<F>(self, f: impl IntoQuotedMut<'a, F, L>) -> Self
788    where
789        F: Fn(&(K, V)) + 'a,
790    {
791        let inspect_f = f.splice_fn1_borrow_ctx::<(K, V), ()>(&self.location).into();
792
793        KeyedSingleton::new(
794            self.location.clone(),
795            HydroNode::Inspect {
796                f: inspect_f,
797                input: Box::new(self.ir_node.into_inner()),
798                metadata: self.location.new_node_metadata(Self::collection_kind()),
799            },
800        )
801    }
802
803    /// Gets the key-value tuple with the largest key among all entries in this [`KeyedSingleton`].
804    ///
805    /// Because this method requires values to be bounded, the output [`Optional`] will only be
806    /// asynchronously updated if a new key is added that is higher than the previous max key.
807    ///
808    /// # Example
809    /// ```rust
810    /// # #[cfg(feature = "deploy")] {
811    /// # use hydro_lang::prelude::*;
812    /// # use futures::StreamExt;
813    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
814    /// let tick = process.tick();
815    /// let keyed_singleton = // { 1: 123, 2: 456, 0: 789 }
816    /// # Stream::<_, _>::from(process.source_iter(q!(vec![(1, 123), (2, 456), (0, 789)])))
817    /// #     .into_keyed()
818    /// #     .first();
819    /// keyed_singleton.get_max_key()
820    /// # .sample_eager(nondet!(/** test */))
821    /// # }, |mut stream| async move {
822    /// // (2, 456)
823    /// # assert_eq!(stream.next().await.unwrap(), (2, 456));
824    /// # }));
825    /// # }
826    /// ```
827    pub fn get_max_key(self) -> Optional<(K, V), L, B::UnderlyingBound>
828    where
829        K: Ord,
830    {
831        self.entries()
832            .assume_ordering_trusted(nondet!(
833                /// There is only one element associated with each key, and the keys are totallly
834                /// ordered so we will produce a deterministic value. The closure technically
835                /// isn't commutative in the case where both passed entries have the same key
836                /// but different values.
837                ///
838                /// In the future, we may want to have an `assume!(...)` statement in the UDF that
839                /// the two inputs do not have the same key.
840            ))
841            .reduce(q!(
842                move |curr, new| {
843                    if new.0 > curr.0 {
844                        *curr = new;
845                    }
846                },
847                idempotent = ManualProof(/* repeated elements are ignored */)
848            ))
849    }
850
851    /// Converts this keyed singleton into a [`KeyedStream`] with each group having a single
852    /// element, the value.
853    ///
854    /// This is the equivalent of [`Singleton::into_stream`] but keyed.
855    ///
856    /// # Example
857    /// ```rust
858    /// # #[cfg(feature = "deploy")] {
859    /// # use hydro_lang::prelude::*;
860    /// # use futures::StreamExt;
861    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
862    /// let keyed_singleton = // { 1: 2, 2: 4 }
863    /// # Stream::<_, _>::from(process.source_iter(q!(vec![(1, 2), (2, 4)])))
864    /// #     .into_keyed()
865    /// #     .first();
866    /// keyed_singleton
867    ///     .clone()
868    ///     .into_keyed_stream()
869    ///     .interleave(
870    ///         keyed_singleton.into_keyed_stream()
871    ///     )
872    /// #   .entries()
873    /// # }, |mut stream| async move {
874    /// /// // { 1: [2, 2], 2: [4, 4] }
875    /// # for w in vec![(1, 2), (2, 4), (1, 2), (2, 4)] {
876    /// #     assert_eq!(stream.next().await.unwrap(), w);
877    /// # }
878    /// # }));
879    /// # }
880    /// ```
881    pub fn into_keyed_stream(
882        self,
883    ) -> KeyedStream<K, V, L, B::UnderlyingBound, TotalOrder, ExactlyOnce> {
884        KeyedStream::new(
885            self.location.clone(),
886            HydroNode::Cast {
887                inner: Box::new(self.ir_node.into_inner()),
888                metadata: self.location.new_node_metadata(KeyedStream::<
889                    K,
890                    V,
891                    L,
892                    B::UnderlyingBound,
893                    TotalOrder,
894                    ExactlyOnce,
895                >::collection_kind()),
896            },
897        )
898    }
899}
900
901impl<'a, K: Hash + Eq, V, L: Location<'a>> KeyedSingleton<K, V, Tick<L>, Bounded> {
902    /// Gets the value associated with a specific key from the keyed singleton.
903    ///
904    /// # Example
905    /// ```rust
906    /// # #[cfg(feature = "deploy")] {
907    /// # use hydro_lang::prelude::*;
908    /// # use futures::StreamExt;
909    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
910    /// let tick = process.tick();
911    /// let keyed_data = process
912    ///     .source_iter(q!(vec![(1, 2), (2, 3)]))
913    ///     .into_keyed()
914    ///     .batch(&tick, nondet!(/** test */))
915    ///     .first();
916    /// let key = tick.singleton(q!(1));
917    /// keyed_data.get(key).all_ticks()
918    /// # }, |mut stream| async move {
919    /// // 2
920    /// # assert_eq!(stream.next().await.unwrap(), 2);
921    /// # }));
922    /// # }
923    /// ```
924    pub fn get(self, key: Singleton<K, Tick<L>, Bounded>) -> Optional<V, Tick<L>, Bounded> {
925        self.entries()
926            .join(key.into_stream().map(q!(|k| (k, ()))))
927            .map(q!(|(_, (v, _))| v))
928            .assume_ordering::<TotalOrder>(nondet!(/** only a single key, so totally ordered */))
929            .first()
930    }
931
932    /// Given a keyed stream of lookup requests, where the key is the lookup and the value
933    /// is some additional metadata, emits a keyed stream of lookup results where the key
934    /// is the same as before, but the value is a tuple of the lookup result and the metadata
935    /// of the request. If the key is not found, no output will be produced.
936    ///
937    /// # Example
938    /// ```rust
939    /// # #[cfg(feature = "deploy")] {
940    /// # use hydro_lang::prelude::*;
941    /// # use futures::StreamExt;
942    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
943    /// let tick = process.tick();
944    /// let keyed_data = process
945    ///     .source_iter(q!(vec![(1, 10), (2, 20)]))
946    ///     .into_keyed()
947    ///     .batch(&tick, nondet!(/** test */))
948    ///     .first();
949    /// let other_data = process
950    ///     .source_iter(q!(vec![(1, 100), (2, 200), (1, 101)]))
951    ///     .into_keyed()
952    ///     .batch(&tick, nondet!(/** test */));
953    /// keyed_data.get_many_if_present(other_data).entries().all_ticks()
954    /// # }, |mut stream| async move {
955    /// // { 1: [(10, 100), (10, 101)], 2: [(20, 200)] } in any order
956    /// # let mut results = vec![];
957    /// # for _ in 0..3 {
958    /// #     results.push(stream.next().await.unwrap());
959    /// # }
960    /// # results.sort();
961    /// # assert_eq!(results, vec![(1, (10, 100)), (1, (10, 101)), (2, (20, 200))]);
962    /// # }));
963    /// # }
964    /// ```
965    pub fn get_many_if_present<O2: Ordering, R2: Retries, V2>(
966        self,
967        requests: KeyedStream<K, V2, Tick<L>, Bounded, O2, R2>,
968    ) -> KeyedStream<K, (V, V2), Tick<L>, Bounded, NoOrder, R2> {
969        self.entries()
970            .weaker_retries::<R2>()
971            .join(requests.entries())
972            .into_keyed()
973    }
974
975    /// Given a keyed stream of lookup requests, where the key is the lookup and the value
976    /// is some additional metadata, emits a keyed stream of lookup results where the key
977    /// is the same as before, but the value is a tuple of the lookup result (as `Option<V>`)
978    /// and the metadata of the request. Unlike `get_many_if_present`, this returns all request
979    /// keys, with `None` for keys that are not found.
980    ///
981    /// # Example
982    /// ```rust
983    /// # #[cfg(feature = "deploy")] {
984    /// # use hydro_lang::prelude::*;
985    /// # use futures::StreamExt;
986    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
987    /// let tick = process.tick();
988    /// let keyed_data = process
989    ///     .source_iter(q!(vec![(1, 10), (2, 20)]))
990    ///     .into_keyed()
991    ///     .batch(&tick, nondet!(/** test */))
992    ///     .first();
993    /// let other_data = process
994    ///     .source_iter(q!(vec![(1, 100), (2, 200), (3, 300)]))
995    ///     .into_keyed()
996    ///     .batch(&tick, nondet!(/** test */));
997    /// keyed_data.get_many(other_data).entries().all_ticks()
998    /// # }, |mut stream| async move {
999    /// // { 1: [(Some(10), 100)], 2: [(Some(20), 200)], 3: [(None, 300)] } in any order
1000    /// # let mut results = vec![];
1001    /// # for _ in 0..3 {
1002    /// #     results.push(stream.next().await.unwrap());
1003    /// # }
1004    /// # results.sort();
1005    /// # assert_eq!(results, vec![(1, (Some(10), 100)), (2, (Some(20), 200)), (3, (None, 300))]);
1006    /// # }));
1007    /// # }
1008    /// ```
1009    #[expect(clippy::type_complexity, reason = "stream types")]
1010    pub fn get_many<O2: Ordering, R2: Retries, V2>(
1011        self,
1012        requests: KeyedStream<K, V2, Tick<L>, Bounded, O2, R2>,
1013    ) -> KeyedStream<K, (Option<V>, V2), Tick<L>, Bounded, NoOrder, R2>
1014    where
1015        K: Clone,
1016        V: Clone,
1017        V2: Clone,
1018    {
1019        let lookup_result = self.clone().get_many_if_present(requests.clone());
1020        let missing_keys = requests.filter_key_not_in(self.keys()).weakest_ordering();
1021
1022        lookup_result
1023            .map(q!(|(v, v2)| (Some(v), v2)))
1024            .chain(missing_keys.map(q!(|v2| (None, v2))))
1025    }
1026
1027    /// For each entry in `self`, looks up the entry in the `from` with a key that matches the
1028    /// **value** of the entry in `self`. The output is a keyed singleton with tuple values
1029    /// containing the value from `self` and an option of the value from `from`. If the key is not
1030    /// present in `from`, the option will be [`None`].
1031    ///
1032    /// # Example
1033    /// ```rust
1034    /// # #[cfg(feature = "deploy")] {
1035    /// # use hydro_lang::prelude::*;
1036    /// # use futures::StreamExt;
1037    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1038    /// # let tick = process.tick();
1039    /// let requests = // { 1: 10, 2: 20 }
1040    /// # process
1041    /// #     .source_iter(q!(vec![(1, 10), (2, 20)]))
1042    /// #     .into_keyed()
1043    /// #     .batch(&tick, nondet!(/** test */))
1044    /// #     .first();
1045    /// let other_data = // { 10: 100, 11: 101 }
1046    /// # process
1047    /// #     .source_iter(q!(vec![(10, 100), (11, 101)]))
1048    /// #     .into_keyed()
1049    /// #     .batch(&tick, nondet!(/** test */))
1050    /// #     .first();
1051    /// requests.get_from(other_data)
1052    /// # .entries().all_ticks()
1053    /// # }, |mut stream| async move {
1054    /// // { 1: (10, Some(100)), 2: (20, None) }
1055    /// # let mut results = vec![];
1056    /// # for _ in 0..2 {
1057    /// #     results.push(stream.next().await.unwrap());
1058    /// # }
1059    /// # results.sort();
1060    /// # assert_eq!(results, vec![(1, (10, Some(100))), (2, (20, None))]);
1061    /// # }));
1062    /// # }
1063    /// ```
1064    pub fn get_from<V2: Clone>(
1065        self,
1066        from: KeyedSingleton<V, V2, Tick<L>, Bounded>,
1067    ) -> KeyedSingleton<K, (V, Option<V2>), Tick<L>, Bounded>
1068    where
1069        K: Clone,
1070        V: Hash + Eq + Clone,
1071    {
1072        let to_lookup = self.entries().map(q!(|(k, v)| (v, k))).into_keyed();
1073        let lookup_result = from.get_many_if_present(to_lookup.clone());
1074        let missing_values =
1075            to_lookup.filter_key_not_in(lookup_result.clone().entries().map(q!(|t| t.0)));
1076        let result_stream = lookup_result
1077            .entries()
1078            .map(q!(|(v, (v2, k))| (k, (v, Some(v2)))))
1079            .into_keyed()
1080            .chain(
1081                missing_values
1082                    .entries()
1083                    .map(q!(|(v, k)| (k, (v, None))))
1084                    .into_keyed(),
1085            );
1086
1087        KeyedSingleton::new(
1088            result_stream.location.clone(),
1089            HydroNode::Cast {
1090                inner: Box::new(result_stream.ir_node.into_inner()),
1091                metadata: result_stream.location.new_node_metadata(KeyedSingleton::<
1092                    K,
1093                    (V, Option<V2>),
1094                    Tick<L>,
1095                    Bounded,
1096                >::collection_kind(
1097                )),
1098            },
1099        )
1100    }
1101}
1102
1103impl<'a, K, V, L, B: KeyedSingletonBound> KeyedSingleton<K, V, L, B>
1104where
1105    L: Location<'a>,
1106{
1107    /// Shifts this keyed singleton into an atomic context, which guarantees that any downstream logic
1108    /// will all be executed synchronously before any outputs are yielded (in [`KeyedSingleton::end_atomic`]).
1109    ///
1110    /// This is useful to enforce local consistency constraints, such as ensuring that a write is
1111    /// processed before an acknowledgement is emitted. Entering an atomic section requires a [`Tick`]
1112    /// argument that declares where the keyed singleton will be atomically processed. Batching a
1113    /// keyed singleton into the _same_ [`Tick`] will preserve the synchronous execution, while
1114    /// batching into a different [`Tick`] will introduce asynchrony.
1115    pub fn atomic(self, tick: &Tick<L>) -> KeyedSingleton<K, V, Atomic<L>, B> {
1116        let out_location = Atomic { tick: tick.clone() };
1117        KeyedSingleton::new(
1118            out_location.clone(),
1119            HydroNode::BeginAtomic {
1120                inner: Box::new(self.ir_node.into_inner()),
1121                metadata: out_location
1122                    .new_node_metadata(KeyedSingleton::<K, V, Atomic<L>, B>::collection_kind()),
1123            },
1124        )
1125    }
1126}
1127
1128impl<'a, K, V, L, B: KeyedSingletonBound> KeyedSingleton<K, V, Atomic<L>, B>
1129where
1130    L: Location<'a> + NoTick,
1131{
1132    /// Yields the elements of this keyed singleton back into a top-level, asynchronous execution context.
1133    /// See [`KeyedSingleton::atomic`] for more details.
1134    pub fn end_atomic(self) -> KeyedSingleton<K, V, L, B> {
1135        KeyedSingleton::new(
1136            self.location.tick.l.clone(),
1137            HydroNode::EndAtomic {
1138                inner: Box::new(self.ir_node.into_inner()),
1139                metadata: self
1140                    .location
1141                    .tick
1142                    .l
1143                    .new_node_metadata(KeyedSingleton::<K, V, L, B>::collection_kind()),
1144            },
1145        )
1146    }
1147}
1148
1149impl<'a, K, V, L: Location<'a>> KeyedSingleton<K, V, Tick<L>, Bounded> {
1150    /// Shifts the state in `self` to the **next tick**, so that the returned keyed singleton at
1151    /// tick `T` always has the entries of `self` at tick `T - 1`.
1152    ///
1153    /// At tick `0`, the output has no entries, since there is no previous tick.
1154    ///
1155    /// This operator enables stateful iterative processing with ticks, by sending data from one
1156    /// tick to the next. For example, you can use it to compare state across consecutive batches.
1157    ///
1158    /// # Example
1159    /// ```rust
1160    /// # #[cfg(feature = "deploy")] {
1161    /// # use hydro_lang::prelude::*;
1162    /// # use futures::StreamExt;
1163    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1164    /// let tick = process.tick();
1165    /// # // ticks are lazy by default, forces the second tick to run
1166    /// # tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
1167    /// # let batch_first_tick = process
1168    /// #   .source_iter(q!(vec![(1, 2), (2, 3)]))
1169    /// #   .batch(&tick, nondet!(/** test */))
1170    /// #   .into_keyed();
1171    /// # let batch_second_tick = process
1172    /// #   .source_iter(q!(vec![(2, 4), (3, 5)]))
1173    /// #   .batch(&tick, nondet!(/** test */))
1174    /// #   .into_keyed()
1175    /// #   .defer_tick(); // appears on the second tick
1176    /// let input_batch = // first tick: { 1: 2, 2: 3 }, second tick: { 2: 4, 3: 5 }
1177    /// # batch_first_tick.chain(batch_second_tick).first();
1178    /// input_batch.clone().filter_key_not_in(
1179    ///     input_batch.defer_tick().keys() // keys present in the previous tick
1180    /// )
1181    /// # .entries().all_ticks()
1182    /// # }, |mut stream| async move {
1183    /// // { 1: 2, 2: 3 } (first tick), { 3: 5 } (second tick)
1184    /// # for w in vec![(1, 2), (2, 3), (3, 5)] {
1185    /// #     assert_eq!(stream.next().await.unwrap(), w);
1186    /// # }
1187    /// # }));
1188    /// # }
1189    /// ```
1190    pub fn defer_tick(self) -> KeyedSingleton<K, V, Tick<L>, Bounded> {
1191        KeyedSingleton::new(
1192            self.location.clone(),
1193            HydroNode::DeferTick {
1194                input: Box::new(self.ir_node.into_inner()),
1195                metadata: self
1196                    .location
1197                    .new_node_metadata(KeyedSingleton::<K, V, Tick<L>, Bounded>::collection_kind()),
1198            },
1199        )
1200    }
1201}
1202
1203impl<'a, K, V, L, B: KeyedSingletonBound<ValueBound = Unbounded>> KeyedSingleton<K, V, L, B>
1204where
1205    L: Location<'a>,
1206{
1207    /// Returns a keyed singleton with a snapshot of each key-value entry at a non-deterministic
1208    /// point in time.
1209    ///
1210    /// # Non-Determinism
1211    /// Because this picks a snapshot of each entry, which is continuously changing, each output has a
1212    /// non-deterministic set of entries since each snapshot can be at an arbitrary point in time.
1213    pub fn snapshot(
1214        self,
1215        tick: &Tick<L>,
1216        _nondet: NonDet,
1217    ) -> KeyedSingleton<K, V, Tick<L>, Bounded> {
1218        assert_eq!(Location::id(tick.outer()), Location::id(&self.location));
1219        KeyedSingleton::new(
1220            tick.clone(),
1221            HydroNode::Batch {
1222                inner: Box::new(self.ir_node.into_inner()),
1223                metadata: tick
1224                    .new_node_metadata(KeyedSingleton::<K, V, Tick<L>, Bounded>::collection_kind()),
1225            },
1226        )
1227    }
1228}
1229
1230impl<'a, K, V, L, B: KeyedSingletonBound<ValueBound = Unbounded>> KeyedSingleton<K, V, Atomic<L>, B>
1231where
1232    L: Location<'a> + NoTick,
1233{
1234    /// Returns a keyed singleton with a snapshot of each key-value entry, consistent with the
1235    /// state of the keyed singleton being atomically processed.
1236    ///
1237    /// # Non-Determinism
1238    /// Because this picks a snapshot of each entry, which is continuously changing, each output has a
1239    /// non-deterministic set of entries since each snapshot can be at an arbitrary point in time.
1240    pub fn snapshot_atomic(self, _nondet: NonDet) -> KeyedSingleton<K, V, Tick<L>, Bounded> {
1241        KeyedSingleton::new(
1242            self.location.clone().tick,
1243            HydroNode::Batch {
1244                inner: Box::new(self.ir_node.into_inner()),
1245                metadata: self.location.tick.new_node_metadata(KeyedSingleton::<
1246                    K,
1247                    V,
1248                    Tick<L>,
1249                    Bounded,
1250                >::collection_kind(
1251                )),
1252            },
1253        )
1254    }
1255}
1256
1257impl<'a, K, V, L, B: KeyedSingletonBound<ValueBound = Bounded>> KeyedSingleton<K, V, L, B>
1258where
1259    L: Location<'a>,
1260{
1261    /// Creates a keyed singleton containing only the key-value pairs where the value satisfies a predicate `f`.
1262    ///
1263    /// The closure `f` receives a reference `&V` to each value and returns a boolean. If the predicate
1264    /// returns `true`, the key-value pair is included in the output. If it returns `false`, the pair
1265    /// is filtered out.
1266    ///
1267    /// The closure `f` receives a reference `&V` rather than an owned value `V` because filtering does
1268    /// not modify or take ownership of the values. If you need to modify the values while filtering
1269    /// use [`KeyedSingleton::filter_map`] instead.
1270    ///
1271    /// # Example
1272    /// ```rust
1273    /// # #[cfg(feature = "deploy")] {
1274    /// # use hydro_lang::prelude::*;
1275    /// # use futures::StreamExt;
1276    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1277    /// let keyed_singleton = // { 1: 2, 2: 4, 3: 1 }
1278    /// # process
1279    /// #     .source_iter(q!(vec![(1, 2), (2, 4), (3, 1)]))
1280    /// #     .into_keyed()
1281    /// #     .first();
1282    /// keyed_singleton.filter(q!(|&v| v > 1))
1283    /// #   .entries()
1284    /// # }, |mut stream| async move {
1285    /// // { 1: 2, 2: 4 }
1286    /// # let mut results = Vec::new();
1287    /// # for _ in 0..2 {
1288    /// #     results.push(stream.next().await.unwrap());
1289    /// # }
1290    /// # results.sort();
1291    /// # assert_eq!(results, vec![(1, 2), (2, 4)]);
1292    /// # }));
1293    /// # }
1294    /// ```
1295    pub fn filter<F>(self, f: impl IntoQuotedMut<'a, F, L> + Copy) -> KeyedSingleton<K, V, L, B>
1296    where
1297        F: Fn(&V) -> bool + 'a,
1298    {
1299        let f: ManualExpr<F, _> = ManualExpr::new(move |ctx: &L| f.splice_fn1_borrow_ctx(ctx));
1300        let filter_f = q!({
1301            let orig = f;
1302            move |t: &(_, _)| orig(&t.1)
1303        })
1304        .splice_fn1_borrow_ctx::<(K, V), bool>(&self.location)
1305        .into();
1306
1307        KeyedSingleton::new(
1308            self.location.clone(),
1309            HydroNode::Filter {
1310                f: filter_f,
1311                input: Box::new(self.ir_node.into_inner()),
1312                metadata: self
1313                    .location
1314                    .new_node_metadata(KeyedSingleton::<K, V, L, B>::collection_kind()),
1315            },
1316        )
1317    }
1318
1319    /// An operator that both filters and maps values. It yields only the key-value pairs where
1320    /// the supplied closure `f` returns `Some(value)`.
1321    ///
1322    /// The closure `f` receives each value `V` and returns `Option<U>`. If the closure returns
1323    /// `Some(new_value)`, the key-value pair `(key, new_value)` is included in the output.
1324    /// If it returns `None`, the key-value pair is filtered out.
1325    ///
1326    /// # Example
1327    /// ```rust
1328    /// # #[cfg(feature = "deploy")] {
1329    /// # use hydro_lang::prelude::*;
1330    /// # use futures::StreamExt;
1331    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
1332    /// let keyed_singleton = // { 1: "42", 2: "hello", 3: "100" }
1333    /// # process
1334    /// #     .source_iter(q!(vec![(1, "42"), (2, "hello"), (3, "100")]))
1335    /// #     .into_keyed()
1336    /// #     .first();
1337    /// keyed_singleton.filter_map(q!(|s| s.parse::<i32>().ok()))
1338    /// #   .entries()
1339    /// # }, |mut stream| async move {
1340    /// // { 1: 42, 3: 100 }
1341    /// # let mut results = Vec::new();
1342    /// # for _ in 0..2 {
1343    /// #     results.push(stream.next().await.unwrap());
1344    /// # }
1345    /// # results.sort();
1346    /// # assert_eq!(results, vec![(1, 42), (3, 100)]);
1347    /// # }));
1348    /// # }
1349    /// ```
1350    pub fn filter_map<F, U>(
1351        self,
1352        f: impl IntoQuotedMut<'a, F, L> + Copy,
1353    ) -> KeyedSingleton<K, U, L, B>
1354    where
1355        F: Fn(V) -> Option<U> + 'a,
1356    {
1357        let f: ManualExpr<F, _> = ManualExpr::new(move |ctx: &L| f.splice_fn1_ctx(ctx));
1358        let filter_map_f = q!({
1359            let orig = f;
1360            move |(k, v)| orig(v).map(|o| (k, o))
1361        })
1362        .splice_fn1_ctx::<(K, V), Option<(K, U)>>(&self.location)
1363        .into();
1364
1365        KeyedSingleton::new(
1366            self.location.clone(),
1367            HydroNode::FilterMap {
1368                f: filter_map_f,
1369                input: Box::new(self.ir_node.into_inner()),
1370                metadata: self
1371                    .location
1372                    .new_node_metadata(KeyedSingleton::<K, U, L, B>::collection_kind()),
1373            },
1374        )
1375    }
1376
1377    /// Returns a keyed singleton with entries consisting of _new_ key-value pairs that have
1378    /// arrived since the previous batch was released.
1379    ///
1380    /// Currently, there is no `all_ticks` dual on [`KeyedSingleton`], instead you may want to use
1381    /// [`KeyedSingleton::into_keyed_stream`] then yield with [`KeyedStream::all_ticks`].
1382    ///
1383    /// # Non-Determinism
1384    /// Because this picks a batch of asynchronously added entries, each output keyed singleton
1385    /// has a non-deterministic set of key-value pairs.
1386    pub fn batch(self, tick: &Tick<L>, nondet: NonDet) -> KeyedSingleton<K, V, Tick<L>, Bounded>
1387    where
1388        L: NoTick,
1389    {
1390        self.atomic(tick).batch_atomic(nondet)
1391    }
1392}
1393
1394impl<'a, K, V, L, B: KeyedSingletonBound<ValueBound = Bounded>> KeyedSingleton<K, V, Atomic<L>, B>
1395where
1396    L: Location<'a> + NoTick,
1397{
1398    /// Returns a keyed singleton with entries consisting of _new_ key-value pairs that are being
1399    /// atomically processed.
1400    ///
1401    /// Currently, there is no dual to asynchronously yield back outside the tick, instead you
1402    /// should use [`KeyedSingleton::into_keyed_stream`] and yield a [`KeyedStream`].
1403    ///
1404    /// # Non-Determinism
1405    /// Because this picks a batch of asynchronously added entries, each output keyed singleton
1406    /// has a non-deterministic set of key-value pairs.
1407    pub fn batch_atomic(self, nondet: NonDet) -> KeyedSingleton<K, V, Tick<L>, Bounded> {
1408        let _ = nondet;
1409        KeyedSingleton::new(
1410            self.location.clone().tick,
1411            HydroNode::Batch {
1412                inner: Box::new(self.ir_node.into_inner()),
1413                metadata: self.location.tick.new_node_metadata(KeyedSingleton::<
1414                    K,
1415                    V,
1416                    Tick<L>,
1417                    Bounded,
1418                >::collection_kind(
1419                )),
1420            },
1421        )
1422    }
1423}
1424
1425#[cfg(test)]
1426mod tests {
1427    #[cfg(feature = "deploy")]
1428    use futures::{SinkExt, StreamExt};
1429    #[cfg(feature = "deploy")]
1430    use hydro_deploy::Deployment;
1431    #[cfg(any(feature = "deploy", feature = "sim"))]
1432    use stageleft::q;
1433
1434    #[cfg(any(feature = "deploy", feature = "sim"))]
1435    use crate::compile::builder::FlowBuilder;
1436    #[cfg(any(feature = "deploy", feature = "sim"))]
1437    use crate::location::Location;
1438    #[cfg(any(feature = "deploy", feature = "sim"))]
1439    use crate::nondet::nondet;
1440
1441    #[cfg(feature = "deploy")]
1442    #[tokio::test]
1443    async fn key_count_bounded_value() {
1444        let mut deployment = Deployment::new();
1445
1446        let flow = FlowBuilder::new();
1447        let node = flow.process::<()>();
1448        let external = flow.external::<()>();
1449
1450        let (input_port, input) = node.source_external_bincode(&external);
1451        let out = input
1452            .into_keyed()
1453            .first()
1454            .key_count()
1455            .sample_eager(nondet!(/** test */))
1456            .send_bincode_external(&external);
1457
1458        let nodes = flow
1459            .with_process(&node, deployment.Localhost())
1460            .with_external(&external, deployment.Localhost())
1461            .deploy(&mut deployment);
1462
1463        deployment.deploy().await.unwrap();
1464
1465        let mut external_in = nodes.connect(input_port).await;
1466        let mut external_out = nodes.connect(out).await;
1467
1468        deployment.start().await.unwrap();
1469
1470        assert_eq!(external_out.next().await.unwrap(), 0);
1471
1472        external_in.send((1, 1)).await.unwrap();
1473        assert_eq!(external_out.next().await.unwrap(), 1);
1474
1475        external_in.send((2, 2)).await.unwrap();
1476        assert_eq!(external_out.next().await.unwrap(), 2);
1477    }
1478
1479    #[cfg(feature = "deploy")]
1480    #[tokio::test]
1481    async fn key_count_unbounded_value() {
1482        let mut deployment = Deployment::new();
1483
1484        let flow = FlowBuilder::new();
1485        let node = flow.process::<()>();
1486        let external = flow.external::<()>();
1487
1488        let (input_port, input) = node.source_external_bincode(&external);
1489        let out = input
1490            .into_keyed()
1491            .fold(q!(|| 0), q!(|acc, _| *acc += 1))
1492            .key_count()
1493            .sample_eager(nondet!(/** test */))
1494            .send_bincode_external(&external);
1495
1496        let nodes = flow
1497            .with_process(&node, deployment.Localhost())
1498            .with_external(&external, deployment.Localhost())
1499            .deploy(&mut deployment);
1500
1501        deployment.deploy().await.unwrap();
1502
1503        let mut external_in = nodes.connect(input_port).await;
1504        let mut external_out = nodes.connect(out).await;
1505
1506        deployment.start().await.unwrap();
1507
1508        assert_eq!(external_out.next().await.unwrap(), 0);
1509
1510        external_in.send((1, 1)).await.unwrap();
1511        assert_eq!(external_out.next().await.unwrap(), 1);
1512
1513        external_in.send((1, 2)).await.unwrap();
1514        assert_eq!(external_out.next().await.unwrap(), 1);
1515
1516        external_in.send((2, 2)).await.unwrap();
1517        assert_eq!(external_out.next().await.unwrap(), 2);
1518
1519        external_in.send((1, 1)).await.unwrap();
1520        assert_eq!(external_out.next().await.unwrap(), 2);
1521
1522        external_in.send((3, 1)).await.unwrap();
1523        assert_eq!(external_out.next().await.unwrap(), 3);
1524    }
1525
1526    #[cfg(feature = "deploy")]
1527    #[tokio::test]
1528    async fn into_singleton_bounded_value() {
1529        let mut deployment = Deployment::new();
1530
1531        let flow = FlowBuilder::new();
1532        let node = flow.process::<()>();
1533        let external = flow.external::<()>();
1534
1535        let (input_port, input) = node.source_external_bincode(&external);
1536        let out = input
1537            .into_keyed()
1538            .first()
1539            .into_singleton()
1540            .sample_eager(nondet!(/** test */))
1541            .send_bincode_external(&external);
1542
1543        let nodes = flow
1544            .with_process(&node, deployment.Localhost())
1545            .with_external(&external, deployment.Localhost())
1546            .deploy(&mut deployment);
1547
1548        deployment.deploy().await.unwrap();
1549
1550        let mut external_in = nodes.connect(input_port).await;
1551        let mut external_out = nodes.connect(out).await;
1552
1553        deployment.start().await.unwrap();
1554
1555        assert_eq!(
1556            external_out.next().await.unwrap(),
1557            std::collections::HashMap::new()
1558        );
1559
1560        external_in.send((1, 1)).await.unwrap();
1561        assert_eq!(
1562            external_out.next().await.unwrap(),
1563            vec![(1, 1)].into_iter().collect()
1564        );
1565
1566        external_in.send((2, 2)).await.unwrap();
1567        assert_eq!(
1568            external_out.next().await.unwrap(),
1569            vec![(1, 1), (2, 2)].into_iter().collect()
1570        );
1571    }
1572
1573    #[cfg(feature = "deploy")]
1574    #[tokio::test]
1575    async fn into_singleton_unbounded_value() {
1576        let mut deployment = Deployment::new();
1577
1578        let flow = FlowBuilder::new();
1579        let node = flow.process::<()>();
1580        let external = flow.external::<()>();
1581
1582        let (input_port, input) = node.source_external_bincode(&external);
1583        let out = input
1584            .into_keyed()
1585            .fold(q!(|| 0), q!(|acc, _| *acc += 1))
1586            .into_singleton()
1587            .sample_eager(nondet!(/** test */))
1588            .send_bincode_external(&external);
1589
1590        let nodes = flow
1591            .with_process(&node, deployment.Localhost())
1592            .with_external(&external, deployment.Localhost())
1593            .deploy(&mut deployment);
1594
1595        deployment.deploy().await.unwrap();
1596
1597        let mut external_in = nodes.connect(input_port).await;
1598        let mut external_out = nodes.connect(out).await;
1599
1600        deployment.start().await.unwrap();
1601
1602        assert_eq!(
1603            external_out.next().await.unwrap(),
1604            std::collections::HashMap::new()
1605        );
1606
1607        external_in.send((1, 1)).await.unwrap();
1608        assert_eq!(
1609            external_out.next().await.unwrap(),
1610            vec![(1, 1)].into_iter().collect()
1611        );
1612
1613        external_in.send((1, 2)).await.unwrap();
1614        assert_eq!(
1615            external_out.next().await.unwrap(),
1616            vec![(1, 2)].into_iter().collect()
1617        );
1618
1619        external_in.send((2, 2)).await.unwrap();
1620        assert_eq!(
1621            external_out.next().await.unwrap(),
1622            vec![(1, 2), (2, 1)].into_iter().collect()
1623        );
1624
1625        external_in.send((1, 1)).await.unwrap();
1626        assert_eq!(
1627            external_out.next().await.unwrap(),
1628            vec![(1, 3), (2, 1)].into_iter().collect()
1629        );
1630
1631        external_in.send((3, 1)).await.unwrap();
1632        assert_eq!(
1633            external_out.next().await.unwrap(),
1634            vec![(1, 3), (2, 1), (3, 1)].into_iter().collect()
1635        );
1636    }
1637
1638    #[cfg(feature = "sim")]
1639    #[test]
1640    fn sim_unbounded_singleton_snapshot() {
1641        let flow = FlowBuilder::new();
1642        let node = flow.process::<()>();
1643
1644        let (input_port, input) = node.sim_input();
1645        let output = input
1646            .into_keyed()
1647            .fold(q!(|| 0), q!(|acc, _| *acc += 1))
1648            .snapshot(&node.tick(), nondet!(/** test */))
1649            .entries()
1650            .all_ticks()
1651            .sim_output();
1652
1653        let count = flow.sim().exhaustive(async || {
1654            input_port.send((1, 123));
1655            input_port.send((1, 456));
1656            input_port.send((2, 123));
1657
1658            let all = output.collect_sorted::<Vec<_>>().await;
1659            assert_eq!(all.last().unwrap(), &(2, 1));
1660        });
1661
1662        assert_eq!(count, 8);
1663    }
1664
1665    #[cfg(feature = "deploy")]
1666    #[tokio::test]
1667    async fn get_many_outer_join() {
1668        let mut deployment = Deployment::new();
1669
1670        let flow = FlowBuilder::new();
1671        let node = flow.process::<()>();
1672        let external = flow.external::<()>();
1673
1674        let tick = node.tick();
1675        let keyed_data = node
1676            .source_iter(q!(vec![(1, 10), (2, 20)]))
1677            .into_keyed()
1678            .batch(&tick, nondet!(/** test */))
1679            .first();
1680        let requests = node
1681            .source_iter(q!(vec![(1, 100), (2, 200), (3, 300)]))
1682            .into_keyed()
1683            .batch(&tick, nondet!(/** test */));
1684
1685        let out = keyed_data
1686            .get_many(requests)
1687            .entries()
1688            .all_ticks()
1689            .send_bincode_external(&external);
1690
1691        let nodes = flow
1692            .with_process(&node, deployment.Localhost())
1693            .with_external(&external, deployment.Localhost())
1694            .deploy(&mut deployment);
1695
1696        deployment.deploy().await.unwrap();
1697
1698        let mut external_out = nodes.connect(out).await;
1699
1700        deployment.start().await.unwrap();
1701
1702        let mut results = vec![];
1703        for _ in 0..3 {
1704            results.push(external_out.next().await.unwrap());
1705        }
1706        results.sort();
1707
1708        assert_eq!(
1709            results,
1710            vec![(1, (Some(10), 100)), (2, (Some(20), 200)), (3, (None, 300))]
1711        );
1712    }
1713}