Skip to main content

rings_core/message/
replay.rs

1//! Destination-scoped replay protection for signed transactions.
2//!
3//! The stream identity is `(network_id, origin account DID, destination DID, traffic class)`
4//! (#898). A receiver keeps a fixed-width window per stream, so delivery may be reordered within
5//! the window without turning a normal gap into an omission claim. The state transition is pure
6//! in [`observe`]; [`TransactionReplay`] is the effect boundary that serializes transitions and
7//! persists an admitted state before returning it to the inbound dispatcher.
8//!
9//! **Law (in-class order).** The sender signs a class's transactions in sequence order and its
10//! outbound scheduler keeps them in that order on the class lane, with fewer than
11//! [`TRANSACTION_REPLAY_WINDOW`] in flight. Each class lane is pinned to one ordered data channel
12//! of the connection, so a class's stream reaches this admission in sequence order whatever the
13//! other classes' channels do, and a stall on one class's channel holds only that class. An
14//! honest stream crossing one edge is therefore never rejected as stale; a class lane that is
15//! not pinned (frames spread over several channels) loses this law, since another channel can
16//! carry later sequences of the class past a stalled one.
17//!
18//! No frame is held on the way: a frame whose delegation reference misses is dropped, never
19//! delivered late, and an honest sender's reference resolves whenever its transit stays under
20//! the lease margin and grace (the lease law of `swarm::session_link`, #908), so the law holds
21//! for every frame that arrives.
22//!
23//! Persistence is one record per stream (see [`store`]): a transition writes only its stream's
24//! record, at most [`TRANSACTION_REPLAY_RECORD_MAX_BYTES`], so the cost of an admission does not
25//! grow with the number of streams retained.
26//!
27//! An admission writes its stream's record every time; a reservation writes it only when it
28//! outruns the stream's durable lease of sender sequences, which then covers the next
29//! `TRANSACTION_SEQUENCE_LEASE` sequences (#1043). A restart resumes past the lease: it may
30//! skip sequences, never reuse one (the laws of [`lease`]). A link-local transaction (#1081) meets
31//! none of this: it is admitted by [`TransactionReplay::admit_on_link`] in a volatile window of
32//! the link it arrived on, which its connection holds ([`LinkWindows`]), and writes nothing
33//! (durable-records, Law Window by classification). The records of the transitions that
34//! run while one batch is written share the next batch, one flush for all of them, and each
35//! transition is released only once its batch is durable (the group-commit law of [`commit`],
36//! #916).
37//!
38//! **Law (fail closed per stream, #910).** The first operation restores the store from one scan
39//! of the storage and caches the result, including every record that does not restore. For a
40//! stream `s` whose stored record is damaged (torn, corrupt or unreadable, or holding another
41//! key's record) or missing (witnessed as written by the store, and no longer held, #915):
42//!
43//! ```text
44//! ∀ transition t of s.   t = Err(TransactionReplayStreamUnavailable { s, record })
45//!                        until the record is cleared and the node restarts
46//! ∀ s′ ≠ s restored.     state(s′) and the verdicts of s′ are those of a store without s
47//! ∀ s′ new.              s′ opens only if its table's streams + |U| < capacity
48//! cost(restore) = O(|store|), once;  cost(call) = 0 store reads + at most 1 record in a batch
49//! ```
50//!
51//! so no replay is admitted from, and no sequence is reused by, such a stream, while every stream
52//! already in the store keeps its guarantee; a new stream sees each such record hold one slot of
53//! its table's bound. The law covers the records the storage witnesses: the native store keeps a
54//! presence marker per record, so a record deleted or renamed outside it is missing, not a
55//! stream never seen; only a store lost whole (its directory, or the browser's database) reads
56//! as a stream never seen, for every stream, which is the reset below. Each batch of the native
57//! store is flushed, which bounds the rate of batches, not of transitions (see the replay
58//! chapter). The unrestorable
59//! records are counted ([`ReplayCounters::unrestorable_record`]), each refusal is counted
60//! ([`ReplayCounters::unavailable_stream`]), and each is logged once at load with its storage
61//! record name. A scan that fails as a whole restores nothing: it is counted as a persistence
62//! failure, and the next operation scans again.
63//!
64//! **Recovery.** An operator clears one failed stream, accepting a replay-window reset for that
65//! stream alone, by removing the record the refusal and the log name while the node is stopped,
66//! and then starting it: the native daemon keeps each record as the file of that name in the
67//! `transaction-replay` directory beside its data store, with its presence marker `<name>.p`
68//! beside it, which the operator removes too; a browser provider keeps it as the
69//! row of that key in the IndexedDB database and object store `<storage name>/transaction-replay`
70//! (see the replay chapter for the steps). After the restart the stream starts from `First`: an
71//! unexpired transaction of a cleared receiver stream may be admitted once more, and a cleared
72//! sender stream restarts at sequence zero. Its destination rejects those sequences until they
73//! pass its retained high watermark: as `Stale` below the window, and as `Fork`, with signed
74//! [`TransactionForkEvidence`] against this node, inside it; the messages they carry are lost.
75//! No other stream is touched.
76//!
77//! **Law (stream admission, #907; load-bounds paper, Law 2).** The receiver table is a table
78//! under slot accounting (`fair_admission::slot_accounting`): a new stream is charged to the
79//! connection slot of the edge that delivered its first transaction, or to this node for its own
80//! relay inbox and
81//! signaling, and admitted only within that principal's floor, fair claim of the pool, or local
82//! share ([`admission::RECEIVER_STREAM_SHARES`]); an origin, which costs nothing to mint, is never
83//! a principal. A stream is spent once its every transaction can no longer be delivered
84//! ([`spent_at`]):
85//!
86//! ```text
87//! spent(s, t) ⟺ t ≥ max_{x ∈ s} (ts(x) + ttl(x)) + ι(class(s)) + σ
88//! ```
89//!
90//! and only a spent stream that holds no relay custody leaves the table, retired by the next
91//! admission that reads the clock past it; forgetting it reopens no replay (Lemma 2), so a
92//! refusal lasts until a stream of the refused principal is spent, never for good. Each
93//! receiver record carries its stream's charge, so a restart recovers the accounting.
94//!
95//! The sender table holds this node's own streams: it never evicts, and a new stream fails
96//! closed at [`TRANSACTION_REPLAY_STREAM_CAPACITY`], which also bounds the receiver table. The
97//! store must therefore hold [`TRANSACTION_REPLAY_STORE_MAX_BYTES`] and
98//! [`TRANSACTION_REPLAY_STORE_MAX_RECORDS`] without evicting any. Deleting that store deletes
99//! the corresponding replay guarantee. Runtime-local origin quota state shares the serialized
100//! receiver commit boundary but is not part of the store.
101
102use std::collections::BTreeMap;
103use std::num::NonZeroU64;
104use std::ops::RangeInclusive;
105use std::sync::atomic::AtomicU64;
106use std::sync::atomic::Ordering;
107use std::sync::Arc;
108use std::time::Duration;
109
110use futures::lock::Mutex;
111use rings_runtime::MaybeSend;
112use serde::Deserialize;
113use serde::Serialize;
114
115use crate::dht::Did;
116use crate::error::Error;
117use crate::error::Result;
118use crate::fair_admission::Principal;
119use crate::fair_admission::SlotFloorUse;
120use crate::fair_admission::TableAccounting;
121use crate::message::quota::quota_admission_error;
122use crate::message::quota::OriginQuotaCounterState;
123use crate::message::quota::OriginQuotaTable;
124use crate::message::types::MessageCategory;
125use crate::message::OriginQuotaConfig;
126use crate::message::OriginQuotaCounters;
127use crate::message::OriginQuotaKey;
128use crate::storage::KvStorageScan;
129use crate::swarm::transport::DELIVERY_BOUND;
130use crate::utils::Instant;
131use crate::utils::SharedClock;
132use crate::utils::SystemClock;
133
134mod admission;
135mod commit;
136mod custody;
137mod lease;
138mod store;
139
140use self::admission::replay_clock;
141pub(crate) use self::admission::spent_at;
142pub(crate) use self::admission::Admission;
143use self::admission::ReplayInstant;
144pub(crate) use self::admission::RECEIVER_STREAM_SHARES;
145use self::commit::Journal;
146use self::commit::Ledger;
147pub(crate) use self::custody::RelayAdmission;
148pub(crate) use self::custody::RelayDelivery;
149use self::lease::allocate;
150use self::store::restore;
151use self::store::sender_record;
152pub use self::store::ReplayRecord;
153use self::store::ReplayStore;
154use self::store::ReplayTable;
155use self::store::RestoreFailure;
156use self::store::StreamCharge;
157pub use self::store::TRANSACTION_REPLAY_RECORD_MAX_BYTES;
158pub use self::store::TRANSACTION_REPLAY_STORE_MAX_BYTES;
159pub use self::store::TRANSACTION_REPLAY_STORE_MAX_RECORDS;
160
161/// Number of out-of-order sequence slots retained for one destination-scoped stream.
162pub const TRANSACTION_REPLAY_WINDOW: usize = 32;
163/// How many later frames of one stream may overtake a frame that still arrives: the replay
164/// window, which refuses a frame further behind. A stream consumer reorders at most this far.
165pub const REORDER_WINDOW: u64 = 32;
166const _: () = assert!(REORDER_WINDOW == TRANSACTION_REPLAY_WINDOW as u64);
167/// How long a frame of one stream may still arrive after a later frame of that stream did.
168///
169/// On one edge a stream's frames arrive in order (the in-class order law). End to end they may
170/// not, when the stream's route, or the connection generation of one of its hops, changes
171/// mid-stream: frames still in flight on the superseded path land later than frames sent on
172/// the new one, each within the delivery bound of every hop it has yet to cross, since every
173/// hop delivers a frame or gives it up within its delivery bound. The deadline allows four such
174/// bounds: a superseded path with at most four hops left to cross. A stream consumer takes a
175/// frame still missing this long after a later one arrived as lost; one that has seen
176/// [`REORDER_WINDOW`] later frames of it has lost it, since the replay window refuses it.
177pub const REORDER_DEADLINE: Duration = DELIVERY_BOUND.saturating_mul(4);
178const TRANSACTION_REPLAY_BACKTRACK: u64 = 31;
179/// Account-to-destination pairs whose four class streams one runtime retains in full.
180const TRANSACTION_REPLAY_PAIR_CAPACITY: usize = 4096;
181/// Maximum sender streams and maximum receiver streams retained by one runtime.
182///
183/// A pair keeps one stream per traffic class (#898), so the table holds one stream per
184/// [`MessageCategory`] for each of 4096 pairs: 4096 origins that use every class, or
185/// proportionally more that use fewer. A pair's streams count separately, and a new stream
186/// fails closed at this bound whichever class it belongs to.
187pub const TRANSACTION_REPLAY_STREAM_CAPACITY: usize =
188    MessageCategory::COUNT * TRANSACTION_REPLAY_PAIR_CAPACITY;
189/// Persistent DID encoding for [`StreamKey`]: always encodes as the 42-character `0x`-prefixed
190/// hex string (`ethereum_types::H160`) so authoritative `ReplayStore` records and storage keys
191/// remain invariant across wire-encoding upgrades (#1282).
192mod persisted_did {
193    use ethereum_types::H160;
194    use serde::Deserialize;
195    use serde::Deserializer;
196    use serde::Serialize;
197    use serde::Serializer;
198
199    use crate::dht::Did;
200
201    pub(super) fn serialize<S>(did: &Did, serializer: S) -> std::result::Result<S::Ok, S::Error>
202    where S: Serializer {
203        H160::from(*did).serialize(serializer)
204    }
205
206    pub(super) fn deserialize<'de, D>(deserializer: D) -> std::result::Result<Did, D::Error>
207    where D: Deserializer<'de> {
208        H160::deserialize(deserializer).map(Did::from)
209    }
210}
211
212/// A destination-scoped transaction stream of one traffic class (#898).
213///
214/// Sequences are ordered only per class. The outbound scheduler preserves order inside a
215/// class lane and deliberately reorders across lanes, so a stream shared by every class let a
216/// backlog in one lane fall behind later-sequenced traffic of another lane and be rejected as
217/// stale. With one stream per class, an honest sender's transactions reach the receiver in
218/// sequence order: the class lane keeps them FIFO with fewer in flight than the replay window,
219/// and the one data channel it is pinned to delivers them in that order.
220#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
221pub struct StreamKey {
222    /// Overlay in which the transaction signature is valid.
223    pub network_id: u32,
224    /// Account DID recovered from the transaction's delegation.
225    #[serde(with = "persisted_did")]
226    pub origin_account: Did,
227    /// Final logical destination of the transaction.
228    #[serde(with = "persisted_did")]
229    pub destination: Did,
230    /// Traffic class implied by the transaction's signed data.
231    pub class: MessageCategory,
232}
233
234impl StreamKey {
235    /// Name one account-to-destination stream of `class` inside an overlay.
236    pub const fn new(
237        network_id: u32,
238        origin_account: Did,
239        destination: Did,
240        class: MessageCategory,
241    ) -> Self {
242        Self {
243            network_id,
244            origin_account,
245            destination,
246            class,
247        }
248    }
249}
250
251/// Digest of one exact signed transaction.
252#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
253pub struct TransactionDigest(pub(crate) [u8; 32]);
254
255impl TransactionDigest {
256    /// Construct a digest from its canonical 32-byte representation.
257    pub const fn new(bytes: [u8; 32]) -> Self {
258        Self(bytes)
259    }
260
261    /// Return the canonical digest bytes.
262    pub const fn into_bytes(self) -> [u8; 32] {
263        self.0
264    }
265}
266
267/// The two exact signed-transaction digests retained for a sequence fork.
268#[derive(Clone, Copy, Debug, Eq, PartialEq)]
269pub struct TransactionForkEvidence {
270    /// Digest already retained for the sequence.
271    pub accepted: TransactionDigest,
272    /// Digest presented by the conflicting transaction.
273    pub incoming: TransactionDigest,
274}
275
276/// Fixed-width accepted-sequence window for one stream.
277///
278/// `accepted.last()` is sequence `high`; preceding slots descend toward
279/// `high.saturating_sub(31)`. Slots below sequence zero are necessarily empty.
280#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
281pub struct SequenceState {
282    high: u64,
283    accepted: [Option<TransactionDigest>; TRANSACTION_REPLAY_WINDOW],
284}
285
286impl SequenceState {
287    fn first(sequence: u64, digest: TransactionDigest) -> Self {
288        let mut accepted = [None; TRANSACTION_REPLAY_WINDOW];
289        if let Some(slot) = accepted.last_mut() {
290            *slot = Some(digest);
291        }
292        Self {
293            high: sequence,
294            accepted,
295        }
296    }
297
298    /// Highest sequence observed for this stream.
299    pub const fn high(&self) -> u64 {
300        self.high
301    }
302
303    /// Lowest sequence whose digest may still be retained.
304    pub const fn retained_min(&self) -> u64 {
305        self.high.saturating_sub(TRANSACTION_REPLAY_BACKTRACK)
306    }
307
308    fn is_valid(&self) -> bool {
309        let retained_slots = self
310            .high
311            .checked_add(1)
312            .and_then(|count| usize::try_from(count).ok())
313            .unwrap_or(TRANSACTION_REPLAY_WINDOW)
314            .min(TRANSACTION_REPLAY_WINDOW);
315        let unused_slots = TRANSACTION_REPLAY_WINDOW.saturating_sub(retained_slots);
316        self.accepted.iter().take(unused_slots).all(Option::is_none)
317            && self.accepted.last().is_some_and(Option::is_some)
318    }
319
320    fn advance(&mut self, sequence: u64, digest: TransactionDigest) {
321        let gap = sequence.saturating_sub(self.high);
322        if gap >= REORDER_WINDOW {
323            self.accepted.fill(None);
324        } else if let Ok(gap) = usize::try_from(gap) {
325            self.accepted.rotate_left(gap);
326            let retained = TRANSACTION_REPLAY_WINDOW.saturating_sub(gap);
327            for slot in self.accepted.iter_mut().skip(retained) {
328                *slot = None;
329            }
330        }
331        self.high = sequence;
332        if let Some(slot) = self.accepted.last_mut() {
333            *slot = Some(digest);
334        }
335    }
336
337    fn observe_retained(&mut self, sequence: u64, digest: TransactionDigest) -> SequenceVerdict {
338        let distance = self.high.saturating_sub(sequence);
339        let Ok(distance) = usize::try_from(distance) else {
340            return SequenceVerdict::Stale {
341                retained_min: self.retained_min(),
342            };
343        };
344        let Some(index) = TRANSACTION_REPLAY_WINDOW.checked_sub(distance.saturating_add(1)) else {
345            return SequenceVerdict::Stale {
346                retained_min: self.retained_min(),
347            };
348        };
349        let Some(slot) = self.accepted.get_mut(index) else {
350            return SequenceVerdict::Stale {
351                retained_min: self.retained_min(),
352            };
353        };
354        match *slot {
355            None => {
356                *slot = Some(digest);
357                SequenceVerdict::Late
358            }
359            Some(accepted) if accepted == digest => SequenceVerdict::Replay,
360            Some(accepted) => SequenceVerdict::Fork {
361                accepted,
362                incoming: digest,
363            },
364        }
365    }
366}
367
368/// Typed result of observing one sequence and exact signed-transaction digest.
369#[derive(Clone, Copy, Debug, Eq, PartialEq)]
370pub enum SequenceVerdict {
371    /// No retained state existed; this transaction established the stream baseline.
372    First,
373    /// The sequence advanced the high watermark, possibly across a normal delivery gap.
374    Advance,
375    /// The sequence filled an empty slot inside the retained reordering window.
376    Late,
377    /// The same exact signed transaction was already retained at this sequence.
378    Replay,
379    /// A different signed transaction was already retained at this sequence.
380    Fork {
381        /// Digest retained for the sequence.
382        accepted: TransactionDigest,
383        /// Digest presented by the new transaction.
384        incoming: TransactionDigest,
385    },
386    /// The sequence fell below the retained window.
387    Stale {
388        /// Lowest sequence that may still be retained.
389        retained_min: u64,
390    },
391}
392
393impl SequenceVerdict {
394    /// Whether this observation may cross the application dispatch boundary.
395    pub const fn permits_dispatch(self) -> bool {
396        matches!(self, Self::First | Self::Advance | Self::Late)
397    }
398}
399
400/// Apply the pure replay-window transition.
401///
402/// Transition shape: `Option<SequenceState> -> (sequence, digest) -> (SequenceState, verdict)`.
403/// Rejected observations return the original state unchanged.
404pub fn observe(
405    state: Option<SequenceState>,
406    sequence: u64,
407    digest: TransactionDigest,
408) -> (SequenceState, SequenceVerdict) {
409    let Some(mut state) = state else {
410        return (
411            SequenceState::first(sequence, digest),
412            SequenceVerdict::First,
413        );
414    };
415    if sequence > state.high {
416        state.advance(sequence, digest);
417        return (state, SequenceVerdict::Advance);
418    }
419    if sequence < state.retained_min() {
420        let retained_min = state.retained_min();
421        return (state, SequenceVerdict::Stale { retained_min });
422    }
423    let verdict = state.observe_retained(sequence, digest);
424    (state, verdict)
425}
426
427/// Run one replay transition detached from its caller (the law of whole transitions of
428/// [`TransactionReplay`]).
429///
430/// Post: `Err(TransactionReplayUnscheduled)` when no runtime is current (the transition never
431/// started) or the transition panicked; otherwise the transition's own result.
432async fn run_whole<T, F>(transition: F) -> Result<T>
433where
434    F: std::future::Future<Output = Result<T>> + MaybeSend + 'static,
435    T: MaybeSend + 'static,
436{
437    rings_runtime::run_detached(transition)
438        .await
439        .map_err(Error::TransactionReplayUnscheduled)?
440}
441
442/// `storage`'s record naming, under which it files each record and reports the records it cannot
443/// decode.
444fn record_naming(storage: &ReplayStorage) -> impl Fn(&str) -> String + '_ {
445    |storage_key| storage.record_name(storage_key)
446}
447
448/// The volatile replay windows of one link (#1081): the window of each stream whose
449/// link-local transactions arrived on it. Held by the link's inbound stage, never written, and
450/// released with the link, so a window lives exactly one link generation (durable-records, Law
451/// Window by classification).
452pub(crate) type LinkWindows = BTreeMap<StreamKey, SequenceState>;
453
454/// Storage accepted by the transaction replay runtime.
455pub type ReplayStorage = Box<rings_runtime::maybe_send_sync!(dyn KvStorageScan<ReplayRecord>)>;
456
457/// Observable rejected-verdict, persistence-failure and unavailable-stream counters.
458#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
459pub struct ReplayCounters {
460    /// Exact duplicate transactions rejected.
461    pub replay: u64,
462    /// Conflicting transactions at one sequence rejected.
463    pub fork: u64,
464    /// Transactions below the retained window rejected.
465    pub stale: u64,
466    /// Replay store reads or writes that failed.
467    pub persistence_failure: u64,
468    /// Records the load found that do not restore, each failing its stream closed; a gauge,
469    /// fixed once the store is loaded, and non-zero calls for an operator.
470    pub unrestorable_record: u64,
471    /// Reservations and admissions refused because their stream's record does not restore.
472    pub unavailable_stream: u64,
473}
474
475/// The atomic cells behind [`ReplayCounters`].
476#[derive(Default)]
477struct ReplayCounterState {
478    replay: AtomicU64,
479    fork: AtomicU64,
480    stale: AtomicU64,
481    persistence_failure: AtomicU64,
482    unrestorable_record: AtomicU64,
483    unavailable_stream: AtomicU64,
484}
485
486impl ReplayCounterState {
487    /// The current value of every counter.
488    fn snapshot(&self) -> ReplayCounters {
489        ReplayCounters {
490            replay: self.replay.load(Ordering::Relaxed),
491            fork: self.fork.load(Ordering::Relaxed),
492            stale: self.stale.load(Ordering::Relaxed),
493            persistence_failure: self.persistence_failure.load(Ordering::Relaxed),
494            unrestorable_record: self.unrestorable_record.load(Ordering::Relaxed),
495            unavailable_stream: self.unavailable_stream.load(Ordering::Relaxed),
496        }
497    }
498}
499
500/// Serialized sender allocator and receiver replay-window effect boundary.
501///
502/// One mutex serializes every reservation and admission on the speculative tables, and the
503/// records are written by group commit outside it (the group-commit law of [`commit`], #916):
504/// the transitions that run while one batch is written join the next, which one store batch
505/// writes with one flush, and each transition is released only once its batch is durable. Each
506/// record is at most [`TRANSACTION_REPLAY_RECORD_MAX_BYTES`].
507///
508/// **Law (whole transitions).** A transition, once started, runs to its end: lock, apply its
509/// effect, join the open batch, unlock, and wait for the batch. [`Self::reserve`] and
510/// [`Self::admit_with_quota`] hand it to the runtime ([`rings_runtime::run_detached`]), so
511/// cancelling the caller abandons only the wait. Otherwise a cancelled caller could leave the
512/// speculative tables holding an effect its batch never carries, and the next transition of the
513/// stream would compute from it: a receiver replay, or re-signed sender sequences, after a
514/// restart.
515///
516/// A cancelled caller's transition therefore commits, exactly as if the caller had dropped the
517/// verdict: an admission enters the window and is charged its quota, though nobody dispatches
518/// it, so a retransmission of that transaction is a `Replay` and the message is lost (as for
519/// any drop after admission); a reservation consumes its sequences, which leaves a gap the
520/// receiver accepts as `Advance`. Cancellation also no longer sheds a queued transition: each
521/// cancelled attempt still joins its batch.
522///
523/// ```text
524/// caller ──call──▶ run_detached ─▶ [lock ─▶ T̂ := t(T̂) ─▶ join batch ─▶ unlock] ─▶ durable
525///   │ drop                                   (owned by the runtime, never torn)
526///   └──────────▶ only the wait is abandoned
527/// ```
528pub(crate) struct TransactionReplay {
529    /// The replay store; `None` when the node was given none, so that every transition is
530    /// refused (`Error::TransactionReplayStorageUnavailable`, #1022): durable-records admits no
531    /// volatile replay store, whose loss at every restart would reopen every stream.
532    storage: Option<ReplayStorage>,
533    /// The receiver table's slot accounting (load-bounds paper, Law 2).
534    accounting: TableAccounting,
535    state: Mutex<TransactionAdmissionState>,
536    started_at: Instant,
537    clock: SharedClock,
538    counters: ReplayCounterState,
539    quota_counters: OriginQuotaCounterState,
540}
541
542struct TransactionAdmissionState {
543    /// The replay store, restored once on the first operation and cached from then on; its
544    /// tables are the speculative ones (the group-commit law).
545    store: Option<ReplayStore>,
546    /// Runtime-local origin quotas.
547    quota: OriginQuotaTable,
548    /// The open batch and the undo log of the one being written.
549    journal: Journal,
550}
551
552impl TransactionReplay {
553    /// Construct a shared replay runtime, as the transport holds it. The store is restored
554    /// lazily on its first operation.
555    #[cfg(test)]
556    pub(crate) fn new_shared(storage: ReplayStorage) -> Arc<Self> {
557        Arc::new(Self::with_quota_for_test(
558            Some(storage),
559            OriginQuotaConfig::default(),
560        ))
561    }
562
563    /// Test builds: a replay runtime over `storage` with `quota_config` and the production
564    /// shares.
565    #[cfg(test)]
566    pub(crate) fn with_quota_for_test(
567        storage: Option<ReplayStorage>,
568        quota_config: OriginQuotaConfig,
569    ) -> Self {
570        let accounting = TableAccounting::new(RECEIVER_STREAM_SHARES);
571        Self::new_with_quota(storage, quota_config, accounting)
572    }
573
574    /// Construct a replay runtime over `storage` with explicit runtime-local origin quotas,
575    /// whose receiver table is accounted in `accounting`; with no storage, every reservation and
576    /// admission is refused (the field's law).
577    pub(crate) fn new_with_quota(
578        storage: Option<ReplayStorage>,
579        quota_config: OriginQuotaConfig,
580        accounting: TableAccounting,
581    ) -> Self {
582        Self {
583            storage,
584            accounting,
585            state: Mutex::new(TransactionAdmissionState {
586                store: None,
587                quota: OriginQuotaTable::new(quota_config),
588                journal: Journal::default(),
589            }),
590            started_at: Instant::now(),
591            clock: Arc::new(SystemClock),
592            counters: ReplayCounterState::default(),
593            quota_counters: OriginQuotaCounterState::default(),
594        }
595    }
596
597    /// Bind `clock` as the epoch clock read by spent-stream retirement and relay custody.
598    pub(crate) fn with_clock(mut self, clock: SharedClock) -> Self {
599        self.clock = clock;
600        self
601    }
602
603    /// Current observable counters.
604    pub(crate) fn counters(&self) -> ReplayCounters {
605        self.counters.snapshot()
606    }
607
608    /// The floor use of every slot in the receiver table at `now_ms` (load-bounds paper,
609    /// Def. 1).
610    pub(crate) fn floor_use_at(&self, now_ms: u128) -> SlotFloorUse {
611        self.accounting.floor_use_at(now_ms)
612    }
613
614    /// Current aggregate origin-quota rejection counters.
615    pub(crate) fn quota_counters(&self) -> OriginQuotaCounters {
616        self.quota_counters.snapshot()
617    }
618
619    /// The replay store, restored from one scan of the storage on the first operation and
620    /// cached from then on, unrestorable records included, so no later operation reads the
621    /// storage again.
622    ///
623    /// A scan that fails as a whole restores nothing: it is counted, the operation fails closed,
624    /// and the next operation scans again.
625    ///
626    /// ```text
627    /// slot cached? ── yes ──────────────────────────────────────────────▶ slot
628    ///      │ no
629    /// no storage ──────────▶ Err(TransactionReplayStorageUnavailable)
630    /// scan storage ── Err ──▶ count persistence failure ──▶ Err(load) (slot stays empty)
631    ///      │ Ok(records)
632    /// restore (pure, total) ──▶ count + log unrestorable ──▶ charge streams ──▶ slot := store
633    /// ```
634    async fn load_store<'a>(
635        &self,
636        slot: &'a mut Option<ReplayStore>,
637    ) -> Result<&'a mut ReplayStore> {
638        if slot.is_none() {
639            let storage = self.storage()?;
640            let records = storage.scan().await.map_err(|source| {
641                self.count_persistence_failure();
642                Error::TransactionReplayPersistence {
643                    operation: "load",
644                    source: Arc::new(source),
645                }
646            })?;
647            let restored = restore(records, record_naming(storage));
648            self.report_unrestorable(&restored.unrestorable);
649            restored.tables.charge_all(&mut self.accounting.lock());
650            *slot = Some(restored);
651        }
652        slot.as_mut().ok_or(Error::TransactionReplayStateInvalid)
653    }
654
655    /// The replay store, or the refusal of a node given none (the law of `storage`).
656    fn storage(&self) -> Result<&ReplayStorage> {
657        self.storage
658            .as_ref()
659            .ok_or(Error::TransactionReplayStorageUnavailable)
660    }
661
662    /// Count and log the `unrestorable` records of a fresh load; each fails its stream closed
663    /// until an operator clears it (see the module documentation).
664    fn report_unrestorable(&self, unrestorable: &BTreeMap<String, RestoreFailure>) {
665        let count = u64::try_from(unrestorable.len()).unwrap_or(u64::MAX);
666        self.counters
667            .unrestorable_record
668            .store(count, Ordering::Relaxed);
669        for (record, failure) in unrestorable.iter() {
670            tracing::error!(
671                record = %record,
672                failure = ?failure,
673                "replay record does not restore; its stream fails closed until it is cleared"
674            );
675        }
676    }
677
678    /// Refuse, and count, a transition of stream `key` of `table` whose record does not
679    /// restore (the fail-closed-per-stream law of [`store`]).
680    fn refuse_unavailable(
681        &self,
682        store: &ReplayStore,
683        table: ReplayTable,
684        key: StreamKey,
685    ) -> Result<()> {
686        match store.unavailable_record(table, &key, record_naming(self.storage()?))? {
687            None => Ok(()),
688            Some(record) => {
689                self.counters
690                    .unavailable_stream
691                    .fetch_add(1, Ordering::Relaxed);
692                Err(Error::TransactionReplayStreamUnavailable { key, record })
693            }
694        }
695    }
696
697    /// Count one failed replay-store read or write.
698    fn count_persistence_failure(&self) {
699        self.counters
700            .persistence_failure
701            .fetch_add(1, Ordering::Relaxed);
702    }
703
704    /// Reserve `count` sender sequences, staging the stream's lease whenever they outrun it,
705    /// and return the range to the signer once its batch is durable (the laws of [`lease`] and
706    /// [`commit`]).
707    ///
708    /// The transition runs detached from the caller (the law of whole transitions): cancelling
709    /// the caller abandons only the wait.
710    pub(crate) async fn reserve(
711        self: &Arc<Self>,
712        key: StreamKey,
713        count: NonZeroU64,
714    ) -> Result<RangeInclusive<u64>> {
715        self.commit(move |replay, ledger| replay.allocate_in(ledger, key, count))
716            .await
717    }
718
719    /// The reservation transition on the speculative state: allocate, stage the extended lease
720    /// if the allocation outruns the stream's lease, then update the table.
721    ///
722    /// ```text
723    /// allocate(table[key], count) ── ⊥ ──▶ Err(TransactionSequenceExhausted)
724    ///      │ extend = None ───────────────────────────▶ table[key] := next ──▶ range
725    ///      │ extend = Some(L) ──▶ stage D := L ───────▶ table[key] := next ──▶ range
726    /// ```
727    fn allocate_in(
728        &self,
729        ledger: &mut Ledger<'_>,
730        key: StreamKey,
731        count: NonZeroU64,
732    ) -> Result<RangeInclusive<u64>> {
733        self.refuse_unavailable(ledger.store, ReplayTable::Sender, key)?;
734        let previous = ledger.store.tables.sender.get(&key).copied();
735        if previous.is_none() {
736            ledger
737                .store
738                .admits_new_stream(ReplayTable::Sender)
739                .map_err(|refusal| Error::TransactionReplayStreamCapacityExceeded {
740                    introducer: Principal::Local,
741                    refusal,
742                })?;
743        }
744        let allocation =
745            allocate(previous, count).ok_or(Error::TransactionSequenceExhausted { key })?;
746        if let Some(leased) = allocation.extend {
747            ledger.write(sender_record(&key, leased)?);
748        }
749        ledger.set_sender(key, allocation.next);
750        Ok(allocation.range)
751    }
752
753    /// Atomically commit replay classification and origin-quota admission before dispatch.
754    ///
755    /// The transition runs detached from the caller (the law of whole transitions): cancelling
756    /// the caller abandons only the wait.
757    pub(crate) async fn admit_with_quota(
758        self: &Arc<Self>,
759        admission: Admission,
760    ) -> Result<SequenceVerdict> {
761        let clock = replay_clock(self.started_at, &self.clock);
762        self.admit_at(admission, clock).await
763    }
764
765    /// The admission transition: read the clock, retire the spent streams, classify, reserve
766    /// quota, update the table and stage the stream's record, as one transition (the
767    /// group-commit law).
768    ///
769    /// Law (Clock under the lock): `clock` is read only inside the critical section of
770    /// `state`, so the instants the quota table receives follow the order in which
771    /// transitions hold the lock. A monotonic clock then gives every quota record a
772    /// non-decreasing sequence of instants, and `MonotonicTimeRegressed` is unreachable;
773    /// an instant read before the lock could be overtaken by a later reading that locked
774    /// first (#953).
775    async fn admit_at<C>(
776        self: &Arc<Self>,
777        admission: Admission,
778        clock: C,
779    ) -> Result<SequenceVerdict>
780    where
781        C: FnOnce() -> ReplayInstant + rings_runtime::MaybeSend + 'static,
782    {
783        self.commit(move |replay, ledger| {
784            let now = clock();
785            ledger.retire_spent(now.wall_ms)?;
786            replay.admit_in(ledger, admission, now, None)
787        })
788        .await
789    }
790
791    /// The admission transition on the speculative state (load-bounds paper, Law 2). A
792    /// `relayed` delivery enters the stream's custody in the same record (the custody law of
793    /// `custody`); a live one leaves the custody as it is.
794    ///
795    /// Pre: the transition read the clock as `now` and retired what is spent at `now.wall_ms`
796    /// ([`Ledger::retire_spent`]), once.
797    ///
798    /// ```text
799    /// s ∉ table ── table full ─────────────────────▶ Err(StreamCapacityExceeded { λ/π, TableFull })
800    ///          └── accounting refuses π ───────────▶ Err(StreamCapacityExceeded { π, refusal })
801    /// observe(window(s)) ── Replay/Fork/Stale ─────▶ Err(…)
802    /// quota(origin) ── refused ────────────────────▶ Err(quota)
803    /// window(s) := next;  custody(s) += relayed;  charge(s) := (π(s), max(spent_at))
804    /// stage record(s) ──▶ Ok(verdict)
805    /// ```
806    fn admit_in(
807        &self,
808        ledger: &mut Ledger<'_>,
809        admission: Admission,
810        now: ReplayInstant,
811        relayed: Option<RelayDelivery>,
812    ) -> Result<SequenceVerdict> {
813        let Admission {
814            key,
815            quota_destination,
816            sequence,
817            digest,
818            charge,
819            byte_cost,
820            introducer,
821            spent_at_ms,
822        } = admission;
823        self.refuse_unavailable(ledger.store, ReplayTable::Receiver, key)?;
824        let previous = ledger.store.tables.receiver.get(&key);
825        if previous.is_none() {
826            ledger
827                .store
828                .admits_new_stream(ReplayTable::Receiver)
829                .and_then(|()| ledger.accounting.lock().admit(introducer))
830                .map_err(|refusal| Error::TransactionReplayStreamCapacityExceeded {
831                    introducer,
832                    refusal,
833                })?;
834        }
835        let (next, verdict) = observe(previous.cloned(), sequence, digest);
836        self.refuse_rejected(key, sequence, verdict)?;
837
838        let quota_key = OriginQuotaKey::new(
839            key.network_id,
840            key.origin_account,
841            quota_destination,
842            charge.lane,
843        );
844        let reservation = ledger.quota.reserve(
845            quota_key,
846            introducer,
847            charge.message_limit,
848            byte_cost,
849            now.quota,
850        );
851        match reservation {
852            Ok(reservation) => ledger.charged(reservation),
853            Err(error) => {
854                self.quota_counters.record(charge.lane, &error);
855                return Err(quota_admission_error(quota_key, byte_cost, error));
856            }
857        }
858        ledger.set_receiver(key, next);
859        if relayed.is_some() {
860            let mut custody = ledger
861                .store
862                .tables
863                .custody
864                .get(&key)
865                .cloned()
866                .unwrap_or_default();
867            custody.extend(relayed);
868            ledger.set_custody(key, custody);
869        }
870        let held = ledger.store.tables.charge(&key);
871        let stream_charge = StreamCharge {
872            introducer: held.map_or(introducer, |held| held.introducer),
873            spent_at_ms: held.map_or(spent_at_ms, |held| held.spent_at_ms.max(spent_at_ms)),
874        };
875        if held != Some(stream_charge) {
876            ledger.set_charge(key, stream_charge);
877        }
878        ledger.write(ledger.store.tables.receiver_record(&key)?);
879        Ok(verdict)
880    }
881
882    /// Refuse, and count, a verdict that does not permit dispatch: `Replay`, `Fork` (with its
883    /// evidence) or `Stale`, whichever window observed it.
884    fn refuse_rejected(
885        &self,
886        key: StreamKey,
887        sequence: u64,
888        verdict: SequenceVerdict,
889    ) -> Result<()> {
890        match verdict {
891            SequenceVerdict::First | SequenceVerdict::Advance | SequenceVerdict::Late => Ok(()),
892            SequenceVerdict::Replay => {
893                self.counters.replay.fetch_add(1, Ordering::Relaxed);
894                Err(Error::TransactionReplay { key, sequence })
895            }
896            SequenceVerdict::Fork { accepted, incoming } => {
897                self.counters.fork.fetch_add(1, Ordering::Relaxed);
898                Err(Error::TransactionSequenceFork {
899                    key,
900                    sequence,
901                    evidence: Box::new(TransactionForkEvidence { accepted, incoming }),
902                })
903            }
904            SequenceVerdict::Stale { retained_min } => {
905                self.counters.stale.fetch_add(1, Ordering::Relaxed);
906                Err(Error::TransactionSequenceStale {
907                    key,
908                    sequence,
909                    retained_min,
910                })
911            }
912        }
913    }
914
915    /// Admit a link-local transaction of stream `key` in `window`, the volatile window of that
916    /// stream on the link it arrived on (#1081; durable-records, Law Window by classification):
917    /// observe, read the quota clock and reserve quota under the lock, then advance the window.
918    ///
919    /// Nothing is written, and the verdict is returned at once: it rests on the link's volatile
920    /// window and the runtime-local quotas, never on a durable state. The quota reservation is
921    /// logged into the pending batch, if any, so a failed batch still rewinds the quota table
922    /// last first (the fail-closed law of [`commit`]); the admission itself stands. A refusal
923    /// leaves `window` and the quotas unchanged.
924    pub(crate) async fn admit_on_link(
925        &self,
926        window: &mut Option<SequenceState>,
927        admission: Admission,
928    ) -> Result<SequenceVerdict> {
929        let Admission {
930            key,
931            quota_destination,
932            sequence,
933            digest,
934            charge,
935            byte_cost,
936            introducer,
937            ..
938        } = admission;
939        let clock = replay_clock(self.started_at, &self.clock);
940        let mut state = self.state.lock().await;
941        let TransactionAdmissionState { quota, journal, .. } = &mut *state;
942        let (next, verdict) = observe(window.clone(), sequence, digest);
943        self.refuse_rejected(key, sequence, verdict)?;
944        let quota_key = OriginQuotaKey::new(
945            key.network_id,
946            key.origin_account,
947            quota_destination,
948            charge.lane,
949        );
950        let reservation = quota
951            .reserve(
952                quota_key,
953                introducer,
954                charge.message_limit,
955                byte_cost,
956                clock().quota,
957            )
958            .map_err(|error| {
959                self.quota_counters.record(charge.lane, &error);
960                quota_admission_error(quota_key, byte_cost, error)
961            })?;
962        journal.log_released_charge(reservation);
963        *window = Some(next);
964        Ok(verdict)
965    }
966
967    /// Test builds: admit `sequence` and `digest` of stream `key`, introduced by this node,
968    /// at quota instant zero and at the wall clock now.
969    #[cfg(test)]
970    async fn admit(
971        self: &Arc<Self>,
972        key: StreamKey,
973        sequence: u64,
974        digest: TransactionDigest,
975    ) -> Result<SequenceVerdict> {
976        let now_ms = crate::utils::get_epoch_ms();
977        let admission = Admission::for_test(key, sequence, digest, now_ms);
978        self.admit_at(admission, move || ReplayInstant {
979            quota: crate::message::OriginQuotaInstant::ZERO,
980            wall_ms: now_ms,
981        })
982        .await
983    }
984
985    #[cfg(all(test, not(target_family = "wasm")))]
986    pub(crate) async fn quota_record_count_for_test(&self) -> usize {
987        self.state.lock().await.quota.len()
988    }
989
990    /// The whole `(message, byte)` tokens `key`'s quota record held after its last admission.
991    #[cfg(all(test, feature = "dummy", not(target_family = "wasm")))]
992    pub(crate) async fn quota_tokens_for_test(&self, key: OriginQuotaKey) -> Option<(u128, u128)> {
993        self.state.lock().await.quota.whole_tokens(key)
994    }
995}
996
997#[cfg(test)]
998mod tests;
999
1000#[cfg(all(test, not(target_family = "wasm")))]
1001mod quota_admission_tests;
1002#[cfg(all(test, feature = "wasm", target_family = "wasm"))]
1003mod test_browser_store;
1004#[cfg(all(test, not(target_family = "wasm")))]
1005mod test_custody;
1006#[cfg(all(test, not(target_family = "wasm")))]
1007mod test_durable_throughput;
1008#[cfg(all(test, not(target_family = "wasm")))]
1009mod test_group_commit;
1010#[cfg(all(test, not(target_family = "wasm")))]
1011mod test_lease;
1012#[cfg(all(test, not(target_family = "wasm")))]
1013mod test_load_failures;
1014#[cfg(all(test, not(target_family = "wasm")))]
1015mod test_slot_accounting;
1016#[cfg(all(test, not(target_family = "wasm")))]
1017mod test_storage;
1018#[cfg(all(test, not(target_family = "wasm")))]
1019mod test_stream_failures;
1020#[cfg(all(test, not(target_family = "wasm")))]
1021mod test_whole_transitions;