Skip to main content

hydro_lang/sim/runtime/
tick_input.rs

1//! Tick-input hooks ([`TickInputHook`]): the per-kind hook types that buffer input for
2//! a tick across scheduling boundaries and decide, when the tick runs, what to release
3//! into that execution: batch hooks ([`StreamBatchHook`], [`KeyedStreamBatchHook`]) and snapshot
4//! hooks ([`SingletonHook`], [`KeyedSingletonHook`], and the choice-free
5//! [`PassthroughSingletonHook`]). Their scripted decision/status types and
6//! [`ScriptableHook`] impls live alongside them.
7
8use std::cell::RefCell;
9use std::collections::VecDeque;
10use std::hash::Hash;
11use std::marker::PhantomData;
12use std::rc::Rc;
13
14use bolero::generator::bolero_generator::driver::object::Borrowed;
15use bolero::{ValueGenerator, produce};
16use dfir_rs::rustc_hash::{FxHashMap, FxHashSet};
17use dfir_rs::util::unsync::mpsc::Sender;
18
19use super::{
20    HookLocationMeta, ManualDebug, RetryBudget, RuntimeHook, ScriptDecision, ScriptableHook,
21    ScriptableTickInputHook, TickInputHook, TruncatedVecDebug, abort, describe_keyed_pending,
22    draw_boolean_false_if_exhausted, keyed_buffer_len, log_release,
23};
24use crate::compile::ir::{StreamOrder, StreamRetry};
25use crate::live_collections::stream::{
26    AtLeastOnce, ExactlyOnce, NoOrder, Ordering, Retries, TotalOrder,
27};
28
29/// Whether a batch hook may keep a released element buffered for redelivery in a later
30/// batch. Lets exactly-once hooks skip the keep draw entirely and not require `T: Clone`.
31trait BatchRetries<T>: Retries {
32    /// The copy to release if `item` is kept.
33    fn autonomous_keep(budget: &mut RetryBudget, item: &T, driver: &mut Borrowed<'_>) -> Option<T>;
34
35    fn scripted_keep(item: &T) -> T;
36}
37
38impl<T> BatchRetries<T> for ExactlyOnce {
39    fn autonomous_keep(_: &mut RetryBudget, _: &T, _: &mut Borrowed<'_>) -> Option<T> {
40        None
41    }
42
43    fn scripted_keep(_: &T) -> T {
44        // rejected by `is_honorable`
45        abort!("a keep decision was applied to an exactly-once batch hook")
46    }
47}
48
49impl<T: Clone> BatchRetries<T> for AtLeastOnce {
50    fn autonomous_keep(budget: &mut RetryBudget, item: &T, driver: &mut Borrowed<'_>) -> Option<T> {
51        if budget.allows_retry() && draw_boolean_false_if_exhausted(driver) {
52            budget.spend(1);
53            Some(item.clone())
54        } else {
55            None
56        }
57    }
58
59    fn scripted_keep(item: &T) -> T {
60        item.clone()
61    }
62}
63
64/// Exactly-once handles can't construct keep decisions, this is just a safety net.
65fn check_keep_allowed<R: Retries>(method: &str) -> Result<(), String> {
66    if R::RETRIES_KIND == StreamRetry::ExactlyOnce {
67        Err(format!(
68            "{method}: only an at-least-once stream may keep released elements for redelivery"
69        ))
70    } else {
71        Ok(())
72    }
73}
74
75fn order_label<O: Ordering>() -> &'static str {
76    match O::ORDERING_KIND {
77        StreamOrder::TotalOrder => "",
78        StreamOrder::NoOrder => "unordered ",
79    }
80}
81
82/// Shared [`RuntimeHook::release_decision`] of the batch hooks.
83fn release_batch<T>(
84    to_release: Option<Vec<T>>,
85    kept: usize,
86    label: &str,
87    batch_location: HookLocationMeta,
88    format_item_debug: fn(&T) -> Option<String>,
89    output: &Sender<T>,
90    log_writer: Option<&mut dyn std::fmt::Write>,
91) {
92    let Some(to_release) = to_release else {
93        panic!("No decision to release");
94    };
95    if let Some(log_writer) = log_writer {
96        let HookLocationMeta {
97            location,
98            line,
99            caret_indent,
100        } = batch_location;
101        let note_str = if to_release.is_empty() {
102            "^ releasing no items".to_owned()
103        } else {
104            format!(
105                "^ releasing {}items: {:?}{}",
106                label,
107                TruncatedVecDebug(RefCell::new(Some(to_release.iter())), 8, format_item_debug),
108                if kept > 0 {
109                    format!(" ({} kept for redelivery)", kept)
110                } else {
111                    String::new()
112                }
113            )
114        };
115
116        log_release(
117            log_writer,
118            location,
119            line,
120            caret_indent,
121            &note_str,
122            colored::Color::Green,
123        );
124    }
125
126    for item in to_release {
127        output.try_send(item).unwrap();
128    }
129}
130
131/// For an `AtLeastOnce` stream, a release may also *keep* released elements buffered, so
132/// they are delivered again in a later batch (each spends one unit of the budget when
133/// autonomous). On a `TotalOrder` stream only the last element of the batch may be kept,
134/// so the redelivery is adjacent to the original delivery.
135pub struct StreamBatchHook<T, Order: Ordering, R: Retries> {
136    input: Rc<RefCell<VecDeque<T>>>,
137    to_release: Option<Vec<T>>,
138    /// Only used for logging.
139    kept_in_release: usize,
140    /// Unused for exactly-once streams and when scripted.
141    budget: RetryBudget,
142    output: Sender<T>,
143    batch_location: HookLocationMeta,
144    format_item_debug: fn(&T) -> Option<String>,
145    _marker: PhantomData<(Order, R)>,
146}
147
148impl<T, Order: Ordering> StreamBatchHook<T, Order, ExactlyOnce> {
149    pub fn new(
150        input: Rc<RefCell<VecDeque<T>>>,
151        output: Sender<T>,
152        batch_location: HookLocationMeta,
153        format_item_debug: fn(&T) -> Option<String>,
154    ) -> Self {
155        Self {
156            input,
157            to_release: None,
158            kept_in_release: 0,
159            budget: RetryBudget::Bounded(0),
160            output,
161            batch_location,
162            format_item_debug,
163            _marker: PhantomData,
164        }
165    }
166}
167
168impl<T, Order: Ordering> StreamBatchHook<T, Order, AtLeastOnce> {
169    pub fn new(
170        input: Rc<RefCell<VecDeque<T>>>,
171        output: Sender<T>,
172        batch_location: HookLocationMeta,
173        format_item_debug: fn(&T) -> Option<String>,
174        budget: RetryBudget,
175    ) -> Self {
176        Self {
177            input,
178            to_release: None,
179            kept_in_release: 0,
180            budget,
181            output,
182            batch_location,
183            format_item_debug,
184            _marker: PhantomData,
185        }
186    }
187}
188
189impl<T, Order: Ordering, R: Retries> RuntimeHook for StreamBatchHook<T, Order, R> {
190    fn has_pending_input(&self) -> bool {
191        !self.input.borrow().is_empty()
192    }
193
194    fn only_one_possible_decision(&self) -> bool {
195        // One buffered element is still a real choice: release it or not.
196        self.input.borrow().is_empty()
197    }
198
199    fn release_decision(&mut self, log_writer: Option<&mut dyn std::fmt::Write>) {
200        release_batch(
201            self.to_release.take(),
202            std::mem::take(&mut self.kept_in_release),
203            order_label::<Order>(),
204            self.batch_location,
205            self.format_item_debug,
206            &self.output,
207            log_writer,
208        );
209    }
210
211    fn location_meta(&self) -> HookLocationMeta {
212        self.batch_location
213    }
214}
215
216impl<T, R: BatchRetries<T>> TickInputHook for StreamBatchHook<T, TotalOrder, R> {
217    fn can_trigger_tick(&self) -> bool {
218        !self.input.borrow().is_empty()
219    }
220
221    fn autonomous_decision<'a>(&mut self, driver: &mut Borrowed<'a>, force_trigger: bool) -> bool {
222        let mut input = self.input.borrow_mut();
223        let count = (usize::from(force_trigger)..=input.len())
224            .generate(driver)
225            .unwrap();
226
227        let mut out: Vec<T> = input.drain(0..count.saturating_sub(1)).collect();
228        if count > 0 {
229            match R::autonomous_keep(&mut self.budget, input.front().unwrap(), driver) {
230                Some(copy) => {
231                    out.push(copy);
232                    self.kept_in_release = 1;
233                }
234                None => out.push(input.pop_front().unwrap()),
235            }
236        }
237        self.to_release = Some(out);
238        count > 0
239    }
240}
241
242impl<T, R: BatchRetries<T>> TickInputHook for StreamBatchHook<T, NoOrder, R> {
243    fn can_trigger_tick(&self) -> bool {
244        !self.input.borrow().is_empty()
245    }
246
247    fn autonomous_decision<'a>(&mut self, driver: &mut Borrowed<'a>, force_trigger: bool) -> bool {
248        let mut input = self.input.borrow_mut();
249        let mut out = vec![];
250        let mut kept = 0;
251        let mut min_index = 0;
252        while min_index < input.len() {
253            let must_release = force_trigger && out.is_empty();
254            if !must_release && produce().generate(driver).unwrap() {
255                break;
256            }
257
258            // only pick at or after the previous pick, since the order within an unordered
259            // batch is irrelevant
260            let idx = (min_index..input.len()).generate(driver).unwrap();
261            // a kept element stays in the buffer, so skip past it
262            if let Some(copy) = R::autonomous_keep(&mut self.budget, &input[idx], driver) {
263                out.push(copy);
264                kept += 1;
265                min_index = idx + 1;
266            } else {
267                out.push(input.remove(idx).unwrap());
268                min_index = idx;
269            }
270        }
271
272        self.kept_in_release = kept;
273        let triggered = !out.is_empty();
274        self.to_release = Some(out);
275        triggered
276    }
277}
278
279/// A scripted decision for a totally ordered batch hook. The `KeepLast` forms are only
280/// valid for `AtLeastOnce` streams.
281#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
282pub enum BatchDecision<T> {
283    /// Release the next `n` buffered elements.
284    Prefix(usize),
285    /// Release this exact sequence of values from the front of the buffer.
286    Values(Vec<T>),
287    /// Release everything that has arrived by the time the tick fires.
288    All,
289    /// Like [`Self::Prefix`], but the last element stays buffered.
290    PrefixKeepLast(usize),
291    /// Like [`Self::Values`], but the last element stays buffered.
292    ValuesKeepLast(Vec<T>),
293}
294
295impl<T> ScriptDecision for BatchDecision<T>
296where
297    T: serde::Serialize + serde::de::DeserializeOwned,
298{
299    fn describe(&self) -> String {
300        match self {
301            BatchDecision::Prefix(n) => format!("release({})", n),
302            BatchDecision::Values(values) => {
303                format!("release_values({} value(s))", values.len())
304            }
305            BatchDecision::All => "release_all()".to_owned(),
306            BatchDecision::PrefixKeepLast(n) => format!("release_keep_last({})", n),
307            BatchDecision::ValuesKeepLast(values) => {
308                format!("release_values_keep_last({} value(s))", values.len())
309            }
310        }
311    }
312}
313
314/// A scripted decision for an unordered batch hook. `ValuesKeep` is only valid for
315/// `AtLeastOnce` streams.
316#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
317pub enum UnorderedBatchDecision<T> {
318    /// Release this multiset of values. Duplicate values name duplicate buffered items.
319    Values(Vec<T>),
320    /// Release everything that has arrived by the time the tick fires.
321    All,
322    /// Like [`Self::Values`], but the elements matching the second multiset (a subset of
323    /// the first) stay buffered.
324    ValuesKeep(Vec<T>, Vec<T>),
325}
326
327impl<T> ScriptDecision for UnorderedBatchDecision<T>
328where
329    T: serde::Serialize + serde::de::DeserializeOwned,
330{
331    fn describe(&self) -> String {
332        match self {
333            UnorderedBatchDecision::Values(values) => {
334                format!("release_values({} value(s))", values.len())
335            }
336            UnorderedBatchDecision::All => "release_all()".to_owned(),
337            UnorderedBatchDecision::ValuesKeep(values, keep) => format!(
338                "release_values_keep({} value(s), {} kept)",
339                values.len(),
340                keep.len()
341            ),
342        }
343    }
344}
345
346/// The pending-input view a batch hook reports to its test-side handle (see
347/// [`ScriptableHook::status`]), used by `pause_until_*` predicates.
348#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
349pub struct BatchStatus {
350    /// The number of buffered elements.
351    pub buffered: usize,
352}
353
354/// `Ok(false)` while the prefix has not fully arrived yet.
355fn ordered_prefix_honorable<T: PartialEq>(
356    input: &VecDeque<T>,
357    values: &[T],
358    method: &str,
359) -> Result<bool, String> {
360    if let Some(idx) = input
361        .iter()
362        .zip(values)
363        .position(|(buffered, expected)| buffered != expected)
364    {
365        Err(format!(
366            "{}: buffered item at prefix position {} did not match the expected value",
367            method, idx
368        ))
369    } else {
370        Ok(input.len() >= values.len())
371    }
372}
373
374fn multiset_included<'a, T: PartialEq + 'a>(
375    requested: &[T],
376    available: impl Iterator<Item = &'a T>,
377) -> bool {
378    let mut unmatched: Vec<&T> = requested.iter().collect();
379    for item in available {
380        if let Some(idx) = unmatched.iter().position(|r| *r == item) {
381            unmatched.swap_remove(idx);
382        }
383    }
384    unmatched.is_empty()
385}
386
387impl<T, R: BatchRetries<T>> ScriptableHook for StreamBatchHook<T, TotalOrder, R>
388where
389    T: serde::Serialize + serde::de::DeserializeOwned + PartialEq,
390{
391    type Decision = BatchDecision<T>;
392    type Status = BatchStatus;
393
394    fn is_honorable(&self, decision: &BatchDecision<T>) -> Result<bool, String> {
395        let input = self.input.borrow();
396        match decision {
397            BatchDecision::Prefix(n) => Ok(input.len() >= *n),
398            BatchDecision::Values(values) => {
399                ordered_prefix_honorable(&input, values, "release_values")
400            }
401            BatchDecision::All => Ok(true),
402            BatchDecision::PrefixKeepLast(n) => {
403                check_keep_allowed::<R>("release_keep_last")?;
404                if *n == 0 {
405                    return Err(
406                        "release_keep_last: at least one element must be released to keep its last"
407                            .to_owned(),
408                    );
409                }
410                Ok(input.len() >= *n)
411            }
412            BatchDecision::ValuesKeepLast(values) => {
413                check_keep_allowed::<R>("release_values_keep_last")?;
414                if values.is_empty() {
415                    return Err(
416                        "release_values_keep_last: at least one value must be released to keep its last"
417                            .to_owned(),
418                    );
419                }
420                ordered_prefix_honorable(&input, values, "release_values_keep_last")
421            }
422        }
423    }
424
425    fn apply(&mut self, decision: BatchDecision<T>) {
426        let mut input = self.input.borrow_mut();
427        let keep_last = matches!(
428            decision,
429            BatchDecision::PrefixKeepLast(_) | BatchDecision::ValuesKeepLast(_)
430        );
431        let count = match decision {
432            BatchDecision::Prefix(n) | BatchDecision::PrefixKeepLast(n) => n,
433            BatchDecision::Values(values) | BatchDecision::ValuesKeepLast(values) => values.len(),
434            BatchDecision::All => input.len(),
435        };
436        let mut out: Vec<T> = input.drain(0..count.saturating_sub(1)).collect();
437        if count > 0 {
438            if keep_last {
439                out.push(R::scripted_keep(input.front().unwrap()));
440                self.kept_in_release = 1;
441            } else {
442                out.push(input.pop_front().unwrap());
443            }
444        }
445        self.to_release = Some(out);
446    }
447
448    fn implicit(&mut self) {
449        self.to_release = Some(vec![]);
450    }
451
452    fn status(&self) -> BatchStatus {
453        BatchStatus {
454            buffered: self.input.borrow().len(),
455        }
456    }
457
458    fn describe_pending(&self) -> Option<String> {
459        let input = self.input.borrow();
460        (!input.is_empty()).then(|| {
461            format!(
462                "{} buffered item(s): {:?}",
463                input.len(),
464                TruncatedVecDebug(RefCell::new(Some(input.iter())), 8, self.format_item_debug)
465            )
466        })
467    }
468}
469
470impl<T, R: BatchRetries<T>> ScriptableTickInputHook for StreamBatchHook<T, TotalOrder, R>
471where
472    T: serde::Serialize + serde::de::DeserializeOwned + PartialEq,
473{
474    fn decision_triggers_tick(&self, decision: &BatchDecision<T>) -> bool {
475        match decision {
476            BatchDecision::Prefix(n) | BatchDecision::PrefixKeepLast(n) => *n > 0,
477            BatchDecision::Values(values) | BatchDecision::ValuesKeepLast(values) => {
478                !values.is_empty()
479            }
480            BatchDecision::All => !self.input.borrow().is_empty(),
481        }
482    }
483}
484
485impl<T, R: BatchRetries<T>> ScriptableHook for StreamBatchHook<T, NoOrder, R>
486where
487    T: serde::Serialize + serde::de::DeserializeOwned + PartialEq,
488{
489    type Decision = UnorderedBatchDecision<T>;
490    type Status = BatchStatus;
491
492    fn is_honorable(&self, decision: &UnorderedBatchDecision<T>) -> Result<bool, String> {
493        match decision {
494            UnorderedBatchDecision::Values(values) => {
495                Ok(multiset_included(values, self.input.borrow().iter()))
496            }
497            UnorderedBatchDecision::All => Ok(true),
498            UnorderedBatchDecision::ValuesKeep(values, keep) => {
499                check_keep_allowed::<R>("release_values_keep")?;
500                if !multiset_included(keep, values.iter()) {
501                    return Err(
502                        "release_values_keep: every kept value must be among the released values"
503                            .to_owned(),
504                    );
505                }
506                Ok(multiset_included(values, self.input.borrow().iter()))
507            }
508        }
509    }
510
511    fn apply(&mut self, decision: UnorderedBatchDecision<T>) {
512        let mut input = self.input.borrow_mut();
513        let (mut values, mut keep) = match decision {
514            UnorderedBatchDecision::All => {
515                self.to_release = Some(input.drain(..).collect());
516                return;
517            }
518            UnorderedBatchDecision::Values(values) => (values, vec![]),
519            UnorderedBatchDecision::ValuesKeep(values, keep) => (values, keep),
520        };
521
522        // a matched element that is also in `keep` is copied and left in the buffer
523        let mut out = vec![];
524        let mut remaining = VecDeque::with_capacity(input.len());
525        let mut kept = 0;
526        for buffered in input.drain(..) {
527            if let Some(idx) = values.iter().position(|requested| *requested == buffered) {
528                values.swap_remove(idx);
529                if let Some(keep_idx) = keep.iter().position(|k| *k == buffered) {
530                    keep.swap_remove(keep_idx);
531                    kept += 1;
532                    out.push(R::scripted_keep(&buffered));
533                    remaining.push_back(buffered);
534                } else {
535                    out.push(buffered);
536                }
537            } else {
538                remaining.push_back(buffered);
539            }
540        }
541        if !(values.is_empty() && keep.is_empty()) {
542            abort!("scripted unordered batch decision was not honorable");
543        }
544        *input = remaining;
545        self.kept_in_release = kept;
546        self.to_release = Some(out);
547    }
548
549    fn implicit(&mut self) {
550        self.to_release = Some(vec![]);
551    }
552
553    fn status(&self) -> BatchStatus {
554        BatchStatus {
555            buffered: self.input.borrow().len(),
556        }
557    }
558
559    fn describe_pending(&self) -> Option<String> {
560        let input = self.input.borrow();
561        (!input.is_empty()).then(|| {
562            format!(
563                "{} buffered item(s): {:?}",
564                input.len(),
565                TruncatedVecDebug(RefCell::new(Some(input.iter())), 8, self.format_item_debug)
566            )
567        })
568    }
569}
570
571impl<T, R: BatchRetries<T>> ScriptableTickInputHook for StreamBatchHook<T, NoOrder, R>
572where
573    T: serde::Serialize + serde::de::DeserializeOwned + PartialEq,
574{
575    fn decision_triggers_tick(&self, decision: &UnorderedBatchDecision<T>) -> bool {
576        match decision {
577            UnorderedBatchDecision::Values(values)
578            | UnorderedBatchDecision::ValuesKeep(values, _) => !values.is_empty(),
579            UnorderedBatchDecision::All => !self.input.borrow().is_empty(),
580        }
581    }
582}
583
584/// Keyed version of [`StreamBatchHook`], with keeping applied per key.
585pub struct KeyedStreamBatchHook<K: Hash + Eq + Clone, V, Order: Ordering, R: Retries> {
586    input: Rc<RefCell<FxHashMap<K, VecDeque<V>>>>, // FxHasher is deterministic
587    to_release: Option<Vec<(K, V)>>,
588    /// Only used for logging.
589    kept_in_release: usize,
590    /// Unused for exactly-once streams and when scripted.
591    budget: RetryBudget,
592    output: Sender<(K, V)>,
593    batch_location: HookLocationMeta,
594    format_item_debug: fn(&(K, V)) -> Option<String>,
595    _marker: PhantomData<(Order, R)>,
596}
597
598impl<K: Hash + Eq + Clone, V, Order: Ordering> KeyedStreamBatchHook<K, V, Order, ExactlyOnce> {
599    pub fn new(
600        input: Rc<RefCell<FxHashMap<K, VecDeque<V>>>>,
601        output: Sender<(K, V)>,
602        batch_location: HookLocationMeta,
603        format_item_debug: fn(&(K, V)) -> Option<String>,
604    ) -> Self {
605        Self {
606            input,
607            to_release: None,
608            kept_in_release: 0,
609            budget: RetryBudget::Bounded(0),
610            output,
611            batch_location,
612            format_item_debug,
613            _marker: PhantomData,
614        }
615    }
616}
617
618impl<K: Hash + Eq + Clone, V, Order: Ordering> KeyedStreamBatchHook<K, V, Order, AtLeastOnce> {
619    pub fn new(
620        input: Rc<RefCell<FxHashMap<K, VecDeque<V>>>>,
621        output: Sender<(K, V)>,
622        batch_location: HookLocationMeta,
623        format_item_debug: fn(&(K, V)) -> Option<String>,
624        budget: RetryBudget,
625    ) -> Self {
626        Self {
627            input,
628            to_release: None,
629            kept_in_release: 0,
630            budget,
631            output,
632            batch_location,
633            format_item_debug,
634            _marker: PhantomData,
635        }
636    }
637}
638
639impl<K: Hash + Eq + Clone, V, Order: Ordering, R: Retries> RuntimeHook
640    for KeyedStreamBatchHook<K, V, Order, R>
641{
642    fn has_pending_input(&self) -> bool {
643        keyed_buffer_len(&self.input.borrow()) > 0
644    }
645
646    fn only_one_possible_decision(&self) -> bool {
647        // One buffered element is still a real choice: release it or not.
648        keyed_buffer_len(&self.input.borrow()) == 0
649    }
650
651    fn release_decision(&mut self, log_writer: Option<&mut dyn std::fmt::Write>) {
652        release_batch(
653            self.to_release.take(),
654            std::mem::take(&mut self.kept_in_release),
655            order_label::<Order>(),
656            self.batch_location,
657            self.format_item_debug,
658            &self.output,
659            log_writer,
660        );
661    }
662
663    fn location_meta(&self) -> HookLocationMeta {
664        self.batch_location
665    }
666}
667
668impl<K: Hash + Eq + Clone, V, R: BatchRetries<V>> TickInputHook
669    for KeyedStreamBatchHook<K, V, TotalOrder, R>
670{
671    fn can_trigger_tick(&self) -> bool {
672        keyed_buffer_len(&self.input.borrow()) > 0
673    }
674
675    fn autonomous_decision<'a>(
676        &mut self,
677        driver: &mut Borrowed<'a>,
678        mut force_trigger: bool,
679    ) -> bool {
680        let mut current_input = self.input.borrow_mut();
681        let mut out = vec![];
682        let mut kept = 0;
683        #[expect(clippy::disallowed_methods, reason = "FxHasher is deterministic")]
684        let nonempty_key_count = current_input.values().filter(|q| !q.is_empty()).count();
685
686        let mut remaining_nonempty_keys = nonempty_key_count;
687        #[expect(clippy::disallowed_methods, reason = "FxHasher is deterministic")]
688        for (key, queue) in current_input.iter_mut() {
689            if queue.is_empty() {
690                continue;
691            }
692
693            remaining_nonempty_keys -= 1;
694
695            let must_reveal = force_trigger && remaining_nonempty_keys == 0;
696            let count = (usize::from(must_reveal)..=queue.len())
697                .generate(driver)
698                .unwrap();
699
700            out.extend(
701                queue
702                    .drain(0..count.saturating_sub(1))
703                    .map(|v| (key.clone(), v)),
704            );
705            if count > 0 {
706                match R::autonomous_keep(&mut self.budget, queue.front().unwrap(), driver) {
707                    Some(copy) => {
708                        out.push((key.clone(), copy));
709                        kept += 1;
710                    }
711                    None => out.push((key.clone(), queue.pop_front().unwrap())),
712                }
713                force_trigger = false;
714            }
715        }
716
717        self.kept_in_release = kept;
718        let triggered = !out.is_empty();
719        self.to_release = Some(out);
720        triggered
721    }
722}
723
724impl<K: Hash + Eq + Clone, V, R: BatchRetries<V>> TickInputHook
725    for KeyedStreamBatchHook<K, V, NoOrder, R>
726{
727    fn can_trigger_tick(&self) -> bool {
728        keyed_buffer_len(&self.input.borrow()) > 0
729    }
730
731    fn autonomous_decision<'a>(
732        &mut self,
733        driver: &mut Borrowed<'a>,
734        mut force_trigger: bool,
735    ) -> bool {
736        let mut current_input = self.input.borrow_mut();
737        let mut out = vec![];
738        let mut kept = 0;
739        #[expect(clippy::disallowed_methods, reason = "FxHasher is deterministic")]
740        let nonempty_key_count = current_input.values().filter(|q| !q.is_empty()).count();
741
742        let mut remaining_nonempty_keys = nonempty_key_count;
743        #[expect(clippy::disallowed_methods, reason = "FxHasher is deterministic")]
744        for (key, queue) in current_input.iter_mut() {
745            if queue.is_empty() {
746                continue;
747            }
748
749            remaining_nonempty_keys -= 1;
750
751            // same per-key subset enumeration as `StreamBatchHook<T, NoOrder, R>`
752            let mut min_index = 0;
753            while min_index < queue.len() {
754                let must_release = force_trigger && remaining_nonempty_keys == 0;
755                if !must_release && produce().generate(driver).unwrap() {
756                    break;
757                }
758
759                let idx = (min_index..queue.len()).generate(driver).unwrap();
760                if let Some(copy) = R::autonomous_keep(&mut self.budget, &queue[idx], driver) {
761                    out.push((key.clone(), copy));
762                    kept += 1;
763                    min_index = idx + 1;
764                } else {
765                    out.push((key.clone(), queue.remove(idx).unwrap()));
766                    min_index = idx;
767                }
768                force_trigger = false;
769            }
770        }
771
772        self.kept_in_release = kept;
773        let triggered = !out.is_empty();
774        self.to_release = Some(out);
775        triggered
776    }
777}
778
779/// A scripted decision for a keyed batch hook over totally ordered values. Named values
780/// are matched against each key's buffered prefix in order. The `KeepLast` forms are only
781/// valid for `AtLeastOnce` values.
782///
783/// Per-key payloads are `Vec`s rather than maps: the scripted entry order is preserved
784/// (map iteration would make the release and log order nondeterministic), and the
785/// handle rejects duplicate keys in [`Self::Prefixes`] when the decision is created, so
786/// key distinctness is an invariant rather than a map-enforced property.
787#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
788pub enum KeyedBatchDecision<K, V> {
789    /// Release the next `n` buffered values of each named key. Keys are distinct
790    /// (enforced by the handle when the decision is created).
791    Prefixes(Vec<(K, usize)>),
792    /// Release exactly these `(key, value)` entries.
793    Values(Vec<(K, V)>),
794    /// Release everything that has arrived by the time the tick fires.
795    All,
796    /// Like [`Self::Prefixes`], but each key's last released value stays buffered.
797    PrefixesKeepLast(Vec<(K, usize)>),
798    /// Like [`Self::Values`], but each key's last released value stays buffered.
799    ValuesKeepLast(Vec<(K, V)>),
800}
801
802impl<K, V> ScriptDecision for KeyedBatchDecision<K, V>
803where
804    K: serde::Serialize + serde::de::DeserializeOwned,
805    V: serde::Serialize + serde::de::DeserializeOwned,
806{
807    fn describe(&self) -> String {
808        match self {
809            KeyedBatchDecision::Prefixes(counts) => {
810                format!("release({} per-key count(s))", counts.len())
811            }
812            KeyedBatchDecision::Values(values) => {
813                format!("release_values({} entr(ies))", values.len())
814            }
815            KeyedBatchDecision::All => "release_all()".to_owned(),
816            KeyedBatchDecision::PrefixesKeepLast(counts) => {
817                format!("release_keep_last({} per-key count(s))", counts.len())
818            }
819            KeyedBatchDecision::ValuesKeepLast(values) => {
820                format!("release_values_keep_last({} entr(ies))", values.len())
821            }
822        }
823    }
824}
825
826/// A scripted decision for a keyed batch hook over unordered values. Named values are
827/// matched per key as multisets. `ValuesKeep` is only valid for `AtLeastOnce` values.
828#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
829pub enum UnorderedKeyedBatchDecision<K, V> {
830    /// Release exactly these `(key, value)` entries.
831    Values(Vec<(K, V)>),
832    /// Release everything that has arrived by the time the tick fires.
833    All,
834    /// Like [`Self::Values`], but the entries matching the second list (a subset of the
835    /// first) stay buffered.
836    ValuesKeep(Vec<(K, V)>, Vec<(K, V)>),
837}
838
839impl<K, V> ScriptDecision for UnorderedKeyedBatchDecision<K, V>
840where
841    K: serde::Serialize + serde::de::DeserializeOwned,
842    V: serde::Serialize + serde::de::DeserializeOwned,
843{
844    fn describe(&self) -> String {
845        match self {
846            UnorderedKeyedBatchDecision::Values(values) => {
847                format!("release_values({} entr(ies))", values.len())
848            }
849            UnorderedKeyedBatchDecision::All => "release_all()".to_owned(),
850            UnorderedKeyedBatchDecision::ValuesKeep(values, keep) => format!(
851                "release_values_keep({} entr(ies), {} kept)",
852                values.len(),
853                keep.len()
854            ),
855        }
856    }
857}
858
859fn keyed_prefixes_honorable<K: Hash + Eq, V>(
860    input: &FxHashMap<K, VecDeque<V>>,
861    counts: &[(K, usize)],
862) -> bool {
863    counts
864        .iter()
865        .all(|(key, count)| input.get(key).is_some_and(|queue| queue.len() >= *count))
866}
867
868/// Each key's values must match that key's buffered prefix; the interleaving of keys is
869/// irrelevant. `Ok(false)` while some prefix has not fully arrived yet.
870fn keyed_values_honorable<K: Hash + Eq, V: PartialEq>(
871    input: &FxHashMap<K, VecDeque<V>>,
872    values: &[(K, V)],
873    method: &str,
874) -> Result<bool, String> {
875    let mut consumed: FxHashMap<&K, usize> = FxHashMap::default();
876    for (position, (key, expected)) in values.iter().enumerate() {
877        let offset = consumed.entry(key).or_insert(0);
878        match input.get(key).and_then(|queue| queue.get(*offset)) {
879            Some(buffered) if buffered == expected => {}
880            Some(_) => {
881                return Err(format!(
882                    "{}: buffered item at per-key prefix position {} did not match the expected value (scripted entry {})",
883                    method, *offset, position
884                ));
885            }
886            None => return Ok(false),
887        }
888        *offset += 1;
889    }
890    Ok(true)
891}
892
893fn keyed_multiset_included<'a, K: Hash + Eq + 'a, V: PartialEq + 'a>(
894    requested: &[(K, V)],
895    available: impl Iterator<Item = (&'a K, &'a V)>,
896) -> bool {
897    let mut unmatched: Vec<(&K, &V)> = requested.iter().map(|(k, v)| (k, v)).collect();
898    for (key, value) in available {
899        if let Some(idx) = unmatched.iter().position(|(k, v)| *k == key && *v == value) {
900            unmatched.swap_remove(idx);
901        }
902    }
903    unmatched.is_empty()
904}
905
906fn drain_all_keyed<K: Clone, V>(input: &mut FxHashMap<K, VecDeque<V>>) -> Vec<(K, V)> {
907    let mut out = vec![];
908    #[expect(clippy::disallowed_methods, reason = "FxHasher is deterministic")]
909    for (key, queue) in input.iter_mut() {
910        out.extend(queue.drain(..).map(|v| (key.clone(), v)));
911    }
912    out
913}
914
915impl<K, V, R: BatchRetries<V>> ScriptableHook for KeyedStreamBatchHook<K, V, TotalOrder, R>
916where
917    K: Hash + Eq + Clone + serde::Serialize + serde::de::DeserializeOwned,
918    V: serde::Serialize + serde::de::DeserializeOwned + PartialEq,
919{
920    type Decision = KeyedBatchDecision<K, V>;
921    type Status = BatchStatus;
922
923    fn is_honorable(&self, decision: &KeyedBatchDecision<K, V>) -> Result<bool, String> {
924        let input = self.input.borrow();
925        match decision {
926            KeyedBatchDecision::Prefixes(counts) => Ok(keyed_prefixes_honorable(&input, counts)),
927            KeyedBatchDecision::Values(values) => {
928                keyed_values_honorable(&input, values, "release_values")
929            }
930            KeyedBatchDecision::All => Ok(true),
931            KeyedBatchDecision::PrefixesKeepLast(counts) => {
932                check_keep_allowed::<R>("release_keep_last")?;
933                if counts.iter().any(|(_, count)| *count == 0) {
934                    return Err(
935                        "release_keep_last: every named key must release at least one value to keep its last"
936                            .to_owned(),
937                    );
938                }
939                Ok(keyed_prefixes_honorable(&input, counts))
940            }
941            KeyedBatchDecision::ValuesKeepLast(values) => {
942                check_keep_allowed::<R>("release_values_keep_last")?;
943                if values.is_empty() {
944                    return Err(
945                        "release_values_keep_last: at least one entry must be released to keep its last"
946                            .to_owned(),
947                    );
948                }
949                keyed_values_honorable(&input, values, "release_values_keep_last")
950            }
951        }
952    }
953
954    fn apply(&mut self, decision: KeyedBatchDecision<K, V>) {
955        let mut input = self.input.borrow_mut();
956        let keep_last = matches!(
957            decision,
958            KeyedBatchDecision::PrefixesKeepLast(_) | KeyedBatchDecision::ValuesKeepLast(_)
959        );
960        let mut kept = 0;
961        let out: Vec<(K, V)> = match decision {
962            KeyedBatchDecision::Prefixes(counts) | KeyedBatchDecision::PrefixesKeepLast(counts) => {
963                let mut out = vec![];
964                for (key, count) in counts {
965                    let queue = input.get_mut(&key).unwrap();
966                    out.extend(
967                        queue
968                            .drain(0..count.saturating_sub(1))
969                            .map(|v| (key.clone(), v)),
970                    );
971                    if count > 0 {
972                        if keep_last {
973                            out.push((key.clone(), R::scripted_keep(queue.front().unwrap())));
974                            kept += 1;
975                        } else {
976                            out.push((key.clone(), queue.pop_front().unwrap()));
977                        }
978                    }
979                }
980                out
981            }
982            KeyedBatchDecision::Values(values) | KeyedBatchDecision::ValuesKeepLast(values) => {
983                // `is_honorable` checked that each key's values are its buffered prefix,
984                // so popping fronts releases exactly them. when keeping, the key's last
985                // value is copied instead of popped.
986                let mut remaining_per_key: FxHashMap<&K, usize> = FxHashMap::default();
987                if keep_last {
988                    for (key, _) in &values {
989                        *remaining_per_key.entry(key).or_insert(0) += 1;
990                    }
991                }
992                let mut out = Vec::with_capacity(values.len());
993                for (key, _expected) in &values {
994                    let queue = input.get_mut(key).unwrap();
995                    let is_kept_last = keep_last && {
996                        let remaining = remaining_per_key.get_mut(key).unwrap();
997                        *remaining -= 1;
998                        *remaining == 0
999                    };
1000                    if is_kept_last {
1001                        out.push((key.clone(), R::scripted_keep(queue.front().unwrap())));
1002                        kept += 1;
1003                    } else {
1004                        out.push((key.clone(), queue.pop_front().unwrap()));
1005                    }
1006                }
1007                out
1008            }
1009            KeyedBatchDecision::All => drain_all_keyed(&mut input),
1010        };
1011
1012        self.kept_in_release = kept;
1013        self.to_release = Some(out);
1014    }
1015
1016    fn implicit(&mut self) {
1017        self.to_release = Some(vec![]);
1018    }
1019
1020    fn status(&self) -> BatchStatus {
1021        BatchStatus {
1022            buffered: keyed_buffer_len(&self.input.borrow()),
1023        }
1024    }
1025
1026    fn describe_pending(&self) -> Option<String> {
1027        describe_keyed_pending(&self.input.borrow())
1028    }
1029}
1030
1031impl<K, V, R: BatchRetries<V>> ScriptableTickInputHook for KeyedStreamBatchHook<K, V, TotalOrder, R>
1032where
1033    K: Hash + Eq + Clone + serde::Serialize + serde::de::DeserializeOwned,
1034    V: serde::Serialize + serde::de::DeserializeOwned + PartialEq,
1035{
1036    fn decision_triggers_tick(&self, decision: &KeyedBatchDecision<K, V>) -> bool {
1037        match decision {
1038            KeyedBatchDecision::Prefixes(counts) | KeyedBatchDecision::PrefixesKeepLast(counts) => {
1039                counts.iter().any(|(_, count)| *count > 0)
1040            }
1041            KeyedBatchDecision::Values(values) | KeyedBatchDecision::ValuesKeepLast(values) => {
1042                !values.is_empty()
1043            }
1044            KeyedBatchDecision::All => keyed_buffer_len(&self.input.borrow()) > 0,
1045        }
1046    }
1047}
1048
1049impl<K, V, R: BatchRetries<V>> ScriptableHook for KeyedStreamBatchHook<K, V, NoOrder, R>
1050where
1051    K: Hash + Eq + Clone + serde::Serialize + serde::de::DeserializeOwned,
1052    V: serde::Serialize + serde::de::DeserializeOwned + PartialEq,
1053{
1054    type Decision = UnorderedKeyedBatchDecision<K, V>;
1055    type Status = BatchStatus;
1056
1057    fn is_honorable(&self, decision: &UnorderedKeyedBatchDecision<K, V>) -> Result<bool, String> {
1058        let input = self.input.borrow();
1059        #[expect(clippy::disallowed_methods, reason = "FxHasher is deterministic")]
1060        let buffered = || {
1061            input
1062                .iter()
1063                .flat_map(|(key, queue)| queue.iter().map(move |value| (key, value)))
1064        };
1065        match decision {
1066            UnorderedKeyedBatchDecision::Values(values) => {
1067                Ok(keyed_multiset_included(values, buffered()))
1068            }
1069            UnorderedKeyedBatchDecision::All => Ok(true),
1070            UnorderedKeyedBatchDecision::ValuesKeep(values, keep) => {
1071                check_keep_allowed::<R>("release_values_keep")?;
1072                if !keyed_multiset_included(keep, values.iter().map(|(k, v)| (k, v))) {
1073                    return Err(
1074                        "release_values_keep: every kept entry must be among the released entries"
1075                            .to_owned(),
1076                    );
1077                }
1078                Ok(keyed_multiset_included(values, buffered()))
1079            }
1080        }
1081    }
1082
1083    fn apply(&mut self, decision: UnorderedKeyedBatchDecision<K, V>) {
1084        let mut input = self.input.borrow_mut();
1085        let (values, mut keep) = match decision {
1086            UnorderedKeyedBatchDecision::All => {
1087                self.to_release = Some(drain_all_keyed(&mut input));
1088                return;
1089            }
1090            UnorderedKeyedBatchDecision::Values(values) => (values, vec![]),
1091            UnorderedKeyedBatchDecision::ValuesKeep(values, keep) => (values, keep),
1092        };
1093
1094        // a matched entry that is also in `keep` is copied and left in the buffer
1095        let mut kept = 0;
1096        let mut out = Vec::with_capacity(values.len());
1097        for (key, expected) in values {
1098            let queue = input.get_mut(&key).unwrap();
1099            let idx = queue.iter().position(|item| *item == expected).unwrap();
1100            if let Some(keep_idx) = keep.iter().position(|(k, v)| *k == key && *v == expected) {
1101                keep.swap_remove(keep_idx);
1102                kept += 1;
1103                out.push((key, R::scripted_keep(&queue[idx])));
1104            } else {
1105                out.push((key, queue.remove(idx).unwrap()));
1106            }
1107        }
1108        if !keep.is_empty() {
1109            abort!("scripted unordered keyed batch decision was not honorable");
1110        }
1111
1112        self.kept_in_release = kept;
1113        self.to_release = Some(out);
1114    }
1115
1116    fn implicit(&mut self) {
1117        self.to_release = Some(vec![]);
1118    }
1119
1120    fn status(&self) -> BatchStatus {
1121        BatchStatus {
1122            buffered: keyed_buffer_len(&self.input.borrow()),
1123        }
1124    }
1125
1126    fn describe_pending(&self) -> Option<String> {
1127        describe_keyed_pending(&self.input.borrow())
1128    }
1129}
1130
1131impl<K, V, R: BatchRetries<V>> ScriptableTickInputHook for KeyedStreamBatchHook<K, V, NoOrder, R>
1132where
1133    K: Hash + Eq + Clone + serde::Serialize + serde::de::DeserializeOwned,
1134    V: serde::Serialize + serde::de::DeserializeOwned + PartialEq,
1135{
1136    fn decision_triggers_tick(&self, decision: &UnorderedKeyedBatchDecision<K, V>) -> bool {
1137        match decision {
1138            UnorderedKeyedBatchDecision::Values(values)
1139            | UnorderedKeyedBatchDecision::ValuesKeep(values, _) => !values.is_empty(),
1140            UnorderedKeyedBatchDecision::All => keyed_buffer_len(&self.input.borrow()) > 0,
1141        }
1142    }
1143}
1144
1145pub struct SingletonHook<T> {
1146    input: Rc<RefCell<VecDeque<T>>>,
1147    /// `Some(None)` releases an empty snapshot: the tick fired before the singleton had any
1148    /// version (snapshot ingress is lazy, so this is possible), and, like production's
1149    /// `snapshot()`, nothing is delivered.
1150    to_release: Option<Option<(T, bool)>>, // (data, is new)
1151    last_released: Option<T>,
1152    skipped_states: Vec<T>,
1153    output: Sender<T>,
1154    batch_location: HookLocationMeta,
1155    format_item_debug: fn(&T) -> Option<String>,
1156}
1157
1158impl<T: Clone> SingletonHook<T> {
1159    pub fn new(
1160        input: Rc<RefCell<VecDeque<T>>>,
1161        output: Sender<T>,
1162        batch_location: HookLocationMeta,
1163        format_item_debug: fn(&T) -> Option<String>,
1164    ) -> Self {
1165        Self {
1166            input,
1167            to_release: None,
1168            last_released: None,
1169            skipped_states: vec![],
1170            output,
1171            batch_location,
1172            format_item_debug,
1173        }
1174    }
1175}
1176
1177impl<T: Clone> RuntimeHook for SingletonHook<T> {
1178    fn has_pending_input(&self) -> bool {
1179        !self.input.borrow().is_empty()
1180    }
1181
1182    fn only_one_possible_decision(&self) -> bool {
1183        // With no previously revealed value, a sole buffered version has exactly one
1184        // resolution: reveal it (there is nothing to keep). Once a value has been
1185        // revealed, any buffered version is a real choice (keep vs reveal); with two or
1186        // more buffered versions the choice of which to reveal is real either way.
1187        let input = self.input.borrow();
1188        input.is_empty() || (input.len() == 1 && self.last_released.is_none())
1189    }
1190
1191    fn release_decision(&mut self, log_writer: Option<&mut dyn std::fmt::Write>) {
1192        if matches!(self.to_release, Some(None)) {
1193            self.to_release = None;
1194            if let Some(log_writer) = log_writer {
1195                let HookLocationMeta {
1196                    location: batch_location,
1197                    line,
1198                    caret_indent,
1199                } = self.batch_location;
1200                log_release(
1201                    log_writer,
1202                    batch_location,
1203                    line,
1204                    caret_indent,
1205                    "^ releasing empty snapshot (no version yet)",
1206                    colored::Color::Green,
1207                );
1208            }
1209            return;
1210        }
1211
1212        if let Some(Some((to_release, is_new))) = self.to_release.take() {
1213            self.last_released = Some(to_release.clone());
1214
1215            if let Some(log_writer) = log_writer {
1216                let HookLocationMeta {
1217                    location: batch_location,
1218                    line,
1219                    caret_indent,
1220                } = self.batch_location;
1221                let note_str = if self.skipped_states.is_empty() {
1222                    if is_new {
1223                        format!(
1224                            "^ releasing snapshot: {:?}",
1225                            ManualDebug(&to_release, self.format_item_debug)
1226                        )
1227                    } else {
1228                        format!(
1229                            "^ releasing unchanged snapshot: {:?}",
1230                            ManualDebug(&to_release, self.format_item_debug)
1231                        )
1232                    }
1233                } else {
1234                    format!(
1235                        "^ releasing snapshot: {:?} (skipping earlier states: {:?})",
1236                        ManualDebug(&to_release, self.format_item_debug),
1237                        self.skipped_states
1238                            .iter()
1239                            .map(|s| ManualDebug(s, self.format_item_debug))
1240                            .collect::<Vec<_>>()
1241                    )
1242                };
1243
1244                log_release(
1245                    log_writer,
1246                    batch_location,
1247                    line,
1248                    caret_indent,
1249                    &note_str,
1250                    colored::Color::Green,
1251                );
1252            }
1253
1254            self.output.try_send(to_release).unwrap();
1255        } else {
1256            panic!("No decision to release");
1257        }
1258    }
1259
1260    fn location_meta(&self) -> HookLocationMeta {
1261        self.batch_location
1262    }
1263}
1264
1265impl<T: Clone> TickInputHook for SingletonHook<T> {
1266    fn can_trigger_tick(&self) -> bool {
1267        // Snapshot ingress is lazy: a new buffered version never wakes the tick on its
1268        // own. It is only revealed when the tick runs for some other reason.
1269        false
1270    }
1271
1272    fn autonomous_decision<'a>(&mut self, driver: &mut Borrowed<'a>, force_trigger: bool) -> bool {
1273        assert!(
1274            !force_trigger,
1275            "Snapshot hooks never trigger a tick, so they must not be forced to"
1276        );
1277
1278        let mut current_input = self.input.borrow_mut();
1279        if current_input.is_empty() {
1280            if let Some(last) = &self.last_released {
1281                // Re-release the last item
1282                self.to_release = Some(Some((last.clone(), false)));
1283            } else {
1284                // No version yet: the snapshot is empty.
1285                self.to_release = Some(None);
1286            }
1287        } else if let Some(last) = &self.last_released
1288            && produce().generate(driver).unwrap()
1289        {
1290            // Re-release the last item
1291            self.to_release = Some(Some((last.clone(), false)));
1292        } else {
1293            // Release a new item
1294            let idx_to_release = (0..current_input.len()).generate(driver).unwrap();
1295            self.skipped_states = current_input.drain(0..idx_to_release).collect(); // Drop earlier items
1296            let item = current_input.pop_front().unwrap();
1297            self.to_release = Some(Some((item, true)));
1298        }
1299        // Revealing a new version is lazy: it never counts as triggering the tick.
1300        false
1301    }
1302}
1303
1304/// A hook for batching / snapshotting an [`Optional`](crate::live_collections::Optional) with
1305/// `InitNone` boundedness into a tick.
1306///
1307/// This is the [`SingletonHook`] analog for optionals whose *presence* is monotone (the
1308/// `InitNone` bound): the optional starts null and, once it becomes non-null, stays non-null.
1309/// It differs from [`SingletonHook`] in that its released value is optional. Before the first
1310/// non-null value it releases *null* (sending nothing into the tick's `source_stream`, so the
1311/// downstream optional is empty). Once it has released a value, presence is monotone, so it only
1312/// ever re-releases or advances to a newer value — never back to null.
1313pub struct OptionalInitNoneHook<T> {
1314    input: Rc<RefCell<VecDeque<T>>>,
1315    to_release: Option<(Option<T>, bool)>, // (value or null, is new)
1316    last_released: Option<T>,              // last non-null value released (None until the first)
1317    skipped_states: Vec<T>,
1318    output: Sender<T>,
1319    batch_location: HookLocationMeta,
1320    format_item_debug: fn(&T) -> Option<String>,
1321}
1322
1323impl<T: Clone> OptionalInitNoneHook<T> {
1324    pub fn new(
1325        input: Rc<RefCell<VecDeque<T>>>,
1326        output: Sender<T>,
1327        batch_location: HookLocationMeta,
1328        format_item_debug: fn(&T) -> Option<String>,
1329    ) -> Self {
1330        Self {
1331            input,
1332            to_release: None,
1333            last_released: None,
1334            skipped_states: vec![],
1335            output,
1336            batch_location,
1337            format_item_debug,
1338        }
1339    }
1340}
1341
1342impl<T: Clone> RuntimeHook for OptionalInitNoneHook<T> {
1343    fn has_pending_input(&self) -> bool {
1344        !self.input.borrow().is_empty()
1345    }
1346
1347    fn only_one_possible_decision(&self) -> bool {
1348        // If there is no input, the decision is trivial.
1349        // Even if the input is a single item, we can always either take it or leave it, and
1350        // remain at the existing value (which may be `None`).
1351        self.input.borrow().is_empty()
1352    }
1353
1354    fn release_decision(&mut self, log_writer: Option<&mut dyn std::fmt::Write>) {
1355        let Some((to_release, is_new)) = self.to_release.take() else {
1356            panic!("No decision to release");
1357        };
1358
1359        if let Some(value) = &to_release {
1360            self.last_released = Some(value.clone());
1361        }
1362
1363        if let Some(log_writer) = log_writer {
1364            let HookLocationMeta {
1365                location: batch_location,
1366                line,
1367                caret_indent,
1368            } = self.batch_location;
1369            let note_str = match (&to_release, is_new) {
1370                (None, _) => "^ releasing null snapshot".to_owned(),
1371                (Some(value), true) => {
1372                    if self.skipped_states.is_empty() {
1373                        format!(
1374                            "^ releasing snapshot: {:?}",
1375                            ManualDebug(value, self.format_item_debug)
1376                        )
1377                    } else {
1378                        format!(
1379                            "^ releasing snapshot: {:?} (skipping earlier states: {:?})",
1380                            ManualDebug(value, self.format_item_debug),
1381                            self.skipped_states
1382                                .iter()
1383                                .map(|s| ManualDebug(s, self.format_item_debug))
1384                                .collect::<Vec<_>>()
1385                        )
1386                    }
1387                }
1388                (Some(value), false) => format!(
1389                    "^ releasing unchanged snapshot: {:?}",
1390                    ManualDebug(value, self.format_item_debug)
1391                ),
1392            };
1393
1394            log_release(
1395                log_writer,
1396                batch_location,
1397                line,
1398                caret_indent,
1399                &note_str,
1400                colored::Color::Green,
1401            );
1402        }
1403
1404        if let Some(value) = to_release {
1405            self.output.try_send(value).unwrap();
1406        }
1407    }
1408
1409    fn location_meta(&self) -> HookLocationMeta {
1410        self.batch_location
1411    }
1412}
1413
1414impl<T: Clone> TickInputHook for OptionalInitNoneHook<T> {
1415    fn can_trigger_tick(&self) -> bool {
1416        // Snapshot ingress is lazy: a new buffered version never wakes the tick on its
1417        // own. It is only revealed when the tick runs for some other reason.
1418        false
1419    }
1420
1421    fn autonomous_decision<'a>(&mut self, driver: &mut Borrowed<'a>, force_trigger: bool) -> bool {
1422        assert!(
1423            !force_trigger,
1424            "Snapshot hooks never trigger a tick, so they must not be forced to"
1425        );
1426
1427        let mut current_input = self.input.borrow_mut();
1428        if current_input.is_empty() {
1429            // Case 1 (trivial): No input.
1430            if let Some(last) = &self.last_released {
1431                // Presence is monotone: once non-null, re-release the latest value.
1432                self.to_release = Some((Some(last.clone()), false));
1433            } else {
1434                // Still in the initial-null prefix.
1435                self.to_release = Some((None, false));
1436            }
1437        } else if produce().generate(driver).unwrap() {
1438            // Case 2: Keep latest value (may be `Some` or `None`)
1439            if let Some(last) = &self.last_released {
1440                // Already non-null; re-release the latest value (models snapshot lag).
1441                self.to_release = Some((Some(last.clone()), false));
1442            } else {
1443                // Still in the initial-null prefix even though a value is buffered: models a
1444                // snapshot that does not yet include the first value.
1445                self.to_release = Some((None, false));
1446            }
1447        } else {
1448            // Case 3: Advance to new value.
1449            let idx_to_release = (0..current_input.len()).generate(driver).unwrap();
1450            self.skipped_states = current_input.drain(0..idx_to_release).collect(); // Drop earlier items
1451            let item = current_input.pop_front().unwrap();
1452            self.to_release = Some((Some(item), true));
1453        }
1454        // Revealing a new version is lazy: it never counts as triggering the tick.
1455        false
1456    }
1457}
1458
1459/// A scripted decision for a snapshot hook: which buffered version of the state the next
1460/// tick execution observes.
1461#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
1462pub enum SnapshotDecision<T> {
1463    /// Reveal the first buffered version equal to this value, skipping over earlier
1464    /// versions.
1465    Reveal(T),
1466    /// Advance to the next buffered version.
1467    RevealNext,
1468    /// Reveal the newest version that has arrived by the time the tick fires.
1469    RevealLatest,
1470    /// Observe the previously revealed version again.
1471    Keep,
1472}
1473
1474impl<T> ScriptDecision for SnapshotDecision<T>
1475where
1476    T: serde::Serialize + serde::de::DeserializeOwned,
1477{
1478    fn describe(&self) -> String {
1479        match self {
1480            SnapshotDecision::Reveal(_) => "reveal(..)".to_owned(),
1481            SnapshotDecision::RevealNext => "reveal_next()".to_owned(),
1482            SnapshotDecision::RevealLatest => "reveal_latest()".to_owned(),
1483            SnapshotDecision::Keep => "keep()".to_owned(),
1484        }
1485    }
1486}
1487
1488/// The pending-input view a snapshot hook reports to its test-side handle (see
1489/// [`ScriptableHook::status`]), used by `pause_until_*` predicates.
1490#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
1491pub struct SnapshotStatus {
1492    /// The number of buffered versions newer than the last revealed one.
1493    pub newer_versions: usize,
1494}
1495
1496impl<T: Clone + PartialEq + serde::Serialize + serde::de::DeserializeOwned> ScriptableHook
1497    for SingletonHook<T>
1498{
1499    type Decision = SnapshotDecision<T>;
1500    type Status = SnapshotStatus;
1501
1502    fn is_honorable(&self, decision: &SnapshotDecision<T>) -> Result<bool, String> {
1503        let input = self.input.borrow();
1504        Ok(match decision {
1505            SnapshotDecision::Reveal(target) => input.iter().any(|version| version == target),
1506            SnapshotDecision::RevealNext => !input.is_empty(),
1507            SnapshotDecision::RevealLatest => !input.is_empty() || self.last_released.is_some(),
1508            SnapshotDecision::Keep => self.last_released.is_some(),
1509        })
1510    }
1511
1512    fn apply(&mut self, decision: SnapshotDecision<T>) {
1513        match decision {
1514            SnapshotDecision::Reveal(target) => {
1515                let mut input = self.input.borrow_mut();
1516                let idx = input.iter().position(|version| *version == target).unwrap();
1517                self.skipped_states = input.drain(0..idx).collect();
1518                let item = input.pop_front().unwrap();
1519                self.to_release = Some(Some((item, true)));
1520            }
1521            SnapshotDecision::RevealNext => {
1522                let mut input = self.input.borrow_mut();
1523                self.skipped_states = vec![];
1524                let item = input.pop_front().unwrap();
1525                self.to_release = Some(Some((item, true)));
1526            }
1527            SnapshotDecision::RevealLatest => {
1528                let mut input = self.input.borrow_mut();
1529                if input.is_empty() {
1530                    self.skipped_states = vec![];
1531                    self.to_release = Some(Some((self.last_released.clone().unwrap(), false)));
1532                } else {
1533                    let skip_count = input.len() - 1;
1534                    self.skipped_states = input.drain(0..skip_count).collect();
1535                    let item = input.pop_front().unwrap();
1536                    self.to_release = Some(Some((item, true)));
1537                }
1538            }
1539            SnapshotDecision::Keep => {
1540                self.skipped_states = vec![];
1541                self.to_release = Some(Some((self.last_released.clone().unwrap(), false)));
1542            }
1543        }
1544    }
1545
1546    fn implicit(&mut self) {
1547        if let Some(last) = &self.last_released {
1548            self.skipped_states = vec![];
1549            self.to_release = Some(Some((last.clone(), false)));
1550        } else {
1551            // `is_ready()` prevents the tick from running before the singleton has a
1552            // value, so this is unreachable.
1553            abort!("scripted snapshot hook asked for implicit behavior with no revealed value");
1554        }
1555    }
1556
1557    fn status(&self) -> SnapshotStatus {
1558        SnapshotStatus {
1559            newer_versions: self.input.borrow().len(),
1560        }
1561    }
1562
1563    fn describe_pending(&self) -> Option<String> {
1564        let input = self.input.borrow();
1565        (!input.is_empty()).then(|| {
1566            format!(
1567                "{} buffered version(s): {:?}",
1568                input.len(),
1569                TruncatedVecDebug(RefCell::new(Some(input.iter())), 8, self.format_item_debug)
1570            )
1571        })
1572    }
1573}
1574
1575impl<T: Clone + PartialEq + serde::Serialize + serde::de::DeserializeOwned> ScriptableTickInputHook
1576    for SingletonHook<T>
1577{
1578    fn decision_triggers_tick(&self, decision: &SnapshotDecision<T>) -> bool {
1579        match decision {
1580            SnapshotDecision::Reveal(_) | SnapshotDecision::RevealNext => true,
1581            SnapshotDecision::RevealLatest => !self.input.borrow().is_empty(),
1582            SnapshotDecision::Keep => false,
1583        }
1584    }
1585}
1586/// A passthrough singleton hook for fold outputs that are already controlled by a
1587/// `TopLevelFoldHook`. Always releases the latest value without any non-deterministic
1588/// decisions, since the fold hook already made the only meaningful choice (which subset
1589/// of inputs to process).
1590pub struct PassthroughSingletonHook<T> {
1591    input: Rc<RefCell<VecDeque<T>>>,
1592    to_release: Option<T>,
1593    output: Sender<T>,
1594    batch_location: HookLocationMeta,
1595    format_item_debug: fn(&T) -> Option<String>,
1596}
1597
1598impl<T> PassthroughSingletonHook<T> {
1599    pub fn new(
1600        input: Rc<RefCell<VecDeque<T>>>,
1601        output: Sender<T>,
1602        batch_location: HookLocationMeta,
1603        format_item_debug: fn(&T) -> Option<String>,
1604    ) -> Self {
1605        Self {
1606            input,
1607            to_release: None,
1608            output,
1609            batch_location,
1610            format_item_debug,
1611        }
1612    }
1613}
1614
1615impl<T> RuntimeHook for PassthroughSingletonHook<T> {
1616    fn has_pending_input(&self) -> bool {
1617        !self.input.borrow().is_empty()
1618    }
1619
1620    fn only_one_possible_decision(&self) -> bool {
1621        // Releasing the latest value is the only behavior this hook ever has: the
1622        // controlling `TopLevelFoldHook` already made every meaningful choice, so even
1623        // with buffered input there is nothing non-deterministic left to decide. (This
1624        // hook is why the choice question is separate from `can_trigger_tick`.)
1625        true
1626    }
1627
1628    fn release_decision(&mut self, log_writer: Option<&mut dyn std::fmt::Write>) {
1629        if let Some(to_release) = self.to_release.take() {
1630            if let Some(log_writer) = log_writer {
1631                let HookLocationMeta {
1632                    location: batch_location,
1633                    line,
1634                    caret_indent,
1635                } = self.batch_location;
1636                let note_str = format!(
1637                    "^ releasing snapshot: {:?}",
1638                    ManualDebug(&to_release, self.format_item_debug)
1639                );
1640
1641                log_release(
1642                    log_writer,
1643                    batch_location,
1644                    line,
1645                    caret_indent,
1646                    &note_str,
1647                    colored::Color::Green,
1648                );
1649            }
1650
1651            self.output.try_send(to_release).unwrap();
1652        } else {
1653            panic!("No decision to release");
1654        }
1655    }
1656
1657    fn location_meta(&self) -> HookLocationMeta {
1658        self.batch_location
1659    }
1660}
1661
1662impl<T> TickInputHook for PassthroughSingletonHook<T> {
1663    fn can_trigger_tick(&self) -> bool {
1664        !self.input.borrow().is_empty()
1665    }
1666
1667    fn autonomous_decision<'a>(
1668        &mut self,
1669        _driver: &mut Borrowed<'a>,
1670        _force_trigger: bool,
1671    ) -> bool {
1672        let mut current_input = self.input.borrow_mut();
1673        // Always take the last (most recent) value, discard intermediates.
1674        if let Some(item) = current_input.pop_back() {
1675            current_input.clear();
1676            self.to_release = Some(item);
1677            true
1678        } else {
1679            false
1680        }
1681    }
1682}
1683
1684pub struct KeyedSingletonHook<K: Hash + Eq + Clone, V: Clone> {
1685    input: Rc<RefCell<FxHashMap<K, VecDeque<V>>>>, // FxHasher is deterministic
1686    to_release: Option<Vec<(K, V, bool)>>,         // (key, data, is new)
1687    last_released: FxHashMap<K, V>,
1688    skipped_states: FxHashMap<K, Vec<V>>,
1689    output: Sender<(K, V)>,
1690    batch_location: HookLocationMeta,
1691    format_key_debug: fn(&K) -> Option<String>,
1692    format_value_debug: fn(&V) -> Option<String>,
1693}
1694
1695impl<K: Hash + Eq + Clone, V: Clone> KeyedSingletonHook<K, V> {
1696    pub fn new(
1697        input: Rc<RefCell<FxHashMap<K, VecDeque<V>>>>,
1698        output: Sender<(K, V)>,
1699        batch_location: HookLocationMeta,
1700        format_key_debug: fn(&K) -> Option<String>,
1701        format_value_debug: fn(&V) -> Option<String>,
1702    ) -> Self {
1703        Self {
1704            input,
1705            to_release: None,
1706            last_released: FxHashMap::default(),
1707            skipped_states: FxHashMap::default(),
1708            output,
1709            batch_location,
1710            format_key_debug,
1711            format_value_debug,
1712        }
1713    }
1714}
1715
1716impl<K: Hash + Eq + Clone, V: Clone> RuntimeHook for KeyedSingletonHook<K, V> {
1717    fn has_pending_input(&self) -> bool {
1718        #[expect(clippy::disallowed_methods, reason = "FxHasher is deterministic")]
1719        !self.input.borrow().values().all(|q| q.is_empty())
1720    }
1721
1722    fn only_one_possible_decision(&self) -> bool {
1723        // Even a sole buffered version for a key admits two resolutions (a key not yet
1724        // in the snapshot may stay withheld; a key with a previous value may keep it).
1725        #[expect(clippy::disallowed_methods, reason = "FxHasher is deterministic")]
1726        self.input.borrow().values().all(|q| q.is_empty())
1727    }
1728
1729    fn release_decision(&mut self, log_writer: Option<&mut dyn std::fmt::Write>) {
1730        if let Some(to_release) = self.to_release.take() {
1731            if let Some(log_writer) = log_writer {
1732                let HookLocationMeta {
1733                    location: batch_location,
1734                    line,
1735                    caret_indent,
1736                } = self.batch_location;
1737                let note_str = if to_release.is_empty() {
1738                    "^ releasing no items".to_owned()
1739                } else {
1740                    let mut mapping_text = String::new();
1741                    for (key, value, is_new) in &to_release {
1742                        let entry_text = if *is_new {
1743                            format!(
1744                                "{:?}: {:?}",
1745                                ManualDebug(key, self.format_key_debug),
1746                                ManualDebug(value, self.format_value_debug)
1747                            )
1748                        } else {
1749                            format!(
1750                                "{:?}: {:?} (unchanged)",
1751                                ManualDebug(key, self.format_key_debug),
1752                                ManualDebug(value, self.format_value_debug)
1753                            )
1754                        };
1755                        if !mapping_text.is_empty() {
1756                            mapping_text.push_str(", ");
1757                        }
1758                        mapping_text.push_str(&entry_text);
1759                    }
1760                    format!("^ releasing items: {{ {} }}", mapping_text)
1761                };
1762
1763                log_release(
1764                    log_writer,
1765                    batch_location,
1766                    line,
1767                    caret_indent,
1768                    &note_str,
1769                    colored::Color::Green,
1770                );
1771            }
1772
1773            for (key, value, _) in to_release {
1774                self.output.try_send((key, value)).unwrap();
1775            }
1776        } else {
1777            panic!("No decision to release");
1778        }
1779    }
1780
1781    fn location_meta(&self) -> HookLocationMeta {
1782        self.batch_location
1783    }
1784}
1785
1786impl<K: Hash + Eq + Clone, V: Clone> TickInputHook for KeyedSingletonHook<K, V> {
1787    fn can_trigger_tick(&self) -> bool {
1788        // Snapshot ingress is lazy: a new buffered version never wakes the tick on its
1789        // own. It is only revealed when the tick runs for some other reason.
1790        false
1791    }
1792
1793    fn autonomous_decision<'a>(&mut self, driver: &mut Borrowed<'a>, force_trigger: bool) -> bool {
1794        assert!(
1795            !force_trigger,
1796            "Snapshot hooks never trigger a tick, so they must not be forced to"
1797        );
1798
1799        let mut current_input = self.input.borrow_mut();
1800        self.to_release = Some(vec![]);
1801        #[expect(clippy::disallowed_methods, reason = "FxHasher is deterministic")]
1802        for (key, queue) in current_input.iter_mut() {
1803            if queue.is_empty() {
1804                self.to_release.as_mut().unwrap().push((
1805                    key.clone(),
1806                    self.last_released.get(key).unwrap().clone(),
1807                    false,
1808                ));
1809
1810                continue;
1811            }
1812
1813            if self.last_released.contains_key(key) && produce().generate(driver).unwrap() {
1814                // Re-release the last item for this key
1815                let last = self.last_released.get(key).unwrap().clone();
1816                self.to_release
1817                    .as_mut()
1818                    .unwrap()
1819                    .push((key.clone(), last, false));
1820            } else {
1821                let allow_null_release = !self.last_released.contains_key(key);
1822                if allow_null_release && produce().generate(driver).unwrap() {
1823                    // Don't emit anything, this key is not yet added to the snapshot
1824                    continue;
1825                }
1826
1827                // Release a new item for this key
1828                let idx_to_release = (0..queue.len()).generate(driver).unwrap();
1829                let skipped: Vec<V> = queue.drain(0..idx_to_release).collect();
1830                let item = queue.pop_front().unwrap();
1831                self.skipped_states.insert(key.clone(), skipped);
1832                self.to_release
1833                    .as_mut()
1834                    .unwrap()
1835                    .push((key.clone(), item.clone(), true));
1836                self.last_released.insert(key.clone(), item);
1837            }
1838        }
1839
1840        // Revealing new versions is lazy: it never counts as triggering the tick.
1841        false
1842    }
1843}
1844
1845/// A scripted decision for a keyed snapshot hook: which buffered version each key's next
1846/// tick execution observes.
1847///
1848/// The [`Self::Reveal`] payload is a `Vec` rather than a map: the scripted entry order is
1849/// preserved for the release log, and the handle rejects duplicate keys when the decision
1850/// is created, so key distinctness is an invariant rather than a map-enforced property.
1851#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
1852pub enum KeyedSnapshotDecision<K, V> {
1853    /// For each named key, reveal the first buffered version equal to the named value,
1854    /// skipping over earlier versions. Keys are distinct (enforced by the handle when
1855    /// the decision is created; a key observes exactly one version per tick). Keys that
1856    /// are not named observe their previously revealed version again (or stay absent if
1857    /// they have never been revealed).
1858    Reveal(Vec<(K, V)>),
1859    /// For every key, reveal the newest version that has arrived by the time the tick
1860    /// fires (keys with nothing newer observe their previously revealed version again).
1861    RevealLatest,
1862    /// Every key observes its previously revealed version again.
1863    Keep,
1864}
1865
1866impl<K, V> ScriptDecision for KeyedSnapshotDecision<K, V>
1867where
1868    K: serde::Serialize + serde::de::DeserializeOwned,
1869    V: serde::Serialize + serde::de::DeserializeOwned,
1870{
1871    fn describe(&self) -> String {
1872        match self {
1873            KeyedSnapshotDecision::Reveal(_) => "reveal(..)".to_owned(),
1874            KeyedSnapshotDecision::RevealLatest => "reveal_latest()".to_owned(),
1875            KeyedSnapshotDecision::Keep => "keep()".to_owned(),
1876        }
1877    }
1878}
1879
1880/// The pending-input view a keyed snapshot hook reports to its test-side handle (see
1881/// [`ScriptableHook::status`]), used by `pause_until_*` predicates.
1882#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
1883pub struct KeyedSnapshotStatus {
1884    /// The total number of buffered versions (across all keys) newer than the last
1885    /// revealed ones.
1886    pub newer_versions: usize,
1887    /// The number of keys with at least one newer buffered version.
1888    pub keys_with_newer_versions: usize,
1889}
1890
1891impl<K, V> ScriptableHook for KeyedSingletonHook<K, V>
1892where
1893    K: Hash + Eq + Clone + serde::Serialize + serde::de::DeserializeOwned,
1894    V: Clone + PartialEq + serde::Serialize + serde::de::DeserializeOwned,
1895{
1896    type Decision = KeyedSnapshotDecision<K, V>;
1897    type Status = KeyedSnapshotStatus;
1898
1899    fn is_honorable(&self, decision: &KeyedSnapshotDecision<K, V>) -> Result<bool, String> {
1900        let input = self.input.borrow();
1901        Ok(match decision {
1902            KeyedSnapshotDecision::Reveal(entries) => entries.iter().all(|(key, target)| {
1903                input
1904                    .get(key)
1905                    .is_some_and(|queue| queue.iter().any(|version| version == target))
1906            }),
1907            KeyedSnapshotDecision::RevealLatest => {
1908                keyed_buffer_len(&input) > 0 || !self.last_released.is_empty()
1909            }
1910            KeyedSnapshotDecision::Keep => true,
1911        })
1912    }
1913
1914    fn apply(&mut self, decision: KeyedSnapshotDecision<K, V>) {
1915        let mut input = self.input.borrow_mut();
1916        match decision {
1917            KeyedSnapshotDecision::Reveal(entries) => {
1918                let mut to_release = vec![];
1919                let mut named: FxHashSet<K> = FxHashSet::default();
1920                for (key, target) in entries {
1921                    let queue = input.get_mut(&key).unwrap();
1922                    let idx = queue.iter().position(|version| *version == target).unwrap();
1923                    let skipped: Vec<V> = queue.drain(0..idx).collect();
1924                    let item = queue.pop_front().unwrap();
1925                    self.skipped_states.insert(key.clone(), skipped);
1926                    self.last_released.insert(key.clone(), item.clone());
1927                    to_release.push((key.clone(), item, true));
1928                    named.insert(key);
1929                }
1930                // Unnamed keys observe their previously revealed version again.
1931                #[expect(clippy::disallowed_methods, reason = "FxHasher is deterministic")]
1932                for (key, last) in self.last_released.iter() {
1933                    if !named.contains(key) {
1934                        to_release.push((key.clone(), last.clone(), false));
1935                    }
1936                }
1937                self.to_release = Some(to_release);
1938            }
1939            KeyedSnapshotDecision::RevealLatest => {
1940                let mut to_release = vec![];
1941                #[expect(clippy::disallowed_methods, reason = "FxHasher is deterministic")]
1942                for (key, queue) in input.iter_mut() {
1943                    if queue.is_empty() {
1944                        if let Some(last) = self.last_released.get(key) {
1945                            to_release.push((key.clone(), last.clone(), false));
1946                        }
1947                    } else {
1948                        let skip_count = queue.len() - 1;
1949                        let skipped: Vec<V> = queue.drain(0..skip_count).collect();
1950                        let item = queue.pop_front().unwrap();
1951                        self.skipped_states.insert(key.clone(), skipped);
1952                        self.last_released.insert(key.clone(), item.clone());
1953                        to_release.push((key.clone(), item, true));
1954                    }
1955                }
1956                self.to_release = Some(to_release);
1957            }
1958            KeyedSnapshotDecision::Keep => {
1959                #[expect(clippy::disallowed_methods, reason = "FxHasher is deterministic")]
1960                let to_release = self
1961                    .last_released
1962                    .iter()
1963                    .map(|(key, last)| (key.clone(), last.clone(), false))
1964                    .collect();
1965                self.to_release = Some(to_release);
1966            }
1967        }
1968    }
1969
1970    fn implicit(&mut self) {
1971        // "Nothing new": every previously revealed key observes its value again.
1972        #[expect(clippy::disallowed_methods, reason = "FxHasher is deterministic")]
1973        let to_release = self
1974            .last_released
1975            .iter()
1976            .map(|(key, last)| (key.clone(), last.clone(), false))
1977            .collect();
1978        self.to_release = Some(to_release);
1979    }
1980
1981    fn status(&self) -> KeyedSnapshotStatus {
1982        let input = self.input.borrow();
1983        #[expect(clippy::disallowed_methods, reason = "FxHasher is deterministic")]
1984        let keys_with_newer_versions = input.values().filter(|q| !q.is_empty()).count();
1985        KeyedSnapshotStatus {
1986            newer_versions: keyed_buffer_len(&input),
1987            keys_with_newer_versions,
1988        }
1989    }
1990
1991    fn describe_pending(&self) -> Option<String> {
1992        let input = self.input.borrow();
1993        let total = keyed_buffer_len(&input);
1994        #[expect(clippy::disallowed_methods, reason = "FxHasher is deterministic")]
1995        let keys = input.values().filter(|q| !q.is_empty()).count();
1996        (total > 0).then(|| format!("{} buffered version(s) across {} key(s)", total, keys))
1997    }
1998}
1999
2000impl<K, V> ScriptableTickInputHook for KeyedSingletonHook<K, V>
2001where
2002    K: Hash + Eq + Clone + serde::Serialize + serde::de::DeserializeOwned,
2003    V: Clone + PartialEq + serde::Serialize + serde::de::DeserializeOwned,
2004{
2005    fn decision_triggers_tick(&self, decision: &KeyedSnapshotDecision<K, V>) -> bool {
2006        match decision {
2007            KeyedSnapshotDecision::Reveal(entries) => !entries.is_empty(),
2008            KeyedSnapshotDecision::RevealLatest => keyed_buffer_len(&self.input.borrow()) > 0,
2009            KeyedSnapshotDecision::Keep => false,
2010        }
2011    }
2012}