Skip to main content

hydro_lang/
sim_hooks.rs

1//! Handle types for **simulator hooks**: scripting the decisions of unsafe operators.
2//!
3//! Every unsafe operator (like [`Stream::batch`](crate::live_collections::Stream::batch) or
4//! [`Singleton::snapshot`](crate::live_collections::Singleton::snapshot)) takes a
5//! [`NonDet`](crate::nondet::NonDet) guard. A guard can optionally carry a **hook handle**,
6//! which lets a simulation test take manual control of the non-deterministic decision made
7//! by that operator (which elements form the next batch, which version of a piece of state
8//! a snapshot reveals, ...). See `hydro_lang::sim::hooks` for the test-side scripting API.
9//!
10//! Handles are created from the [`FlowBuilder`](crate::compile::builder::FlowBuilder) via
11//! [`FlowBuilder::sim_hook`](crate::compile::builder::FlowBuilder::sim_hook) *before* the
12//! program under test is constructed, and attached to the operator they control with the
13//! `nondet!(... hook = handle)` syntax. Handles are small and `Copy`: the same value is
14//! passed into the program during construction and used later inside the test body to
15//! script decisions.
16//!
17//! # Hook scopes
18//!
19//! Every handle type carries a **scope** parameter naming the kind of root location the
20//! hooked operator runs on, mirroring
21//! [`Location::SimHookScope`](crate::location::Location::SimHookScope):
22//!
23//! - [`OnProcess<P>`] (the default): the operator has one instance, scripted directly.
24//! - [`OnCluster<C>`]: every cluster member runs its own instance of the operator;
25//!   select the one to script with [`.on(member_id)`](BatchHook::on), which yields an
26//!   [`OnMember<C>`]-scoped handle.
27//!
28//! Operators name the scope in their `NonDet` payload type, so scope mismatches fail to
29//! compile.
30//!
31//! This module contains only the handle types themselves (plain data), so components can
32//! expose hookable signatures (e.g. `nondet_batch: NonDet<Option<BatchHook<u32>>>`, passed
33//! directly to the `batch` operator it controls) without pulling
34//! in any simulator machinery; binding a hook in a flow that is *deployed* rather than
35//! simulated is harmless metadata that non-simulator backends ignore.
36
37use std::hash::Hash;
38use std::marker::PhantomData;
39
40use serde::Serialize;
41use serde::de::DeserializeOwned;
42
43use crate::live_collections::boundedness::{Boundedness, Unbounded};
44use crate::live_collections::stream::{
45    AtLeastOnce, ExactlyOnce, NoOrder, Ordering, Retries, TotalOrder,
46};
47
48/// A simulator hook handle (or a set of them) that can be created in one call to
49/// [`FlowBuilder::sim_hook`](crate::compile::builder::FlowBuilder::sim_hook).
50///
51/// Individual handle types implement this trait, and a struct of handles (a component's
52/// "testing interface") can implement it by creating every field. Fields are typed
53/// `Option<...>` so the struct doubles as a composite hook payload: its [`Default`]
54/// ("no hooks") is what a plain `nondet!(...)` guard carries, while `flow.sim_hook()`
55/// fills in every handle:
56///
57/// ```rust,ignore
58/// #[derive(Clone, Copy, Default)]
59/// pub struct CounterHooks {
60///     pub batch: Option<BatchHook<u32>>,
61///     pub snapshot: Option<SnapshotHook<u64>>,
62/// }
63///
64/// impl SimHook for CounterHooks {
65///     fn create(next_id: &mut dyn FnMut() -> usize) -> Self {
66///         CounterHooks {
67///             batch: SimHook::create(next_id),
68///             snapshot: SimHook::create(next_id),
69///         }
70///     }
71/// }
72/// ```
73///
74/// Such structs nest (a field can itself be a struct of handles), and since handles are
75/// `Copy` a test can pass the struct around or destructure it freely.
76///
77/// Each handle's [`SimHook`] impl carries the trait bounds that the *scripted simulation
78/// codegen* for its operator kind requires (serde round-tripping for decisions, equality
79/// for value-naming decisions, `Hash + Eq + Clone` keys for keyed buffers). Since handles
80/// can only be created through this trait, binding a hook to an operator over unsupported
81/// types fails at the `flow.sim_hook()` call — an ordinary compile error in the test crate
82/// — instead of surfacing as a rustc failure inside the generated simulation dylib.
83pub trait SimHook {
84    /// Creates every handle in this value, allocating fresh IDs via `next_id`.
85    fn create(next_id: &mut dyn FnMut() -> usize) -> Self;
86}
87
88impl<H: SimHook> SimHook for Option<H> {
89    fn create(next_id: &mut dyn FnMut() -> usize) -> Self {
90        Some(H::create(next_id))
91    }
92}
93
94/// Hook scope marker: the hooked operator runs on a
95/// [`Process`](crate::location::Process) with tag `P` and has one instance, which the
96/// handle scripts directly.
97///
98/// This is the default scope of every handle type. See [the module docs](self#hook-scopes).
99pub struct OnProcess<P = ()> {
100    _phantom: PhantomData<fn(P)>,
101}
102
103/// Hook scope marker: the hooked operator runs on a
104/// [`Cluster`](crate::location::Cluster) with tag `C`, so every member runs its own
105/// independent instance of the operator.
106///
107/// Select the instance to script with [`.on(member_id)`](BatchHook::on), which yields an
108/// [`OnMember`]-scoped handle. Each member's instance makes its own decisions: a member
109/// with buffered input needs its own decision or pause.
110pub struct OnCluster<C = ()> {
111    _phantom: PhantomData<fn(C)>,
112}
113
114/// Hook scope marker: one selected member's instance of an operator running on a
115/// [`Cluster`](crate::location::Cluster) with tag `C`, produced by
116/// [`.on(member_id)`](BatchHook::on).
117///
118/// Member-scoped handles script decisions like process-scoped ones, but cannot be
119/// created or bound: operators are always bound through the unscoped [`OnCluster`]
120/// handle.
121pub struct OnMember<C = ()> {
122    _phantom: PhantomData<fn(C)>,
123}
124
125/// Hook scopes a handle can be created and bound with: [`OnProcess`] and [`OnCluster`].
126/// Operator signatures select the scope through
127/// [`Location::SimHookScope`](crate::location::Location::SimHookScope).
128#[diagnostic::on_unimplemented(
129    message = "`{Self}` is not a scope that sim hook handles can be created with",
130    note = "handles are created with the `OnProcess<P>` or `OnCluster<C>` scope of the operator they will be bound to; `OnMember` handles only arise from `.on(member_id)` at scripting time"
131)]
132#[sealed::sealed]
133pub trait BindableHookScope {}
134#[sealed::sealed]
135impl<P> BindableHookScope for OnProcess<P> {}
136#[sealed::sealed]
137impl<C> BindableHookScope for OnCluster<C> {}
138
139/// Hook scopes that name a single instance of the hooked operator and can therefore
140/// script decisions and pauses: [`OnProcess`] and [`OnMember`]. An [`OnCluster`]-scoped
141/// handle must first select a member with [`.on(member_id)`](BatchHook::on).
142#[diagnostic::on_unimplemented(
143    message = "a `{Self}`-scoped sim hook handle cannot script decisions",
144    note = "a hook bound to an operator running on a cluster has one independent instance per member; select the member to script with `.on(member_id)`"
145)]
146#[sealed::sealed]
147pub trait ScriptableHookScope {}
148#[sealed::sealed]
149impl<P> ScriptableHookScope for OnProcess<P> {}
150#[sealed::sealed]
151impl<C> ScriptableHookScope for OnMember<C> {}
152
153/// Generates the `.on(member_id)` member-selection method on [`OnCluster`]-scoped
154/// handles, shared by every handle type.
155macro_rules! on_member_method {
156    ($handle:ident < $($param:ident),* >) => {
157        /// Selects one cluster member's instance of the hooked operator, returning an
158        /// [`OnMember`]-scoped handle with the full scripting API.
159        ///
160        /// Each member's instance is scripted independently: `handle.on(0).release(2)`
161        /// scripts member 0's next batch and says nothing about the other members, each
162        /// of which needs its own decision (or pause) when it holds buffered input. A
163        /// member ID outside the cluster's sizing is reported when the scripting call
164        /// is awaited.
165        pub fn on(&self, member_id: u32) -> $handle<$($param,)* OnMember<C>> {
166            $handle {
167                id: self.id,
168                member: Some(member_id),
169                _phantom: PhantomData,
170            }
171        }
172    };
173}
174
175/// A hook handle controlling a `batch` operator over a stream of `T` elements with ordering
176/// `O` and retry guarantee `R` (mirroring the type of the stream being batched). `S` is the
177/// handle's [scope](self#hook-scopes).
178///
179/// A decision for a batch hook says which buffered elements form the next batch released
180/// into the tick. For an `AtLeastOnce` stream, decisions may also keep released elements
181/// buffered so they are delivered again in a later batch. See `hydro_lang::sim::hooks` for
182/// the decisions offered.
183pub struct BatchHook<T, O: Ordering = TotalOrder, R: Retries = ExactlyOnce, S = OnProcess> {
184    pub(crate) id: usize,
185    /// The member selected by `.on(member_id)`; `None` for process-scoped handles.
186    #[cfg_attr(
187        not(feature = "sim"),
188        expect(dead_code, reason = "only read by the `sim`-gated scripting API")
189    )]
190    pub(crate) member: Option<u32>,
191    pub(crate) _phantom: PhantomData<fn(T, O, R, S)>,
192}
193
194impl<T, O: Ordering, R: Retries, C> BatchHook<T, O, R, OnCluster<C>> {
195    on_member_method!(BatchHook<T, O, R>);
196}
197
198impl<T, O: Ordering, R: Retries, S> Clone for BatchHook<T, O, R, S> {
199    fn clone(&self) -> Self {
200        *self
201    }
202}
203impl<T, O: Ordering, R: Retries, S> Copy for BatchHook<T, O, R, S> {}
204
205impl<T, O: Ordering, R: Retries, S> std::fmt::Debug for BatchHook<T, O, R, S> {
206    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
207        f.debug_struct("BatchHook").field("id", &self.id).finish()
208    }
209}
210
211impl<T, O: Ordering, R: Retries, S: BindableHookScope> SimHook for BatchHook<T, O, R, S>
212where
213    T: Serialize + DeserializeOwned + PartialEq,
214{
215    fn create(next_id: &mut dyn FnMut() -> usize) -> Self {
216        BatchHook {
217            id: next_id(),
218            member: None,
219            _phantom: PhantomData,
220        }
221    }
222}
223
224/// A hook handle controlling a `snapshot` operator over a singleton of `T`. `S` is the
225/// handle's [scope](self#hook-scopes).
226///
227/// A decision for a snapshot hook picks which buffered version of the state the next tick
228/// execution observes. See `hydro_lang::sim::hooks` for the decisions offered.
229pub struct SnapshotHook<T, S = OnProcess> {
230    pub(crate) id: usize,
231    /// The member selected by `.on(member_id)`; `None` for process-scoped handles.
232    #[cfg_attr(
233        not(feature = "sim"),
234        expect(dead_code, reason = "only read by the `sim`-gated scripting API")
235    )]
236    pub(crate) member: Option<u32>,
237    pub(crate) _phantom: PhantomData<fn(T, S)>,
238}
239
240impl<T, C> SnapshotHook<T, OnCluster<C>> {
241    on_member_method!(SnapshotHook<T>);
242}
243
244impl<T, S> Clone for SnapshotHook<T, S> {
245    fn clone(&self) -> Self {
246        *self
247    }
248}
249impl<T, S> Copy for SnapshotHook<T, S> {}
250
251impl<T, S> std::fmt::Debug for SnapshotHook<T, S> {
252    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
253        f.debug_struct("SnapshotHook")
254            .field("id", &self.id)
255            .finish()
256    }
257}
258
259impl<T, S: BindableHookScope> SimHook for SnapshotHook<T, S>
260where
261    T: Clone + PartialEq + Serialize + DeserializeOwned,
262{
263    fn create(next_id: &mut dyn FnMut() -> usize) -> Self {
264        SnapshotHook {
265            id: next_id(),
266            member: None,
267            _phantom: PhantomData,
268        }
269    }
270}
271
272/// A hook handle controlling an `assume_ordering` operator over `T` elements, with retry
273/// guarantee `R` (mirroring the type of the stream whose ordering is assumed). `S` is the
274/// handle's [scope](self#hook-scopes).
275///
276/// For an `ExactlyOnce` stream, a top-level decision selects the next buffered element to
277/// release, and an `assume_ordering` inside a tick instead takes one exhaustive ordering
278/// of that tick's complete input. For an `AtLeastOnce` stream, ordering additionally
279/// decides which *slots* each element's retries occupy, so top-level decisions split into
280/// `emit` (release a slot, keep the element for re-emission) and `emit_final` (release
281/// the element's last slot), and the in-tick ordering may emit each element into several
282/// slots. See `hydro_lang::sim::hooks` for the decisions offered.
283pub struct OrderingHook<T, B: Boundedness = Unbounded, R: Retries = ExactlyOnce, S = OnProcess> {
284    pub(crate) id: usize,
285    /// The member selected by `.on(member_id)`; `None` for process-scoped handles.
286    #[cfg_attr(
287        not(feature = "sim"),
288        expect(dead_code, reason = "only read by the `sim`-gated scripting API")
289    )]
290    pub(crate) member: Option<u32>,
291    pub(crate) _phantom: PhantomData<fn(T, B, R, S)>,
292}
293
294impl<T, B: Boundedness, R: Retries, C> OrderingHook<T, B, R, OnCluster<C>> {
295    on_member_method!(OrderingHook<T, B, R>);
296}
297
298impl<T, B: Boundedness, R: Retries, S> Clone for OrderingHook<T, B, R, S> {
299    fn clone(&self) -> Self {
300        *self
301    }
302}
303impl<T, B: Boundedness, R: Retries, S> Copy for OrderingHook<T, B, R, S> {}
304
305impl<T, B: Boundedness, R: Retries, S> std::fmt::Debug for OrderingHook<T, B, R, S> {
306    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
307        f.debug_struct("OrderingHook")
308            .field("id", &self.id)
309            .finish()
310    }
311}
312
313impl<T, B: Boundedness, S: BindableHookScope> SimHook for OrderingHook<T, B, ExactlyOnce, S>
314where
315    T: Serialize + DeserializeOwned + PartialEq,
316{
317    fn create(next_id: &mut dyn FnMut() -> usize) -> Self {
318        OrderingHook {
319            id: next_id(),
320            member: None,
321            _phantom: PhantomData,
322        }
323    }
324}
325
326impl<T, B: Boundedness, S: BindableHookScope> SimHook for OrderingHook<T, B, AtLeastOnce, S>
327where
328    T: Clone + Serialize + DeserializeOwned + PartialEq,
329{
330    fn create(next_id: &mut dyn FnMut() -> usize) -> Self {
331        OrderingHook {
332            id: next_id(),
333            member: None,
334            _phantom: PhantomData,
335        }
336    }
337}
338
339/// A hook handle controlling an `assume_retries` operator over a stream of `T` elements
340/// with ordering `O` (mirroring the type of the stream whose retries are assumed). `S`
341/// is the handle's [scope](self#hook-scopes).
342///
343/// A decision for a retries hook says how many times a buffered element is released —
344/// the point where the simulator injects the duplicates the `AtLeastOnce` type says
345/// downstream must tolerate. Because every element admits arbitrarily many retries, the
346/// decision space is infinite and exhaustive simulation of an unhooked `assume_retries`
347/// requires `SimFlow::retries_depth`. See
348/// `hydro_lang::sim::hooks` for the decisions offered.
349pub struct RetriesHook<T, O: Ordering = NoOrder, B: Boundedness = Unbounded, S = OnProcess> {
350    pub(crate) id: usize,
351    /// The selected cluster member (set by `.on(member_id)` on an [`OnCluster`]-scoped
352    /// handle); `None` for process-scoped handles. Only read by the simulator's
353    /// scripting machinery (`hydro_lang::sim::hooks`), which is feature-gated.
354    #[cfg_attr(
355        not(feature = "sim"),
356        expect(
357            dead_code,
358            reason = "read only by the `sim`-gated scripting machinery; handles are plain data usable without it"
359        )
360    )]
361    pub(crate) member: Option<u32>,
362    pub(crate) _phantom: PhantomData<fn(T, O, B, S)>,
363}
364
365impl<T, O: Ordering, B: Boundedness, C> RetriesHook<T, O, B, OnCluster<C>> {
366    on_member_method!(RetriesHook<T, O, B>);
367}
368
369impl<T, O: Ordering, B: Boundedness, S> Clone for RetriesHook<T, O, B, S> {
370    fn clone(&self) -> Self {
371        *self
372    }
373}
374impl<T, O: Ordering, B: Boundedness, S> Copy for RetriesHook<T, O, B, S> {}
375
376impl<T, O: Ordering, B: Boundedness, S> std::fmt::Debug for RetriesHook<T, O, B, S> {
377    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
378        f.debug_struct("RetriesHook").field("id", &self.id).finish()
379    }
380}
381
382impl<T, O: Ordering, B: Boundedness, S: BindableHookScope> SimHook for RetriesHook<T, O, B, S>
383where
384    T: Clone + Serialize + DeserializeOwned + PartialEq,
385{
386    fn create(next_id: &mut dyn FnMut() -> usize) -> Self {
387        RetriesHook {
388            id: next_id(),
389            member: None,
390            _phantom: PhantomData,
391        }
392    }
393}
394
395/// A hook handle controlling a `batch` operator over a keyed stream with keys `K`, values
396/// `V`, per-key value ordering `O`, and retry guarantee `R` (mirroring the type of the
397/// keyed stream being batched). `S` is the handle's [scope](self#hook-scopes).
398///
399/// A `batch` over a keyed singleton with bounded per-key values (where each entry is final
400/// once it appears, so a batch is the set of *new* entries) is controlled by a
401/// `KeyedBatchHook<K, V>` with the default `TotalOrder` / `ExactlyOnce` parameters.
402///
403/// A decision for a keyed batch hook says which buffered `(key, value)` entries form the
404/// next batch released into the tick. See `hydro_lang::sim::hooks` for the decisions
405/// offered.
406pub struct KeyedBatchHook<K, V, O: Ordering = TotalOrder, R: Retries = ExactlyOnce, S = OnProcess> {
407    pub(crate) id: usize,
408    /// The member selected by `.on(member_id)`; `None` for process-scoped handles.
409    #[cfg_attr(
410        not(feature = "sim"),
411        expect(dead_code, reason = "only read by the `sim`-gated scripting API")
412    )]
413    pub(crate) member: Option<u32>,
414    pub(crate) _phantom: PhantomData<fn(K, V, O, R, S)>,
415}
416
417impl<K, V, O: Ordering, R: Retries, C> KeyedBatchHook<K, V, O, R, OnCluster<C>> {
418    on_member_method!(KeyedBatchHook<K, V, O, R>);
419}
420
421impl<K, V, O: Ordering, R: Retries, S> Clone for KeyedBatchHook<K, V, O, R, S> {
422    fn clone(&self) -> Self {
423        *self
424    }
425}
426impl<K, V, O: Ordering, R: Retries, S> Copy for KeyedBatchHook<K, V, O, R, S> {}
427
428impl<K, V, O: Ordering, R: Retries, S> std::fmt::Debug for KeyedBatchHook<K, V, O, R, S> {
429    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
430        f.debug_struct("KeyedBatchHook")
431            .field("id", &self.id)
432            .finish()
433    }
434}
435
436impl<K, V, O: Ordering, R: Retries, S: BindableHookScope> SimHook for KeyedBatchHook<K, V, O, R, S>
437where
438    K: Hash + Eq + Clone + Serialize + DeserializeOwned,
439    V: Serialize + DeserializeOwned + PartialEq,
440{
441    fn create(next_id: &mut dyn FnMut() -> usize) -> Self {
442        KeyedBatchHook {
443            id: next_id(),
444            member: None,
445            _phantom: PhantomData,
446        }
447    }
448}
449
450/// A hook handle controlling a `snapshot` operator over a keyed singleton with keys `K` and
451/// values `V`. `S` is the handle's [scope](self#hook-scopes).
452///
453/// A decision for a keyed snapshot hook picks which buffered version of each key's state
454/// the next tick execution observes. See `hydro_lang::sim::hooks` for the decisions
455/// offered.
456pub struct KeyedSnapshotHook<K, V, S = OnProcess> {
457    pub(crate) id: usize,
458    /// The member selected by `.on(member_id)`; `None` for process-scoped handles.
459    #[cfg_attr(
460        not(feature = "sim"),
461        expect(dead_code, reason = "only read by the `sim`-gated scripting API")
462    )]
463    pub(crate) member: Option<u32>,
464    pub(crate) _phantom: PhantomData<fn(K, V, S)>,
465}
466
467impl<K, V, C> KeyedSnapshotHook<K, V, OnCluster<C>> {
468    on_member_method!(KeyedSnapshotHook<K, V>);
469}
470
471impl<K, V, S> Clone for KeyedSnapshotHook<K, V, S> {
472    fn clone(&self) -> Self {
473        *self
474    }
475}
476impl<K, V, S> Copy for KeyedSnapshotHook<K, V, S> {}
477
478impl<K, V, S> std::fmt::Debug for KeyedSnapshotHook<K, V, S> {
479    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
480        f.debug_struct("KeyedSnapshotHook")
481            .field("id", &self.id)
482            .finish()
483    }
484}
485
486impl<K, V, S: BindableHookScope> SimHook for KeyedSnapshotHook<K, V, S>
487where
488    K: Hash + Eq + Clone + Serialize + DeserializeOwned,
489    V: Clone + PartialEq + Serialize + DeserializeOwned,
490{
491    fn create(next_id: &mut dyn FnMut() -> usize) -> Self {
492        KeyedSnapshotHook {
493            id: next_id(),
494            member: None,
495            _phantom: PhantomData,
496        }
497    }
498}
499
500/// A hook handle controlling an `assume_ordering` operator over a keyed stream with keys
501/// `K` and values `V`. `S` is the handle's [scope](self#hook-scopes).
502///
503/// A top-level decision selects the next buffered `(key, value)` entry to release. An
504/// `assume_ordering` inside a tick instead takes one exhaustive per-key ordering of that
505/// tick's complete input. See `hydro_lang::sim::hooks` for the decisions offered.
506pub struct KeyedOrderingHook<K, V, B: Boundedness = Unbounded, S = OnProcess> {
507    pub(crate) id: usize,
508    /// The member selected by `.on(member_id)`; `None` for process-scoped handles.
509    #[cfg_attr(
510        not(feature = "sim"),
511        expect(dead_code, reason = "only read by the `sim`-gated scripting API")
512    )]
513    pub(crate) member: Option<u32>,
514    pub(crate) _phantom: PhantomData<fn(K, V, B, S)>,
515}
516
517impl<K, V, B: Boundedness, C> KeyedOrderingHook<K, V, B, OnCluster<C>> {
518    on_member_method!(KeyedOrderingHook<K, V, B>);
519}
520
521impl<K, V, B: Boundedness, S> Clone for KeyedOrderingHook<K, V, B, S> {
522    fn clone(&self) -> Self {
523        *self
524    }
525}
526impl<K, V, B: Boundedness, S> Copy for KeyedOrderingHook<K, V, B, S> {}
527
528impl<K, V, B: Boundedness, S> std::fmt::Debug for KeyedOrderingHook<K, V, B, S> {
529    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
530        f.debug_struct("KeyedOrderingHook")
531            .field("id", &self.id)
532            .finish()
533    }
534}
535
536impl<K, V, B: Boundedness, S: BindableHookScope> SimHook for KeyedOrderingHook<K, V, B, S>
537where
538    K: Hash + Eq + Clone + Serialize + DeserializeOwned,
539    V: Serialize + DeserializeOwned + PartialEq,
540{
541    fn create(next_id: &mut dyn FnMut() -> usize) -> Self {
542        KeyedOrderingHook {
543            id: next_id(),
544            member: None,
545            _phantom: PhantomData,
546        }
547    }
548}
549
550/// A hook handle controlling an `entries_partially_ordered` operator over a keyed stream
551/// with keys `K` and values `V`. `S` is the handle's [scope](self#hook-scopes).
552///
553/// The operator preserves the order of values within each key while interleaving across
554/// keys non-deterministically. A top-level decision releases the front entry of one key's
555/// buffer; inside a tick, a single decision supplies the complete interleaving. See
556/// `hydro_lang::sim::hooks` for the decisions offered.
557pub struct PartialOrderingHook<K, V, B: Boundedness = Unbounded, S = OnProcess> {
558    pub(crate) id: usize,
559    /// The member selected by `.on(member_id)`; `None` for process-scoped handles.
560    #[cfg_attr(
561        not(feature = "sim"),
562        expect(dead_code, reason = "only read by the `sim`-gated scripting API")
563    )]
564    pub(crate) member: Option<u32>,
565    pub(crate) _phantom: PhantomData<fn(K, V, B, S)>,
566}
567
568impl<K, V, B: Boundedness, C> PartialOrderingHook<K, V, B, OnCluster<C>> {
569    on_member_method!(PartialOrderingHook<K, V, B>);
570}
571
572impl<K, V, B: Boundedness, S> Clone for PartialOrderingHook<K, V, B, S> {
573    fn clone(&self) -> Self {
574        *self
575    }
576}
577impl<K, V, B: Boundedness, S> Copy for PartialOrderingHook<K, V, B, S> {}
578
579impl<K, V, B: Boundedness, S> std::fmt::Debug for PartialOrderingHook<K, V, B, S> {
580    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
581        f.debug_struct("PartialOrderingHook")
582            .field("id", &self.id)
583            .finish()
584    }
585}
586
587impl<K, V, B: Boundedness, S: BindableHookScope> SimHook for PartialOrderingHook<K, V, B, S>
588where
589    K: Hash + Eq + Clone + Serialize + DeserializeOwned,
590    V: Serialize + DeserializeOwned + PartialEq,
591{
592    fn create(next_id: &mut dyn FnMut() -> usize) -> Self {
593        PartialOrderingHook {
594            id: next_id(),
595            member: None,
596            _phantom: PhantomData,
597        }
598    }
599}
600
601/// A hook handle controlling a `merge_ordered` operator over streams of `T` elements. `S`
602/// is the handle's [scope](self#hook-scopes).
603///
604/// The operator preserves the order of each input while interleaving the two inputs
605/// non-deterministically. A top-level decision releases the front element of one input's
606/// buffer; inside a tick, a single decision supplies the complete interleaving. See
607/// `hydro_lang::sim::hooks` for the decisions offered.
608pub struct MergeOrderedHook<T, B: Boundedness = Unbounded, S = OnProcess> {
609    pub(crate) id: usize,
610    /// The member selected by `.on(member_id)`; `None` for process-scoped handles.
611    #[cfg_attr(
612        not(feature = "sim"),
613        expect(dead_code, reason = "only read by the `sim`-gated scripting API")
614    )]
615    pub(crate) member: Option<u32>,
616    pub(crate) _phantom: PhantomData<fn(T, B, S)>,
617}
618
619impl<T, B: Boundedness, C> MergeOrderedHook<T, B, OnCluster<C>> {
620    on_member_method!(MergeOrderedHook<T, B>);
621}
622
623impl<T, B: Boundedness, S> Clone for MergeOrderedHook<T, B, S> {
624    fn clone(&self) -> Self {
625        *self
626    }
627}
628impl<T, B: Boundedness, S> Copy for MergeOrderedHook<T, B, S> {}
629
630impl<T, B: Boundedness, S> std::fmt::Debug for MergeOrderedHook<T, B, S> {
631    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
632        f.debug_struct("MergeOrderedHook")
633            .field("id", &self.id)
634            .finish()
635    }
636}
637
638impl<T, B: Boundedness, S: BindableHookScope> SimHook for MergeOrderedHook<T, B, S>
639where
640    T: Serialize + DeserializeOwned + PartialEq,
641{
642    fn create(next_id: &mut dyn FnMut() -> usize) -> Self {
643        MergeOrderedHook {
644            id: next_id(),
645            member: None,
646            _phantom: PhantomData,
647        }
648    }
649}
650
651/// A hook handle controlling a `merge_ordered` operator over keyed streams with keys `K`
652/// and values `V`. `S` is the handle's [scope](self#hook-scopes).
653///
654/// The operator preserves each input's order within every key while interleaving the two
655/// inputs non-deterministically (cross-key order is unconstrained). A top-level decision
656/// releases the front entry of one key's buffer in one input; inside a tick, a single
657/// decision supplies the complete interleaving. See `hydro_lang::sim::hooks` for the
658/// decisions offered.
659pub struct KeyedMergeOrderedHook<K, V, B: Boundedness = Unbounded, S = OnProcess> {
660    pub(crate) id: usize,
661    /// The member selected by `.on(member_id)`; `None` for process-scoped handles.
662    #[cfg_attr(
663        not(feature = "sim"),
664        expect(dead_code, reason = "only read by the `sim`-gated scripting API")
665    )]
666    pub(crate) member: Option<u32>,
667    pub(crate) _phantom: PhantomData<fn(K, V, B, S)>,
668}
669
670impl<K, V, B: Boundedness, C> KeyedMergeOrderedHook<K, V, B, OnCluster<C>> {
671    on_member_method!(KeyedMergeOrderedHook<K, V, B>);
672}
673
674impl<K, V, B: Boundedness, S> Clone for KeyedMergeOrderedHook<K, V, B, S> {
675    fn clone(&self) -> Self {
676        *self
677    }
678}
679impl<K, V, B: Boundedness, S> Copy for KeyedMergeOrderedHook<K, V, B, S> {}
680
681impl<K, V, B: Boundedness, S> std::fmt::Debug for KeyedMergeOrderedHook<K, V, B, S> {
682    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
683        f.debug_struct("KeyedMergeOrderedHook")
684            .field("id", &self.id)
685            .finish()
686    }
687}
688
689impl<K, V, B: Boundedness, S: BindableHookScope> SimHook for KeyedMergeOrderedHook<K, V, B, S>
690where
691    K: Hash + Eq + Clone + Serialize + DeserializeOwned,
692    V: Serialize + DeserializeOwned + PartialEq,
693{
694    fn create(next_id: &mut dyn FnMut() -> usize) -> Self {
695        KeyedMergeOrderedHook {
696            id: next_id(),
697            member: None,
698            _phantom: PhantomData,
699        }
700    }
701}