hydro_lang/sim/hooks.rs
1//! Test-side API for **simulator hooks**: scripting the decisions of unsafe operators.
2//!
3//! A hook handle (see [`crate::sim_hooks`]) is created from the
4//! [`FlowBuilder`](crate::compile::builder::FlowBuilder) via
5//! [`FlowBuilder::sim_hook`](crate::compile::builder::FlowBuilder::sim_hook) and attached
6//! to one specific unsafe operator with `nondet!(/** reason */ hook = handle)`. Inside a
7//! simulation test body (under [`SimFlow::deterministic`](crate::sim::flow::SimFlow::deterministic),
8//! [`fuzz`](crate::sim::flow::SimFlow::fuzz), or
9//! [`exhaustive`](crate::sim::flow::SimFlow::exhaustive)), the handle scripts the
10//! operator's decisions.
11//!
12//! # The script is a schedule
13//!
14//! Decision calls are `async`, and the sequence of calls in the test body is a
15//! **schedule**, read in program order:
16//!
17//! - Consecutive decisions that target *different hooks of the same tick* form a
18//! **group**: one execution of that tick will consume all of them together.
19//! - A decision that targets a different tick — or the *next execution* of the same tick
20//! (scripting a hook that already has a decision in the current group) — starts a new
21//! group. The `.await` on the first decision of a new group suspends the test until the
22//! previous group's tick execution has actually happened, so the test body advances in
23//! lockstep with the execution it describes. Decisions whose turn has already come
24//! return immediately without suspending.
25//! - Output awaits are group barriers: an output await completes only after every
26//! decision scripted so far has been consumed.
27//!
28//! A decision may be scripted before its data exists (`release(3)` immediately after
29//! `send_many([1, 2, 3])`): the tick simply fires at the first moment the decision can be
30//! honored in full. A decision that can *never* be honored is reported when the
31//! simulation runs out of other work, attributed to the test line that is suspended
32//! waiting on it.
33//!
34//! # Holding data on purpose
35//!
36//! A hook with buffered data and no decision is an error the simulator reports at every
37//! scheduling boundary. When buffering *is* the scenario, declare it with the `pause`
38//! family ([`BatchHook::pause`], [`BatchHook::pause_while`],
39//! [`BatchHook::pause_until_count`], [`BatchHook::auto_pause`], and the snapshot
40//! equivalents).
41//!
42//! # Hooks on clusters
43//!
44//! A handle bound to an operator running on a cluster controls one independent hook
45//! instance per member; its [`OnCluster`] scope requires selecting the instance to
46//! script with `.on(member_id)` (e.g. `hook.on(0).release(2).await`). Decisions for
47//! different members never share a group — each member's execution takes its own place
48//! in the schedule — and every member's instance is independently subject to the
49//! missing-decision error.
50
51use std::future::Future;
52use std::marker::PhantomData;
53use std::pin::Pin;
54use std::task::{Context, Poll};
55
56use serde::Serialize;
57use serde::de::DeserializeOwned;
58
59use crate::live_collections::boundedness::{Bounded, Unbounded};
60use crate::live_collections::stream::{
61 AtLeastOnce, ExactlyOnce, NoOrder, Ordering, Retries, TotalOrder,
62};
63use crate::sim::compiled::{
64 ScheduleDecision, script_ctx, script_stuck_error, script_unconsumed_description,
65};
66use crate::sim::runtime::{
67 AtLeastOnceOrderingDecision, BatchDecision, InlineOrderingDecision, InlineRetriesDecision,
68 KeyedBatchDecision, KeyedSnapshotDecision, MergeDecision, NoOrderRetriesDecision,
69 OrderedRetriesDecision, ScriptDecision, SnapshotDecision, TopLevelOrderingDecision,
70 UnorderedBatchDecision, UnorderedKeyedBatchDecision,
71};
72pub use crate::sim::runtime::{
73 BatchStatus, KeyedSnapshotStatus, MergeStatus, OrderingStatus, SnapshotStatus,
74};
75pub use crate::sim_hooks::{
76 BatchHook, BindableHookScope, KeyedBatchHook, KeyedMergeOrderedHook, KeyedOrderingHook,
77 KeyedSnapshotHook, MergeOrderedHook, OnCluster, OnMember, OnProcess, OrderingHook,
78 PartialOrderingHook, RetriesHook, ScriptableHookScope, SimHook, SnapshotHook,
79};
80
81/// A scripted decision that has been issued but not yet installed into the schedule.
82///
83/// Awaiting it suspends the test until every previously scripted tick execution the
84/// decision must come after has actually happened (see the module docs); it resolves once
85/// the decision is installed for its tick's next execution. Panics (at the `.await`'s
86/// location) if the decision can never take its place in the schedule.
87#[must_use = "a scripted decision does nothing until awaited"]
88pub struct DecisionFuture {
89 hook_id: usize,
90 /// The cluster member whose hook instance the decision targets (from `.on(..)` on
91 /// the handle); `None` for hooks on processes.
92 member: Option<u32>,
93 /// The decision, MessagePack-serialized (the handle and the hook it is bound to
94 /// statically know the same decision type). `None` once installed.
95 blob: Option<Vec<u8>>,
96}
97
98impl DecisionFuture {
99 fn new(hook_id: usize, member: Option<u32>, decision: &impl ScriptDecision) -> Self {
100 DecisionFuture {
101 hook_id,
102 member,
103 blob: Some(rmp_serde::to_vec_named(decision).unwrap()),
104 }
105 }
106}
107
108/// Panics (at the scripting call site) when a per-key decision names the same key more
109/// than once, establishing the no-duplicate-keys invariant of the keyed decisions before
110/// they are installed.
111#[track_caller]
112fn assert_distinct_keys<'a, K: std::hash::Hash + Eq + 'a>(
113 keys: impl Iterator<Item = &'a K>,
114 method: &str,
115) {
116 let mut seen: dfir_rs::rustc_hash::FxHashSet<&K> = Default::default();
117 for (position, key) in keys.enumerate() {
118 assert!(
119 seen.insert(key),
120 "{}: the same key appears more than once in a single decision (duplicate at entry {}); a key takes exactly one decision per tick",
121 method,
122 position
123 );
124 }
125}
126
127/// Panics (at the scripting call site) when a retries decision requests zero copies:
128/// releasing an element zero times would be a *loss*, which `AtLeastOnce` does not
129/// permit.
130#[track_caller]
131fn assert_copies_at_least_one(copies: usize) {
132 assert!(
133 copies >= 1,
134 "the number of copies must be at least 1 (at-least-once permits duplicates, not losses)"
135 );
136}
137
138impl Future for DecisionFuture {
139 type Output = ();
140
141 #[track_caller]
142 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
143 let this = self.get_mut();
144 let Some(blob) = this.blob.take() else {
145 return Poll::Ready(());
146 };
147
148 let ctx = script_ctx();
149 match ctx.try_schedule_decision(this.hook_id, this.member, blob) {
150 Ok(ScheduleDecision::Installed) => Poll::Ready(()),
151 Ok(ScheduleDecision::Wait(blob)) => {
152 this.blob = Some(blob);
153 // While the script waits, the rest of the simulation does not: the
154 // scheduler keeps freely choosing which *other* ticks run. The test body
155 // is re-polled after every scheduler step; the waker is only needed for
156 // the parked (quiescent) case.
157 ctx.push_park_waker(cx.waker());
158 Poll::Pending
159 }
160 Err(message) => panic!("{}", message),
161 }
162 }
163}
164
165/// A `pause_until` wait: resolves once the hook's pending-input status satisfies the
166/// predicate, un-pausing the hook. The status is read from the hook **on demand** at every
167/// poll (the test body is polled between every pair of scheduler steps), so the wait
168/// resolves at the first scheduling point where the predicate holds. Panics (at the
169/// `.await`'s location) if the simulation can no longer satisfy it.
170#[must_use = "the pause is only released once this future is awaited"]
171pub struct PauseUntilFuture<S, F> {
172 hook_id: usize,
173 /// The cluster member whose hook instance is paused; `None` for hooks on processes.
174 member: Option<u32>,
175 /// What the wait is called in error messages (e.g. `pause_until_count(3)`).
176 label: String,
177 predicate: F,
178 _status: PhantomData<fn(S)>,
179}
180
181impl<S: DeserializeOwned, F: Fn(&S) -> bool + Unpin> Future for PauseUntilFuture<S, F> {
182 type Output = ();
183
184 #[track_caller]
185 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
186 let this = self.get_mut();
187 let ctx = script_ctx();
188
189 // A `pause_until` wait is a script barrier, like an output await: it must not
190 // resolve (dropping the hold) while an earlier decision group is unconsumed,
191 // or the next decision would spuriously overlap the outstanding group and the
192 // boundary scan would see the exposed hook mid-group. And if that group is
193 // stuck, it is the root cause — report it instead of blaming the predicate.
194 if let Some(stuck) = script_unconsumed_description() {
195 assert!(!ctx.is_quiescent(), "{}", script_stuck_error(&stuck));
196 ctx.push_park_waker(cx.waker());
197 return Poll::Pending;
198 }
199
200 let hook = ctx.control(this.hook_id, this.member);
201
202 let status: S = rmp_serde::from_slice(&hook.borrow().status_blob())
203 .expect("internal error: hook status blob did not match the handle's status type");
204
205 if (this.predicate)(&status) {
206 // The wait is satisfied; the hook is unpaused (the ordinary missing-decision
207 // error applies from here on).
208 hook.borrow_mut().release_hold();
209 Poll::Ready(())
210 } else if ctx.is_quiescent() {
211 let hook = hook.borrow();
212 let loc = hook.location_meta().location;
213 let member = this
214 .member
215 .map(|m| format!(" (cluster member {m})"))
216 .unwrap_or_default();
217 panic!(
218 "{} can never be satisfied: the hook at {}{} has {} and the simulation has no more work it can do",
219 this.label,
220 loc,
221 member,
222 hook.describe_pending()
223 .unwrap_or_else(|| "no pending input".to_owned()),
224 );
225 } else {
226 ctx.push_park_waker(cx.waker());
227 Poll::Pending
228 }
229 }
230}
231
232/// RAII guard for [`BatchHook::pause_while`] / [`SnapshotHook::pause_while`]: ends the
233/// hold when dropped (even on panic), leaving a standing `auto_pause` hold in place.
234struct PauseGuard {
235 hook_id: usize,
236 member: Option<u32>,
237}
238
239impl Drop for PauseGuard {
240 fn drop(&mut self) {
241 let ctx = script_ctx();
242 let hook = ctx.control(self.hook_id, self.member);
243 hook.borrow_mut().release_hold();
244 }
245}
246
247macro_rules! pause_family {
248 ($status:ty) => {
249 /// Declares that buffering at this operator is intended: while paused, the hook is
250 /// exempt from the missing-decision error, never causes its tick to run, and — if
251 /// its tick runs anyway because *other* hooks feed it — contributes its "nothing
252 /// new" behavior each time. Scripting any decision implicitly resumes the hook.
253 ///
254 /// A pause takes its place in the script like everything else: requested while a
255 /// decision is still pending, the hold begins once that decision has been
256 /// consumed.
257 pub fn pause(&self) {
258 let ctx = script_ctx();
259 ctx.control(self.id, self.member)
260 .borrow_mut()
261 .set_hold(true);
262 }
263
264 /// Ends a [`Self::pause`] (and clears [`Self::auto_pause`] mode).
265 pub fn resume(&self) {
266 let ctx = script_ctx();
267 let hook = ctx.control(self.id, self.member);
268 let mut hook = hook.borrow_mut();
269 hook.set_auto_pause(false);
270 hook.set_hold(false);
271 }
272
273 /// Sets a standing mode where this hook only ever acts when scripted: it holds
274 /// immediately, and every scripted decision leaves a fresh hold in place behind
275 /// it.
276 ///
277 /// This deliberately opts out of the forgotten-hook protection: if the test
278 /// forgets a step, the operator silently holds its data instead of failing. The
279 /// one `auto_pause()` line at the top of a test is the reviewer-visible marker
280 /// that this hook's timing is entirely script-driven, missed steps and all.
281 pub fn auto_pause(&self) {
282 let ctx = script_ctx();
283 let hook = ctx.control(self.id, self.member);
284 let mut hook = hook.borrow_mut();
285 hook.set_auto_pause(true);
286 hook.set_hold(true);
287 }
288
289 /// Pauses the hook exactly for the duration of `body` (resuming even on panic), so
290 /// a bracketed buffering phase cannot leak a paused hook.
291 pub async fn pause_while<Fut: Future>(&self, body: Fut) -> Fut::Output {
292 self.pause();
293 let _guard = PauseGuard {
294 hook_id: self.id,
295 member: self.member,
296 };
297 body.await
298 }
299
300 /// Pauses the hook and returns a future that resolves once the hook's
301 /// pending-input status satisfies `predicate` — a synchronization point for
302 /// scripts where the right decision is not knowable upfront. The status is read
303 /// on demand at every scheduling point. After the future resolves, the hook is
304 /// unpaused; the ordinary missing-decision error applies from there on.
305 pub fn pause_until(
306 &self,
307 predicate: impl Fn(&$status) -> bool + Unpin,
308 ) -> PauseUntilFuture<$status, impl Fn(&$status) -> bool + Unpin> {
309 self.pause_until_labeled("pause_until(..)".to_owned(), predicate)
310 }
311
312 fn pause_until_labeled<F: Fn(&$status) -> bool + Unpin>(
313 &self,
314 label: String,
315 predicate: F,
316 ) -> PauseUntilFuture<$status, F> {
317 let ctx = script_ctx();
318 ctx.control(self.id, self.member)
319 .borrow_mut()
320 .set_hold(true);
321 PauseUntilFuture {
322 hook_id: self.id,
323 member: self.member,
324 label,
325 predicate,
326 _status: PhantomData,
327 }
328 }
329 };
330}
331
332impl<T, O: Ordering, R: Retries, Scope: ScriptableHookScope> BatchHook<T, O, R, Scope> {
333 pause_family!(BatchStatus);
334
335 /// Pauses the hook and returns a future that resolves once at least `n` elements are
336 /// buffered; see [`Self::pause_until`].
337 pub fn pause_until_count(
338 &self,
339 n: usize,
340 ) -> PauseUntilFuture<BatchStatus, impl Fn(&BatchStatus) -> bool + Unpin> {
341 self.pause_until_labeled(format!("pause_until_count({})", n), move |status| {
342 status.buffered >= n
343 })
344 }
345}
346
347impl<T, R: Retries, Scope: ScriptableHookScope> BatchHook<T, TotalOrder, R, Scope>
348where
349 T: Serialize + DeserializeOwned + PartialEq,
350{
351 /// Scripts the next batch to be exactly the next `n` buffered elements. The tick
352 /// fires at the first moment the decision can be honored in full.
353 pub fn release(&self, n: usize) -> DecisionFuture {
354 DecisionFuture::new(self.id, self.member, &BatchDecision::<T>::Prefix(n))
355 }
356
357 /// Scripts the next batch to be exactly this sequence of values. Values must match the
358 /// buffered prefix in order: a mismatching available value panics immediately, while a
359 /// matching but incomplete prefix waits for the remaining values to arrive.
360 pub fn release_values(&self, values: impl IntoIterator<Item = T>) -> DecisionFuture {
361 DecisionFuture::new(
362 self.id,
363 self.member,
364 &BatchDecision::Values(values.into_iter().collect()),
365 )
366 }
367
368 /// Scripts the next batch to be everything that has arrived by the time the tick
369 /// fires. Under fuzzing, the released contents co-vary with the schedule being
370 /// explored; use [`Self::release`] to name them exactly.
371 pub fn release_all(&self) -> DecisionFuture {
372 DecisionFuture::new(self.id, self.member, &BatchDecision::<T>::All)
373 }
374
375 /// Scripts the next batch to be empty, holding everything buffered. Shorthand for
376 /// [`Self::release`]`(0)`.
377 pub fn release_empty(&self) -> DecisionFuture {
378 self.release(0)
379 }
380}
381
382impl<T, Scope: ScriptableHookScope> BatchHook<T, TotalOrder, AtLeastOnce, Scope>
383where
384 T: Serialize + DeserializeOwned + PartialEq,
385{
386 /// Like [`Self::release`], but the last released element stays buffered, so it is
387 /// delivered again as the first element of the next batch.
388 ///
389 /// # Panics
390 /// If `n` is zero.
391 #[track_caller]
392 pub fn release_keep_last(&self, n: usize) -> DecisionFuture {
393 assert!(
394 n >= 1,
395 "release_keep_last: at least one element must be released to keep its last"
396 );
397 DecisionFuture::new(self.id, self.member, &BatchDecision::<T>::PrefixKeepLast(n))
398 }
399
400 /// Like [`Self::release_values`], but the last released element stays buffered; see
401 /// [`Self::release_keep_last`].
402 ///
403 /// # Panics
404 /// If `values` is empty.
405 #[track_caller]
406 pub fn release_values_keep_last(&self, values: impl IntoIterator<Item = T>) -> DecisionFuture {
407 let values: Vec<T> = values.into_iter().collect();
408 assert!(
409 !values.is_empty(),
410 "release_values_keep_last: at least one value must be released to keep its last"
411 );
412 DecisionFuture::new(self.id, self.member, &BatchDecision::ValuesKeepLast(values))
413 }
414}
415
416impl<T, R: Retries, Scope: ScriptableHookScope> BatchHook<T, NoOrder, R, Scope>
417where
418 T: Serialize + DeserializeOwned + PartialEq,
419{
420 /// Scripts the next batch to contain exactly this multiset of buffered values. Values
421 /// are matched independently of arrival order; duplicates request the corresponding
422 /// number of equal buffered items. The tick fires once every requested value exists.
423 pub fn release_values(&self, values: impl IntoIterator<Item = T>) -> DecisionFuture {
424 DecisionFuture::new(
425 self.id,
426 self.member,
427 &UnorderedBatchDecision::Values(values.into_iter().collect()),
428 )
429 }
430
431 /// Scripts the next batch to be everything that has arrived by the time the tick
432 /// fires. Under fuzzing, the released contents co-vary with the schedule being
433 /// explored; use [`Self::release_values`] to name them exactly.
434 pub fn release_all(&self) -> DecisionFuture {
435 DecisionFuture::new(self.id, self.member, &UnorderedBatchDecision::<T>::All)
436 }
437
438 /// Scripts the next batch to be empty, holding everything buffered. Shorthand for
439 /// [`Self::release_values`] with no values.
440 pub fn release_empty(&self) -> DecisionFuture {
441 self.release_values([])
442 }
443}
444
445impl<T, Scope: ScriptableHookScope> BatchHook<T, NoOrder, AtLeastOnce, Scope>
446where
447 T: Serialize + DeserializeOwned + PartialEq,
448{
449 /// Like [`Self::release_values`], but the elements matching `keep` (a subset of
450 /// `values`) stay buffered, so they are delivered again in a later batch.
451 pub fn release_values_keep(
452 &self,
453 values: impl IntoIterator<Item = T>,
454 keep: impl IntoIterator<Item = T>,
455 ) -> DecisionFuture {
456 DecisionFuture::new(
457 self.id,
458 self.member,
459 &UnorderedBatchDecision::ValuesKeep(
460 values.into_iter().collect(),
461 keep.into_iter().collect(),
462 ),
463 )
464 }
465}
466
467impl<T, Scope: ScriptableHookScope> OrderingHook<T, Unbounded, ExactlyOnce, Scope>
468where
469 T: Serialize + DeserializeOwned,
470{
471 /// Scripts a top-level `assume_ordering` action to release the buffered element equal
472 /// to `value`. Exactly one element is released, preserving opportunities for ticks and
473 /// feedback to interleave with the remaining buffered input.
474 pub fn next(&self, value: T) -> DecisionFuture {
475 DecisionFuture::new(self.id, self.member, &TopLevelOrderingDecision::Next(value))
476 }
477
478 pause_family!(OrderingStatus);
479
480 /// Pauses a top-level ordering hook until at least `n` elements are buffered; see
481 /// [`Self::pause_until`].
482 pub fn pause_until_count(
483 &self,
484 n: usize,
485 ) -> PauseUntilFuture<OrderingStatus, impl Fn(&OrderingStatus) -> bool + Unpin> {
486 self.pause_until_labeled(format!("pause_until_count({})", n), move |status| {
487 status.buffered >= n
488 })
489 }
490}
491
492impl<T, Scope: ScriptableHookScope> OrderingHook<T, Bounded, ExactlyOnce, Scope>
493where
494 T: Serialize + DeserializeOwned,
495{
496 /// Scripts an in-tick `assume_ordering` observation to consume its complete input in
497 /// exactly this order. The supplied values must be a permutation of all values received
498 /// by the operator during that tick.
499 pub fn order(&self, values: impl IntoIterator<Item = T>) -> DecisionFuture {
500 DecisionFuture::new(
501 self.id,
502 self.member,
503 &InlineOrderingDecision::Order(values.into_iter().collect()),
504 )
505 }
506}
507
508impl<T, Scope: ScriptableHookScope> OrderingHook<T, Unbounded, AtLeastOnce, Scope>
509where
510 T: Serialize + DeserializeOwned,
511{
512 /// Scripts a top-level `assume_ordering` action on an at-least-once stream to release
513 /// one **slot** for the value `value`, *keeping* it buffered: later decisions may
514 /// emit it again (a delayed redelivery, still `AtLeastOnce`), after other elements
515 /// have taken slots in between.
516 ///
517 /// The value remains pending input, so the script must eventually retire it with
518 /// [`Self::emit_final`] (or declare the buffering with the pause family). The
519 /// immediately-following decision may name the same value again only when two or
520 /// more buffered elements share it (the adjacent slots then belong to different
521 /// elements): a sole element in adjacent slots would be a redundant duplicate —
522 /// adjacent duplicate slots denote the same at-least-once collection, and per-slot
523 /// *cardinality* belongs to the downstream `assume_retries` observation.
524 pub fn emit(&self, value: T) -> DecisionFuture {
525 DecisionFuture::new(
526 self.id,
527 self.member,
528 &AtLeastOnceOrderingDecision::Emit(value),
529 )
530 }
531
532 /// Scripts a top-level `assume_ordering` action on an at-least-once stream to release
533 /// the *last* slot for the value `value`, consuming **every** buffered element equal
534 /// to it (the script names values, not individual elements, so retirement is
535 /// value-level). Because each buffered element must occupy at least one slot,
536 /// retiring a value that several buffered elements share requires enough prior
537 /// [`Self::emit`]s: `k` equal buffered elements need at least `k` slots in total. A
538 /// value that was never emitted before simply occupies a single slot.
539 pub fn emit_final(&self, value: T) -> DecisionFuture {
540 DecisionFuture::new(
541 self.id,
542 self.member,
543 &AtLeastOnceOrderingDecision::EmitFinal(value),
544 )
545 }
546
547 pause_family!(OrderingStatus);
548
549 /// Pauses a top-level ordering hook until at least `n` elements are buffered; see
550 /// [`Self::pause_until`].
551 pub fn pause_until_count(
552 &self,
553 n: usize,
554 ) -> PauseUntilFuture<OrderingStatus, impl Fn(&OrderingStatus) -> bool + Unpin> {
555 self.pause_until_labeled(format!("pause_until_count({})", n), move |status| {
556 status.buffered >= n
557 })
558 }
559}
560
561impl<T, Scope: ScriptableHookScope> OrderingHook<T, Bounded, AtLeastOnce, Scope>
562where
563 T: Serialize + DeserializeOwned,
564{
565 /// Scripts an in-tick `assume_ordering` observation on an at-least-once stream to
566 /// consume its complete input in exactly this slot sequence. Every value received by
567 /// the operator during that tick must be emitted into at least one slot, and a value
568 /// may occupy several **non-adjacent** slots — each extra slot is a delayed
569 /// redelivery, still `AtLeastOnce`. Only received values may appear, and adjacent
570 /// equal slots are accepted only when the tick received at least two equal instances
571 /// of that value (a sole instance in adjacent slots would be a redundant duplicate —
572 /// per-slot cardinality belongs to the downstream `assume_retries`).
573 pub fn order(&self, values: impl IntoIterator<Item = T>) -> DecisionFuture {
574 DecisionFuture::new(
575 self.id,
576 self.member,
577 &InlineOrderingDecision::Order(values.into_iter().collect()),
578 )
579 }
580}
581
582impl<T, O: Ordering, Scope: ScriptableHookScope> RetriesHook<T, O, Unbounded, Scope> {
583 pause_family!(OrderingStatus);
584
585 /// Pauses a top-level retries hook until at least `n` elements are buffered; see
586 /// [`Self::pause_until`].
587 pub fn pause_until_count(
588 &self,
589 n: usize,
590 ) -> PauseUntilFuture<OrderingStatus, impl Fn(&OrderingStatus) -> bool + Unpin> {
591 self.pause_until_labeled(format!("pause_until_count({})", n), move |status| {
592 status.buffered >= n
593 })
594 }
595}
596
597impl<T, Scope: ScriptableHookScope> RetriesHook<T, NoOrder, Unbounded, Scope>
598where
599 T: Serialize + DeserializeOwned,
600{
601 /// Scripts a top-level `assume_retries` action to release `copies` copies of the
602 /// buffered element equal to `value`, consuming it. This is where the simulator
603 /// injects the duplicates the `AtLeastOnce` input type says downstream must
604 /// tolerate; `copies` is the *total* number of deliveries, so `release(v, 1)`
605 /// observes `v` exactly once, with no duplicate.
606 ///
607 /// Any buffered element may be named — the copies' placement is unobservable on a
608 /// `NoOrder` output, so the cardinality is the entire decision.
609 ///
610 /// # Panics
611 /// Panics immediately if `copies` is zero: releasing an element zero times would be
612 /// a *loss*, which `AtLeastOnce` does not permit.
613 #[track_caller]
614 pub fn release(&self, value: T, copies: usize) -> DecisionFuture {
615 assert_copies_at_least_one(copies);
616 DecisionFuture::new(
617 self.id,
618 self.member,
619 &NoOrderRetriesDecision::Release(value, copies),
620 )
621 }
622}
623
624impl<T, Scope: ScriptableHookScope> RetriesHook<T, TotalOrder, Unbounded, Scope>
625where
626 T: Serialize + DeserializeOwned,
627{
628 /// Scripts a top-level `assume_retries` action to release these values, which must
629 /// match a prefix of the buffered queue in arrival order, where a value may be
630 /// repeated back-to-back to simulate retries. This is where the simulator injects
631 /// the duplicates the `AtLeastOnce` input type says downstream must tolerate. The
632 /// decision fires only once it can be honored in full; matched elements before the
633 /// last value are consumed (a later value can only start once the earlier one's
634 /// copies ended).
635 ///
636 /// This is the **non-final** form: the trailing value's element stays buffered with
637 /// its copies left open, so later decisions may release more copies of it —
638 /// scripting `release` never over-commits to an element being done. The element
639 /// remains pending input until a [`Self::release_final`] consumes it (or the
640 /// buffering is declared with the pause family). Elements left un-released by a
641 /// partial decision likewise stay pending, and downstream tick-input hooks batch
642 /// independently of how releases are grouped into decisions.
643 ///
644 /// # Panics
645 /// Panics immediately if `values` is empty: a decision must release something (use
646 /// the pause family to hold data on purpose).
647 #[track_caller]
648 pub fn release(&self, values: impl IntoIterator<Item = T>) -> DecisionFuture {
649 let values: Vec<T> = values.into_iter().collect();
650 assert!(
651 !values.is_empty(),
652 "release: at least one value must be released (declare intentional buffering with the pause family instead)"
653 );
654 DecisionFuture::new(
655 self.id,
656 self.member,
657 &OrderedRetriesDecision::Release(values),
658 )
659 }
660
661 /// Like [`Self::release`], but **final**: the trailing value's element is consumed
662 /// along with the rest of the matched prefix, declaring that no more copies of it
663 /// will be observed. With no values, finalizes a front element whose copies were
664 /// all released by earlier `release` decisions, delivering nothing more.
665 pub fn release_final(&self, values: impl IntoIterator<Item = T>) -> DecisionFuture {
666 DecisionFuture::new(
667 self.id,
668 self.member,
669 &OrderedRetriesDecision::ReleaseFinal(values.into_iter().collect()),
670 )
671 }
672
673 /// Scripts a top-level `assume_retries` action to release `copies` copies of the
674 /// front of the buffered queue, whatever it is, consuming it (waiting for an
675 /// element to arrive if the queue is empty). Unlike [`Self::release_final`], this
676 /// does not assert the released value; prefer the value-naming forms, which fail
677 /// loudly when the script falls out of sync with the program.
678 ///
679 /// # Panics
680 /// Panics immediately if `copies` is zero: releasing an element zero times would be
681 /// a *loss*, which `AtLeastOnce` does not permit.
682 #[track_caller]
683 pub fn release_next(&self, copies: usize) -> DecisionFuture {
684 assert_copies_at_least_one(copies);
685 DecisionFuture::new(
686 self.id,
687 self.member,
688 &OrderedRetriesDecision::<T>::ReleaseNext(copies),
689 )
690 }
691}
692
693impl<T, O: Ordering, Scope: ScriptableHookScope> RetriesHook<T, O, Bounded, Scope>
694where
695 T: Serialize + DeserializeOwned,
696{
697 /// Scripts an in-tick `assume_retries` observation to consume its complete input and
698 /// release exactly these values. Every value received by the operator during that
699 /// tick must be released at least once, and only received values may appear.
700 ///
701 /// On a `TotalOrder` stream the scripted sequence must follow the input order, where
702 /// a value may repeat only back-to-back (a repeat cannot come after a different
703 /// value). On a `NoOrder` stream only the multiset of scripted values matters.
704 pub fn release(&self, values: impl IntoIterator<Item = T>) -> DecisionFuture {
705 DecisionFuture::new(
706 self.id,
707 self.member,
708 &InlineRetriesDecision::Release(values.into_iter().collect()),
709 )
710 }
711}
712
713impl<T, Scope: ScriptableHookScope> SnapshotHook<T, Scope> {
714 /// Scripts the next tick execution to observe the buffered version equal to `value`:
715 /// scans forward from the currently-revealed version through the buffered ones and
716 /// releases the first equal version, skipping over earlier versions.
717 ///
718 /// This is a combined assertion and release, and the recommended way to script
719 /// snapshots: a script written with positional decisions breaks silently when the
720 /// program changes how often the state updates, while `reveal(value)` names the state
721 /// it means and any mis-synchronization fails loudly at the reveal.
722 pub fn reveal(&self, value: T) -> DecisionFuture
723 where
724 T: Serialize + DeserializeOwned,
725 {
726 DecisionFuture::new(self.id, self.member, &SnapshotDecision::Reveal(value))
727 }
728
729 /// Scripts the next tick execution to observe the next buffered version.
730 pub fn reveal_next(&self) -> DecisionFuture
731 where
732 T: Serialize + DeserializeOwned,
733 {
734 DecisionFuture::new(self.id, self.member, &SnapshotDecision::<T>::RevealNext)
735 }
736
737 /// Scripts the next tick execution to observe the newest version that has arrived by
738 /// the time the tick fires. Under fuzzing, which version is newest co-varies with the
739 /// schedule being explored; use [`Self::reveal`] to name it exactly.
740 pub fn reveal_latest(&self) -> DecisionFuture
741 where
742 T: Serialize + DeserializeOwned,
743 {
744 DecisionFuture::new(self.id, self.member, &SnapshotDecision::<T>::RevealLatest)
745 }
746
747 /// Scripts the next tick execution to observe the previously revealed version again.
748 pub fn keep(&self) -> DecisionFuture
749 where
750 T: Serialize + DeserializeOwned,
751 {
752 DecisionFuture::new(self.id, self.member, &SnapshotDecision::<T>::Keep)
753 }
754
755 pause_family!(SnapshotStatus);
756
757 /// Pauses the hook and returns a future that resolves once at least `n` newer
758 /// versions are buffered; see [`Self::pause_until`].
759 pub fn pause_until_versions(
760 &self,
761 n: usize,
762 ) -> PauseUntilFuture<SnapshotStatus, impl Fn(&SnapshotStatus) -> bool + Unpin> {
763 self.pause_until_labeled(format!("pause_until_versions({})", n), move |status| {
764 status.newer_versions >= n
765 })
766 }
767}
768
769impl<K, V, O: Ordering, R: Retries, Scope: ScriptableHookScope> KeyedBatchHook<K, V, O, R, Scope> {
770 pause_family!(BatchStatus);
771
772 /// Pauses the hook and returns a future that resolves once at least `n` entries are
773 /// buffered (in total, across all keys); see [`Self::pause_until`].
774 pub fn pause_until_count(
775 &self,
776 n: usize,
777 ) -> PauseUntilFuture<BatchStatus, impl Fn(&BatchStatus) -> bool + Unpin> {
778 self.pause_until_labeled(format!("pause_until_count({})", n), move |status| {
779 status.buffered >= n
780 })
781 }
782}
783
784impl<K, V, R: Retries, Scope: ScriptableHookScope> KeyedBatchHook<K, V, TotalOrder, R, Scope>
785where
786 K: Serialize + DeserializeOwned + PartialEq,
787 V: Serialize + DeserializeOwned + PartialEq,
788{
789 /// Scripts the next batch to be exactly the next `count` buffered values of each
790 /// named key. The tick fires at the first moment the decision can be honored in
791 /// full.
792 ///
793 /// # Panics
794 /// Panics immediately if `counts` names the same key more than once.
795 #[track_caller]
796 pub fn release(&self, counts: impl IntoIterator<Item = (K, usize)>) -> DecisionFuture
797 where
798 K: std::hash::Hash + Eq,
799 {
800 let counts: Vec<(K, usize)> = counts.into_iter().collect();
801 assert_distinct_keys(counts.iter().map(|(key, _)| key), "release");
802 DecisionFuture::new(
803 self.id,
804 self.member,
805 &KeyedBatchDecision::<K, V>::Prefixes(counts),
806 )
807 }
808
809 /// Scripts the next batch to be exactly these `(key, value)` entries. Each key's
810 /// values must match that key's buffered prefix in order (the interleaving of
811 /// *different* keys in the scripted sequence is irrelevant): a mismatching available
812 /// value panics immediately, while a matching but incomplete prefix waits for the
813 /// remaining values to arrive.
814 pub fn release_values(&self, entries: impl IntoIterator<Item = (K, V)>) -> DecisionFuture {
815 DecisionFuture::new(
816 self.id,
817 self.member,
818 &KeyedBatchDecision::Values(entries.into_iter().collect()),
819 )
820 }
821
822 /// Scripts the next batch to be everything that has arrived by the time the tick
823 /// fires. Under fuzzing, the released contents co-vary with the schedule being
824 /// explored; use [`Self::release_values`] to name them exactly.
825 pub fn release_all(&self) -> DecisionFuture {
826 DecisionFuture::new(self.id, self.member, &KeyedBatchDecision::<K, V>::All)
827 }
828
829 /// Scripts the next batch to be empty, holding everything buffered. Shorthand for
830 /// [`Self::release_values`] with no entries.
831 pub fn release_empty(&self) -> DecisionFuture {
832 self.release_values([])
833 }
834}
835
836impl<K, V, Scope: ScriptableHookScope> KeyedBatchHook<K, V, TotalOrder, AtLeastOnce, Scope>
837where
838 K: Serialize + DeserializeOwned + PartialEq,
839 V: Serialize + DeserializeOwned + PartialEq,
840{
841 /// Like [`Self::release`], but each key's last released value stays buffered, so it
842 /// is delivered again as that key's first value in the next batch.
843 ///
844 /// # Panics
845 /// If `counts` names the same key more than once, or any count is zero.
846 #[track_caller]
847 pub fn release_keep_last(&self, counts: impl IntoIterator<Item = (K, usize)>) -> DecisionFuture
848 where
849 K: std::hash::Hash + Eq,
850 {
851 let counts: Vec<(K, usize)> = counts.into_iter().collect();
852 assert_distinct_keys(counts.iter().map(|(key, _)| key), "release_keep_last");
853 assert!(
854 counts.iter().all(|(_, count)| *count >= 1),
855 "release_keep_last: every named key must release at least one value to keep its last"
856 );
857 DecisionFuture::new(
858 self.id,
859 self.member,
860 &KeyedBatchDecision::<K, V>::PrefixesKeepLast(counts),
861 )
862 }
863
864 /// Like [`Self::release_values`], but each key's last released value stays buffered;
865 /// see [`Self::release_keep_last`].
866 ///
867 /// # Panics
868 /// If `entries` is empty.
869 #[track_caller]
870 pub fn release_values_keep_last(
871 &self,
872 entries: impl IntoIterator<Item = (K, V)>,
873 ) -> DecisionFuture {
874 let entries: Vec<(K, V)> = entries.into_iter().collect();
875 assert!(
876 !entries.is_empty(),
877 "release_values_keep_last: at least one entry must be released to keep its last"
878 );
879 DecisionFuture::new(
880 self.id,
881 self.member,
882 &KeyedBatchDecision::ValuesKeepLast(entries),
883 )
884 }
885}
886
887impl<K, V, R: Retries, Scope: ScriptableHookScope> KeyedBatchHook<K, V, NoOrder, R, Scope>
888where
889 K: Serialize + DeserializeOwned + PartialEq,
890 V: Serialize + DeserializeOwned + PartialEq,
891{
892 /// Scripts the next batch to contain exactly these `(key, value)` entries. Values are
893 /// matched per key as multisets (independently of arrival order); duplicates request
894 /// the corresponding number of equal buffered items. The tick fires once every
895 /// requested entry exists.
896 pub fn release_values(&self, entries: impl IntoIterator<Item = (K, V)>) -> DecisionFuture {
897 DecisionFuture::new(
898 self.id,
899 self.member,
900 &UnorderedKeyedBatchDecision::Values(entries.into_iter().collect()),
901 )
902 }
903
904 /// Scripts the next batch to be everything that has arrived by the time the tick
905 /// fires. Under fuzzing, the released contents co-vary with the schedule being
906 /// explored; use [`Self::release_values`] to name them exactly.
907 pub fn release_all(&self) -> DecisionFuture {
908 DecisionFuture::new(
909 self.id,
910 self.member,
911 &UnorderedKeyedBatchDecision::<K, V>::All,
912 )
913 }
914
915 /// Scripts the next batch to be empty, holding everything buffered. Shorthand for
916 /// [`Self::release_values`] with no entries.
917 pub fn release_empty(&self) -> DecisionFuture {
918 self.release_values([])
919 }
920}
921
922impl<K, V, Scope: ScriptableHookScope> KeyedBatchHook<K, V, NoOrder, AtLeastOnce, Scope>
923where
924 K: Serialize + DeserializeOwned + PartialEq,
925 V: Serialize + DeserializeOwned + PartialEq,
926{
927 /// Like [`Self::release_values`], but the entries matching `keep` (a subset of
928 /// `entries`) stay buffered, so they are delivered again in a later batch.
929 pub fn release_values_keep(
930 &self,
931 entries: impl IntoIterator<Item = (K, V)>,
932 keep: impl IntoIterator<Item = (K, V)>,
933 ) -> DecisionFuture {
934 DecisionFuture::new(
935 self.id,
936 self.member,
937 &UnorderedKeyedBatchDecision::ValuesKeep(
938 entries.into_iter().collect(),
939 keep.into_iter().collect(),
940 ),
941 )
942 }
943}
944
945impl<K, V, Scope: ScriptableHookScope> KeyedSnapshotHook<K, V, Scope> {
946 /// Scripts the next tick execution to observe, for each named key, the buffered
947 /// version equal to the named value: scans forward from that key's currently-revealed
948 /// version through the buffered ones and releases the first equal version, skipping
949 /// over earlier versions. Keys that are not named observe their previously revealed
950 /// version again (or stay absent if they have never been revealed).
951 ///
952 /// This is a combined assertion and release, and the recommended way to script keyed
953 /// snapshots: naming the state each key means makes any mis-synchronization fail
954 /// loudly at the reveal.
955 ///
956 /// # Panics
957 /// Panics immediately if `entries` names the same key more than once: a key observes
958 /// exactly one version per tick execution.
959 #[track_caller]
960 pub fn reveal(&self, entries: impl IntoIterator<Item = (K, V)>) -> DecisionFuture
961 where
962 K: Serialize + DeserializeOwned + std::hash::Hash + Eq,
963 V: Serialize + DeserializeOwned,
964 {
965 let entries: Vec<(K, V)> = entries.into_iter().collect();
966 assert_distinct_keys(entries.iter().map(|(key, _)| key), "reveal");
967 DecisionFuture::new(
968 self.id,
969 self.member,
970 &KeyedSnapshotDecision::Reveal(entries),
971 )
972 }
973
974 /// Scripts the next tick execution to observe, for every key, the newest version that
975 /// has arrived by the time the tick fires (keys with nothing newer observe their
976 /// previously revealed version again). Under fuzzing, which versions are newest
977 /// co-varies with the schedule being explored; use [`Self::reveal`] to name them
978 /// exactly.
979 pub fn reveal_latest(&self) -> DecisionFuture
980 where
981 K: Serialize + DeserializeOwned,
982 V: Serialize + DeserializeOwned,
983 {
984 DecisionFuture::new(
985 self.id,
986 self.member,
987 &KeyedSnapshotDecision::<K, V>::RevealLatest,
988 )
989 }
990
991 /// Scripts the next tick execution to observe every key's previously revealed version
992 /// again.
993 pub fn keep(&self) -> DecisionFuture
994 where
995 K: Serialize + DeserializeOwned,
996 V: Serialize + DeserializeOwned,
997 {
998 DecisionFuture::new(self.id, self.member, &KeyedSnapshotDecision::<K, V>::Keep)
999 }
1000
1001 pause_family!(KeyedSnapshotStatus);
1002
1003 /// Pauses the hook and returns a future that resolves once at least `n` newer
1004 /// versions are buffered (in total, across all keys); see [`Self::pause_until`].
1005 pub fn pause_until_versions(
1006 &self,
1007 n: usize,
1008 ) -> PauseUntilFuture<KeyedSnapshotStatus, impl Fn(&KeyedSnapshotStatus) -> bool + Unpin> {
1009 self.pause_until_labeled(format!("pause_until_versions({})", n), move |status| {
1010 status.newer_versions >= n
1011 })
1012 }
1013}
1014
1015impl<K, V, Scope: ScriptableHookScope> KeyedOrderingHook<K, V, Unbounded, Scope>
1016where
1017 K: Serialize + DeserializeOwned,
1018 V: Serialize + DeserializeOwned,
1019{
1020 /// Scripts a top-level keyed `assume_ordering` action to release the buffered entry
1021 /// under `key` equal to `value`. Exactly one entry is released, preserving
1022 /// opportunities for ticks and feedback to interleave with the remaining buffered
1023 /// input.
1024 pub fn next(&self, key: K, value: V) -> DecisionFuture {
1025 DecisionFuture::new(
1026 self.id,
1027 self.member,
1028 &TopLevelOrderingDecision::Next((key, value)),
1029 )
1030 }
1031
1032 pause_family!(OrderingStatus);
1033
1034 /// Pauses a top-level keyed ordering hook until at least `n` entries are buffered (in
1035 /// total, across all keys); see [`Self::pause_until`].
1036 pub fn pause_until_count(
1037 &self,
1038 n: usize,
1039 ) -> PauseUntilFuture<OrderingStatus, impl Fn(&OrderingStatus) -> bool + Unpin> {
1040 self.pause_until_labeled(format!("pause_until_count({})", n), move |status| {
1041 status.buffered >= n
1042 })
1043 }
1044}
1045
1046impl<K, V, Scope: ScriptableHookScope> KeyedOrderingHook<K, V, Bounded, Scope>
1047where
1048 K: Serialize + DeserializeOwned,
1049 V: Serialize + DeserializeOwned,
1050{
1051 /// Scripts an in-tick keyed `assume_ordering` observation to consume its complete
1052 /// input with each key's values in exactly the scripted per-key order. The supplied
1053 /// entries must contain exactly all `(key, value)` entries received by the operator
1054 /// during that tick; the relative order of *different* keys in the scripted sequence
1055 /// is irrelevant (a keyed stream carries no cross-key ordering).
1056 pub fn order(&self, entries: impl IntoIterator<Item = (K, V)>) -> DecisionFuture {
1057 DecisionFuture::new(
1058 self.id,
1059 self.member,
1060 &InlineOrderingDecision::Order(entries.into_iter().collect()),
1061 )
1062 }
1063}
1064
1065impl<K, V, Scope: ScriptableHookScope> PartialOrderingHook<K, V, Unbounded, Scope>
1066where
1067 K: Serialize + DeserializeOwned,
1068 V: Serialize + DeserializeOwned,
1069{
1070 /// Scripts a top-level `entries_partially_ordered` action to release the front entry
1071 /// of `key`'s buffer, which must equal `value` (within-key order is preserved, so a
1072 /// mismatch panics). Exactly one entry is released, preserving opportunities for
1073 /// ticks and feedback to interleave with the remaining buffered input.
1074 pub fn next(&self, key: K, value: V) -> DecisionFuture {
1075 DecisionFuture::new(
1076 self.id,
1077 self.member,
1078 &TopLevelOrderingDecision::Next((key, value)),
1079 )
1080 }
1081
1082 pause_family!(OrderingStatus);
1083
1084 /// Pauses a top-level partially-ordered hook until at least `n` entries are buffered
1085 /// (in total, across all keys); see [`Self::pause_until`].
1086 pub fn pause_until_count(
1087 &self,
1088 n: usize,
1089 ) -> PauseUntilFuture<OrderingStatus, impl Fn(&OrderingStatus) -> bool + Unpin> {
1090 self.pause_until_labeled(format!("pause_until_count({})", n), move |status| {
1091 status.buffered >= n
1092 })
1093 }
1094}
1095
1096impl<K, V, Scope: ScriptableHookScope> PartialOrderingHook<K, V, Bounded, Scope>
1097where
1098 K: Serialize + DeserializeOwned,
1099 V: Serialize + DeserializeOwned,
1100{
1101 /// Scripts an in-tick `entries_partially_ordered` observation to consume its complete
1102 /// input in exactly this interleaving. The supplied entries must be a permutation of
1103 /// all `(key, value)` entries received by the operator during that tick that preserves
1104 /// each key's within-key order.
1105 pub fn order(&self, entries: impl IntoIterator<Item = (K, V)>) -> DecisionFuture {
1106 DecisionFuture::new(
1107 self.id,
1108 self.member,
1109 &InlineOrderingDecision::Order(entries.into_iter().collect()),
1110 )
1111 }
1112}
1113
1114impl<T, Scope: ScriptableHookScope> MergeOrderedHook<T, Unbounded, Scope>
1115where
1116 T: Serialize + DeserializeOwned,
1117{
1118 /// Scripts a top-level `merge_ordered` action to release the front element of the
1119 /// *first* input's buffer, which must equal `value` (per-input order is preserved, so
1120 /// a mismatch panics). Exactly one element is released, preserving opportunities for
1121 /// ticks and feedback to interleave with the remaining buffered input.
1122 pub fn next_first(&self, value: T) -> DecisionFuture {
1123 DecisionFuture::new(self.id, self.member, &MergeDecision::<T>::First(value))
1124 }
1125
1126 /// Scripts a top-level `merge_ordered` action to release the front element of the
1127 /// *second* input's buffer, which must equal `value`; see [`Self::next_first`].
1128 pub fn next_second(&self, value: T) -> DecisionFuture {
1129 DecisionFuture::new(self.id, self.member, &MergeDecision::<T>::Second(value))
1130 }
1131
1132 /// Scripts a top-level `merge_ordered` action to release the front element of the
1133 /// *first* input's buffer, whatever it is (waiting for one to arrive if that input is
1134 /// empty). Unlike [`Self::next_first`], this does not assert the released value; use
1135 /// `next_first(value)` to name it exactly and fail loudly on mis-synchronization.
1136 pub fn advance_first(&self) -> DecisionFuture {
1137 DecisionFuture::new(self.id, self.member, &MergeDecision::<T>::FirstNext(()))
1138 }
1139
1140 /// Scripts a top-level `merge_ordered` action to release the front element of the
1141 /// *second* input's buffer, whatever it is; see [`Self::advance_first`].
1142 pub fn advance_second(&self) -> DecisionFuture {
1143 DecisionFuture::new(self.id, self.member, &MergeDecision::<T>::SecondNext(()))
1144 }
1145
1146 pause_family!(MergeStatus);
1147
1148 /// Pauses a top-level merge hook until at least `n` elements are buffered (in total,
1149 /// across both inputs); see [`Self::pause_until`].
1150 pub fn pause_until_count(
1151 &self,
1152 n: usize,
1153 ) -> PauseUntilFuture<MergeStatus, impl Fn(&MergeStatus) -> bool + Unpin> {
1154 self.pause_until_labeled(format!("pause_until_count({})", n), move |status| {
1155 status.first_buffered + status.second_buffered >= n
1156 })
1157 }
1158}
1159
1160impl<T, Scope: ScriptableHookScope> MergeOrderedHook<T, Bounded, Scope>
1161where
1162 T: Serialize + DeserializeOwned,
1163{
1164 /// Scripts an in-tick `merge_ordered` observation to consume its complete input in
1165 /// exactly this interleaving, with each value labeled by the input it is drawn from
1166 /// (`false` = first/left, `true` = second/right). Each input's labeled values must be
1167 /// exactly that input's tick-local batch, in order.
1168 pub fn order(&self, values: impl IntoIterator<Item = (bool, T)>) -> DecisionFuture {
1169 DecisionFuture::new(
1170 self.id,
1171 self.member,
1172 &InlineOrderingDecision::Order(values.into_iter().collect()),
1173 )
1174 }
1175}
1176
1177impl<K, V, Scope: ScriptableHookScope> KeyedMergeOrderedHook<K, V, Unbounded, Scope>
1178where
1179 K: Serialize + DeserializeOwned,
1180 V: Serialize + DeserializeOwned,
1181{
1182 /// Scripts a top-level keyed `merge_ordered` action to release the front entry of
1183 /// `key`'s buffer in the *first* input, which must equal `value` (per-input
1184 /// within-key order is preserved, so a mismatch panics). Exactly one entry is
1185 /// released, preserving opportunities for ticks and feedback to interleave with the
1186 /// remaining buffered input.
1187 pub fn next_first(&self, key: K, value: V) -> DecisionFuture {
1188 DecisionFuture::new(
1189 self.id,
1190 self.member,
1191 &MergeDecision::<(K, V), K>::First((key, value)),
1192 )
1193 }
1194
1195 /// Scripts a top-level keyed `merge_ordered` action to release the front entry of
1196 /// `key`'s buffer in the *second* input, which must equal `value`; see
1197 /// [`Self::next_first`].
1198 pub fn next_second(&self, key: K, value: V) -> DecisionFuture {
1199 DecisionFuture::new(
1200 self.id,
1201 self.member,
1202 &MergeDecision::<(K, V), K>::Second((key, value)),
1203 )
1204 }
1205
1206 /// Scripts a top-level keyed `merge_ordered` action to release the front entry of
1207 /// `key`'s buffer in the *first* input, whatever its value (waiting for one to arrive
1208 /// if that key's buffer is empty). Unlike [`Self::next_first`], this does not assert
1209 /// the released value; use `next_first(key, value)` to name it exactly and fail
1210 /// loudly on mis-synchronization.
1211 pub fn advance_first(&self, key: K) -> DecisionFuture {
1212 DecisionFuture::new(
1213 self.id,
1214 self.member,
1215 &MergeDecision::<(K, V), K>::FirstNext(key),
1216 )
1217 }
1218
1219 /// Scripts a top-level keyed `merge_ordered` action to release the front entry of
1220 /// `key`'s buffer in the *second* input, whatever its value; see
1221 /// [`Self::advance_first`].
1222 pub fn advance_second(&self, key: K) -> DecisionFuture {
1223 DecisionFuture::new(
1224 self.id,
1225 self.member,
1226 &MergeDecision::<(K, V), K>::SecondNext(key),
1227 )
1228 }
1229
1230 pause_family!(MergeStatus);
1231
1232 /// Pauses a top-level keyed merge hook until at least `n` entries are buffered (in
1233 /// total, across both inputs and all keys); see [`Self::pause_until`].
1234 pub fn pause_until_count(
1235 &self,
1236 n: usize,
1237 ) -> PauseUntilFuture<MergeStatus, impl Fn(&MergeStatus) -> bool + Unpin> {
1238 self.pause_until_labeled(format!("pause_until_count({})", n), move |status| {
1239 status.first_buffered + status.second_buffered >= n
1240 })
1241 }
1242}
1243
1244impl<K, V, Scope: ScriptableHookScope> KeyedMergeOrderedHook<K, V, Bounded, Scope>
1245where
1246 K: Serialize + DeserializeOwned,
1247 V: Serialize + DeserializeOwned,
1248{
1249 /// Scripts an in-tick keyed `merge_ordered` observation to consume its complete input
1250 /// in exactly this interleaving, with each `(key, value)` entry labeled by the input
1251 /// it is drawn from (`false` = first/left, `true` = second/right). Each input's
1252 /// labeled entries must be exactly that input's tick-local batch, with every key's
1253 /// values in order; the relative order of *different* keys is irrelevant (a keyed
1254 /// stream carries no cross-key ordering).
1255 pub fn order(&self, entries: impl IntoIterator<Item = (bool, K, V)>) -> DecisionFuture {
1256 DecisionFuture::new(
1257 self.id,
1258 self.member,
1259 &InlineOrderingDecision::Order(
1260 entries
1261 .into_iter()
1262 .map(|(from_second, key, value)| (from_second, (key, value)))
1263 .collect(),
1264 ),
1265 )
1266 }
1267}