Skip to main content

reef_core/runtime/
session.rs

1//! Exclusive session leases, sticky admission bindings, and targeted input.
2//!
3//! Four properties define the module: one active lease at a time, mutation only
4//! through a held lease, complete sticky binding sets, and FIFO targeted input.
5
6use std::collections::{BTreeMap, VecDeque};
7use std::error::Error;
8use std::fmt;
9use std::sync::{Arc, Mutex, MutexGuard};
10#[cfg(test)]
11use std::sync::{Barrier, TryLockError, mpsc};
12
13use crate::redact::Locked;
14use crate::state::session_state::{self, Writer};
15use crate::transcript::item::Item;
16use crate::transcript::store::{self, Snapshot, SnapshotReader, Store, Version};
17
18/// One opaque dependency identity in a session's complete sticky binding set.
19#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
20pub struct Binding {
21    name: String,
22    identity: String,
23}
24
25impl Binding {
26    /// Creates a complete non-empty binding.
27    ///
28    /// # Errors
29    ///
30    /// [`BindingError`] if either component is empty. A binding is the pair that
31    /// lets a session recognise the same dependency across successor Runs, and
32    /// half of one cannot do that: an empty name has nothing to match against,
33    /// and an empty identity would compare equal to every other empty identity.
34    pub fn new(name: String, identity: String) -> Result<Self, BindingError> {
35        if name.is_empty() || identity.is_empty() {
36            return Err(BindingError);
37        }
38        Ok(Self { name, identity })
39    }
40
41    /// Returns the dependency name.
42    #[must_use]
43    pub fn name(&self) -> &str {
44        &self.name
45    }
46
47    /// Returns the opaque continuity identity.
48    #[must_use]
49    pub fn identity(&self) -> &str {
50        &self.identity
51    }
52}
53
54/// A binding omitted its name or identity.
55#[derive(Clone, Copy, Debug, Eq, PartialEq)]
56pub struct BindingError;
57
58impl fmt::Display for BindingError {
59    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
60        formatter.write_str("session binding name and identity must be non-empty")
61    }
62}
63
64impl Error for BindingError {}
65
66/// A lease admission or mutation failure.
67#[derive(Clone, Debug, Eq, PartialEq)]
68#[non_exhaustive]
69pub enum LeaseError {
70    /// This lease has already released its authority.
71    Released,
72    /// Admission was already committed for this lease.
73    AlreadyAdmitted,
74    /// A complete binding set contained the same name twice.
75    DuplicateBinding(String),
76    /// The complete binding set differs from the session's sticky set.
77    BindingMismatch,
78    /// The underlying transcript rejected the mutation.
79    Transcript(store::Error),
80}
81
82impl fmt::Display for LeaseError {
83    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
84        match self {
85            Self::Released => formatter.write_str("session lease released"),
86            Self::AlreadyAdmitted => formatter.write_str("session lease already admitted"),
87            Self::DuplicateBinding(name) => write!(formatter, "duplicate session binding: {name}"),
88            Self::BindingMismatch => formatter.write_str("session binding mismatch"),
89            Self::Transcript(error) => error.fmt(formatter),
90        }
91    }
92}
93
94impl Error for LeaseError {
95    fn source(&self) -> Option<&(dyn Error + 'static)> {
96        match self {
97            Self::Transcript(error) => Some(error),
98            Self::Released
99            | Self::AlreadyAdmitted
100            | Self::DuplicateBinding(_)
101            | Self::BindingMismatch => None,
102        }
103    }
104}
105
106/// The lifecycle phase at which an input batch may be admitted.
107#[derive(Clone, Copy, Debug, Eq, PartialEq)]
108pub enum InputTarget {
109    /// Extend the active turn at its next legal step boundary.
110    NextStep,
111    /// Open a distinct turn after the active turn ends.
112    NextTurn,
113}
114
115/// A requested input batch contained no transcript items.
116#[derive(Clone, Copy, Debug, Eq, PartialEq)]
117pub struct EmptyInputBatchError;
118
119impl fmt::Display for EmptyInputBatchError {
120    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
121        formatter.write_str("input batch must not be empty")
122    }
123}
124
125impl Error for EmptyInputBatchError {}
126
127/// One owned, ordered input batch with an immutable admission target.
128#[derive(Clone, Debug)]
129pub struct InputBatch {
130    target: InputTarget,
131    items: Vec<Item>,
132}
133
134impl InputBatch {
135    /// Freezes an owned non-empty batch for one admission target.
136    ///
137    /// # Errors
138    ///
139    /// [`EmptyInputBatchError`] if `items` is empty. An empty batch would occupy
140    /// a place in the mailbox's FIFO order and then open a Turn or Step boundary
141    /// with nothing to admit, so it is refused at construction rather than
142    /// discarded later, where the discard would be invisible to whoever queued it.
143    pub fn new(target: InputTarget, items: Vec<Item>) -> Result<Self, EmptyInputBatchError> {
144        if items.is_empty() {
145            return Err(EmptyInputBatchError);
146        }
147        Ok(Self { target, items })
148    }
149
150    /// Returns the frozen target.
151    #[must_use]
152    pub const fn target(&self) -> InputTarget {
153        self.target
154    }
155
156    /// Returns the ordered owned payload by immutable view.
157    #[must_use]
158    pub fn items(&self) -> &[Item] {
159        &self.items
160    }
161
162    /// Transfers the frozen target and owned payload together.
163    #[must_use]
164    pub fn into_parts(self) -> (InputTarget, Vec<Item>) {
165        (self.target, self.items)
166    }
167}
168
169/// Thread-safe FIFO input storage with target-selective atomic claims.
170///
171/// # Panics
172///
173/// Every method here propagates a poisoned queue lock rather than recovering it,
174/// per the crate-level [lock-poisoning contract](crate#lock-poisoning). Nothing a
175/// caller passes can cause that: the queue holds owned [`InputBatch`] values and
176/// no foreign code runs under the lock.
177#[derive(Clone, Default)]
178pub struct InputMailbox {
179    batches: Arc<Mutex<VecDeque<InputBatch>>>,
180}
181
182impl fmt::Debug for InputMailbox {
183    /// Reports the queue depth at one non-blocking observation.
184    ///
185    /// The mailbox is the session's only concurrent write entry point, so a
186    /// formatter that waited for the queue lock could stall the very producer
187    /// it is describing. On contention it says so rather than guessing.
188    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
189        let mut mailbox = formatter.debug_struct("InputMailbox");
190        match self.batches.try_lock() {
191            Ok(batches) => mailbox.field("batches", &batches.len()),
192            Err(_contended_or_poisoned) => mailbox.field("batches", &Locked),
193        }
194        .finish()
195    }
196}
197
198impl InputMailbox {
199    /// Creates an empty mailbox attached to no Session.
200    ///
201    /// This is for a composition layer assembling its own queue — a test double,
202    /// or a staging buffer drained into a real inbox later. It is **not** how you
203    /// reach a running Run: [`Session::input_mailbox`] returns a handle onto the
204    /// Session's own queue, and a mailbox built here shares nothing with it, so
205    /// pushing to one succeeds and is never claimed by anybody.
206    #[must_use]
207    pub fn new() -> Self {
208        Self::default()
209    }
210
211    /// Moves one already-frozen owned batch into global FIFO order.
212    ///
213    /// # Panics
214    ///
215    /// If the queue lock is poisoned, as
216    /// [the mailbox's panic conditions](InputMailbox#panics) describe.
217    pub fn push(&self, batch: InputBatch) {
218        self.batches
219            .lock()
220            .expect("injection mailbox lock poisoned")
221            .push_back(batch);
222    }
223
224    /// Atomically removes the oldest batch for `target` without reordering peers.
225    ///
226    /// # Panics
227    ///
228    /// If the queue lock is poisoned, as
229    /// [the mailbox's panic conditions](InputMailbox#panics) describe.
230    #[must_use]
231    pub fn claim(&self, target: InputTarget) -> Option<InputBatch> {
232        let mut batches = self
233            .batches
234            .lock()
235            .expect("injection mailbox lock poisoned");
236        let index = batches.iter().position(|batch| batch.target == target)?;
237        batches.remove(index)
238    }
239
240    /// Atomically removes every currently queued batch in FIFO order.
241    ///
242    /// # Panics
243    ///
244    /// If the queue lock is poisoned, as
245    /// [the mailbox's panic conditions](InputMailbox#panics) describe.
246    #[must_use]
247    pub fn drain(&self) -> Vec<InputBatch> {
248        std::mem::take(
249            &mut *self
250                .batches
251                .lock()
252                .expect("injection mailbox lock poisoned"),
253        )
254        .into()
255    }
256
257    /// Returns the number of queued batches at one lock linearization point.
258    ///
259    /// # Panics
260    ///
261    /// If the queue lock is poisoned, as
262    /// [the mailbox's panic conditions](InputMailbox#panics) describe.
263    #[must_use]
264    pub fn len(&self) -> usize {
265        self.batches
266            .lock()
267            .expect("injection mailbox lock poisoned")
268            .len()
269    }
270
271    /// Reports whether the mailbox is empty at one lock linearization point.
272    ///
273    /// # Panics
274    ///
275    /// If the queue lock is poisoned, as
276    /// [the mailbox's panic conditions](InputMailbox#panics) describe.
277    #[must_use]
278    pub fn is_empty(&self) -> bool {
279        self.len() == 0
280    }
281}
282
283struct LeaseToken {
284    _identity: u8,
285}
286
287struct ActiveLease {
288    token: Arc<LeaseToken>,
289    admitted: bool,
290}
291
292struct Control {
293    active: Option<ActiveLease>,
294    bindings: BTreeMap<String, String>,
295}
296
297struct SessionInner {
298    id: String,
299    transcript: Store,
300    state: session_state::Store,
301    input_mailbox: InputMailbox,
302    /// The session's sole transcript-transaction authority.
303    ///
304    /// A live transcript mutation is a reserve-commit-publish transaction that
305    /// spans more than the store's own lock, so the session owns one outer lock
306    /// that every mutation path shares: the reservation controller, a direct
307    /// compare-and-set through [`Lease`], lease release, and successor
308    /// acquisition. Holding it session-wide rather than per controller instance
309    /// is what makes "no second mutation crosses an unresolved transaction"
310    /// true for callers the controller does not know about.
311    ///
312    /// Lock order is always this lock before [`SessionInner::control`], and no
313    /// path ever takes them in the other order.
314    transaction: Mutex<()>,
315    control: Mutex<Control>,
316    #[cfg(test)]
317    admit_before_control: Mutex<Option<Arc<TestOverlap>>>,
318    #[cfg(test)]
319    admit_with_control: Mutex<Option<Arc<TestOverlap>>>,
320    #[cfg(test)]
321    commit_overlap: Mutex<Option<Arc<TestOverlap>>>,
322    #[cfg(test)]
323    release_probe: Mutex<Option<Arc<TestOverlap>>>,
324    #[cfg(test)]
325    transaction_arrivals: Mutex<Option<mpsc::Sender<()>>>,
326}
327
328impl SessionInner {
329    /// Acquires the session's sole transcript-transaction authority.
330    ///
331    /// Every transcript mutation path funnels through here, so this is the one
332    /// place the session-wide transaction domain is entered. The lock is not
333    /// reentrant: a caller that already holds a transaction must reuse it rather
334    /// than open a second one.
335    ///
336    /// The controller resumes a reservation panic while its guard is still
337    /// alive, which poisons this lock. The lock guards no data of its own, and
338    /// such a transaction has already resolved every reservation it held and
339    /// either committed fully or not at all, so the poison is recovered instead
340    /// of propagated: a successor must still be able to mutate the transcript.
341    fn enter_transaction(&self) -> MutexGuard<'_, ()> {
342        #[cfg(test)]
343        probe_transaction_lock(self);
344        self.transaction
345            .lock()
346            .unwrap_or_else(|poisoned| poisoned.into_inner())
347    }
348
349    fn control(&self) -> MutexGuard<'_, Control> {
350        self.control.lock().expect("session control lock poisoned")
351    }
352}
353
354/// A long-lived conversation substrate with a single active lease.
355///
356/// # Panics
357///
358/// A session serializes lease admission and release behind one control lock, and
359/// every operation on a `Session` or its [`Lease`] that consults that lock
360/// propagates a poisoned one rather than recovering it, per the crate-level
361/// [lock-poisoning contract](crate#lock-poisoning). The lock guards only the
362/// active-lease slot and the sticky binding map, and no foreign code runs while
363/// it is held, so nothing a caller passes can poison it.
364///
365/// The session's separate transcript-transaction lock is the crate's one
366/// deliberate recovery, for the reason that contract records: a mutation is
367/// expected to unwind through it, and a successor must still be able to mutate
368/// the transcript afterwards.
369#[derive(Clone)]
370pub struct Session {
371    inner: Arc<SessionInner>,
372}
373
374impl fmt::Debug for Session {
375    /// Prints the session identity, which is what a session is addressed by.
376    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
377        formatter
378            .debug_struct("Session")
379            .field("id", &self.inner.id)
380            .finish()
381    }
382}
383
384impl Session {
385    /// Creates a session from an optional owned transcript snapshot.
386    ///
387    /// # The seed/live boundary lives with the caller
388    ///
389    /// `seed` is the replayed prefix, so this caller already holds both
390    /// coordinates the boundary can be named in: the prefix length, and the
391    /// [`Version`] the epoch resumes at. Both remain valid as live work
392    /// appends, and a composition layer that forks or resumes keeps whichever
393    /// its own persistence is keyed on.
394    ///
395    /// The transcript stores no such marker, because no core path treats a
396    /// replayed record differently from a live one: projection, the exchange
397    /// grammar and replay validity are all properties of the whole history.
398    /// Recording the boundary here would be storing a number core neither
399    /// produces nor consumes. Session trees, branching and branch replay are
400    /// composition-layer concerns built on top of these two coordinates.
401    #[must_use]
402    pub fn new(id: String, seed: Option<Snapshot>) -> Self {
403        let transcript = seed.map_or_else(Store::new, Store::restore);
404        Self {
405            inner: Arc::new(SessionInner {
406                id,
407                transcript,
408                state: session_state::Store::new(),
409                input_mailbox: InputMailbox::new(),
410                transaction: Mutex::new(()),
411                control: Mutex::new(Control {
412                    active: None,
413                    bindings: BTreeMap::new(),
414                }),
415                #[cfg(test)]
416                admit_before_control: Mutex::new(None),
417                #[cfg(test)]
418                admit_with_control: Mutex::new(None),
419                #[cfg(test)]
420                commit_overlap: Mutex::new(None),
421                #[cfg(test)]
422                release_probe: Mutex::new(None),
423                #[cfg(test)]
424                transaction_arrivals: Mutex::new(None),
425            }),
426        }
427    }
428
429    /// Returns this session's identity.
430    #[must_use]
431    pub fn id(&self) -> &str {
432        &self.inner.id
433    }
434
435    /// Returns read-only atomic transcript snapshot authority.
436    #[must_use]
437    pub fn transcript(&self) -> SnapshotReader {
438        self.inner.transcript.snapshot_reader()
439    }
440
441    /// Returns read-only owned session-state authority.
442    #[must_use]
443    pub fn state(&self) -> session_state::Reader {
444        self.inner.state.reader()
445    }
446
447    /// Returns the shared asynchronous input mailbox.
448    ///
449    /// **Shared, despite being returned by value.** [`InputMailbox`] is a
450    /// handle: this hands back another one onto *this* Session's queue, so
451    /// pushing to it reaches a Run that is already running, and two calls to
452    /// `input_mailbox` address the same queue.
453    ///
454    /// That matters because [`InputMailbox::new`] is also public, and a
455    /// mailbox built that way belongs to nobody. Pushing to it succeeds, returns
456    /// nothing, and is never claimed — the one way to inject input and observe
457    /// no error and no effect. If a batch you pushed never arrived, check that it
458    /// went through `session.input_mailbox()`.
459    #[must_use]
460    pub fn input_mailbox(&self) -> InputMailbox {
461        self.inner.input_mailbox.clone()
462    }
463
464    /// Atomically acquires the sole active lease, or returns `None` while busy.
465    ///
466    /// Acquisition waits for any in-flight transcript transaction to resolve, so
467    /// a successor can never observe a committed version whose reservations have
468    /// not yet published.
469    ///
470    /// # Panics
471    ///
472    /// If the session control lock is poisoned, as
473    /// [the session's panic conditions](Session#panics) describe.
474    #[must_use]
475    pub fn try_acquire(&self) -> Option<Lease> {
476        let _transaction = self.inner.enter_transaction();
477        let mut control = self.inner.control();
478        if control.active.is_some() {
479            return None;
480        }
481        let token = Arc::new(LeaseToken { _identity: 0 });
482        control.active = Some(ActiveLease {
483            token: Arc::clone(&token),
484            admitted: false,
485        });
486        Some(Lease {
487            inner: Arc::clone(&self.inner),
488            token,
489            state: self.inner.state.acquire(),
490        })
491    }
492}
493
494/// Exclusive, explicitly admitted mutation authority for one session use.
495pub struct Lease {
496    inner: Arc<SessionInner>,
497    token: Arc<LeaseToken>,
498    state: Writer,
499}
500
501impl fmt::Debug for Lease {
502    /// Prints the session this exclusive authority was taken over.
503    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
504        formatter
505            .debug_struct("Lease")
506            .field("session", &self.inner.id)
507            .finish()
508    }
509}
510
511impl Lease {
512    /// Atomically commits successful admission and the complete sticky binding set.
513    ///
514    /// # Errors
515    ///
516    /// - [`LeaseError::DuplicateBinding`], naming the repeated dependency, if
517    ///   `bindings` names one twice. Checked before the session is touched.
518    /// - [`LeaseError::Released`] if this lease is no longer the session's active
519    ///   one, which includes a lease that was released and a session that has
520    ///   since admitted a successor.
521    /// - [`LeaseError::AlreadyAdmitted`] if this lease already committed
522    ///   admission. Admission is once per lease, not idempotent, because the
523    ///   second call would be asking to re-freeze a binding set that a Run is
524    ///   already using.
525    /// - [`LeaseError::BindingMismatch`] if the session already carries a sticky
526    ///   set and `bindings` is not exactly that set. `bindings` must be
527    ///   *complete*: a subset mismatches, and so does an empty vector, because a
528    ///   session's continuity guarantee is that every dependency it was admitted
529    ///   with is still the same one. A session with no sticky set yet accepts any
530    ///   set, including an empty one, and adopts a non-empty one as its own.
531    ///
532    /// A failure commits nothing — neither the admitted flag nor the binding set
533    /// changes — so a caller may correct the set and try again on the same lease.
534    ///
535    /// # Panics
536    ///
537    /// If the session control lock is poisoned, as
538    /// [the session's panic conditions](Session#panics) describe. Admission also
539    /// asserts that the lease it verified under that lock is still the active one
540    /// when it marks it admitted; both hold the same guard, so failing that
541    /// assertion would be a defect in this crate rather than a caller error.
542    pub fn admit(&self, bindings: Vec<Binding>) -> Result<(), LeaseError> {
543        let presented = collect_bindings(bindings)?;
544        #[cfg(test)]
545        pause_at(&self.inner.admit_before_control);
546        let mut control = self.inner.control();
547        if active(&control, &self.token)?.admitted {
548            return Err(LeaseError::AlreadyAdmitted);
549        }
550        if !control.bindings.is_empty() && control.bindings != presented {
551            return Err(LeaseError::BindingMismatch);
552        }
553        #[cfg(test)]
554        pause_at(&self.inner.admit_with_control);
555        if !presented.is_empty() {
556            control.bindings = presented;
557        }
558        control
559            .active
560            .as_mut()
561            .expect("active lease was verified under the same lock")
562            .admitted = true;
563        Ok(())
564    }
565
566    /// Reports whether this still-active lease has synchronously committed admission.
567    ///
568    /// # Panics
569    ///
570    /// If the session control lock is poisoned, as
571    /// [the session's panic conditions](Session#panics) describe.
572    #[must_use]
573    pub fn is_admitted(&self) -> bool {
574        let control = self.inner.control();
575        control
576            .active
577            .as_ref()
578            .is_some_and(|active| Arc::ptr_eq(&active.token, &self.token) && active.admitted)
579    }
580
581    /// Returns this lease's mutable session-state capability.
582    #[must_use]
583    pub const fn state(&self) -> &Writer {
584        &self.state
585    }
586
587    /// Atomically captures the transcript; reads remain valid after release.
588    ///
589    /// # Errors
590    ///
591    /// [`store::Error::Poisoned`] if a transcript writer panicked while holding
592    /// the store lock. Release is deliberately not a failure here: this is a
593    /// read, and the whole point of an owned snapshot is that it stays usable
594    /// after the authority that captured it is gone.
595    pub fn transcript_snapshot(&self) -> Result<Snapshot, store::Error> {
596        self.inner.transcript.snapshot_reader().snapshot()
597    }
598
599    /// Opens the session's sole transcript transaction.
600    ///
601    /// Every transcript mutation, including the reservation controller's
602    /// reserve-commit-publish sequence, runs inside one of these. The returned
603    /// guard is the only route to a compare-and-set, so no caller can commit
604    /// outside the transaction domain, and a second mutation - a direct
605    /// compare-and-set, a release, or a successor acquisition - blocks until this
606    /// transaction resolves.
607    ///
608    /// A reservation callback holds no lease, so it cannot re-enter this
609    /// non-reentrant transaction from inside one.
610    pub(crate) fn begin_transaction(&self) -> Transaction<'_> {
611        Transaction {
612            _transaction: self.inner.enter_transaction(),
613            lease: self,
614        }
615    }
616
617    /// Appends an owned batch only at `expected`, inside its own transaction.
618    ///
619    /// # Errors
620    ///
621    /// [`LeaseError::Released`] if this lease is no longer the session's active
622    /// one, checked before the transcript is touched, so a stale authority never
623    /// mutates history. Otherwise [`LeaseError::Transcript`] carrying whatever
624    /// the store reported: a
625    /// [`VersionConflict`](store::Error::VersionConflict) if another writer
626    /// advanced past `expected`, a
627    /// [`VersionOverflow`](store::Error::VersionOverflow), or a
628    /// [`Poisoned`](store::Error::Poisoned) store. Every one of those leaves the
629    /// history unchanged.
630    ///
631    /// # Panics
632    ///
633    /// If the session control lock is poisoned, as
634    /// [the session's panic conditions](Session#panics) describe. Transcript
635    /// poisoning is reported instead as
636    /// [`LeaseError::Transcript`]`(`[`store::Error::Poisoned`]`)`.
637    pub fn append_batch_if_version(
638        &self,
639        items: Vec<Item>,
640        expected: Version,
641    ) -> Result<Version, LeaseError> {
642        self.begin_transaction()
643            .append_batch_if_version(items, expected)
644    }
645
646    /// Replaces the transcript only at `expected`, inside its own transaction.
647    ///
648    /// # Errors
649    ///
650    /// [`LeaseError::Released`] if this lease is no longer the session's active
651    /// one, or [`LeaseError::Transcript`] carrying a
652    /// [`VersionConflict`](store::Error::VersionConflict),
653    /// [`VersionOverflow`](store::Error::VersionOverflow), or
654    /// [`Poisoned`](store::Error::Poisoned) store. A refused replacement swaps
655    /// nothing, which is what lets a compaction be attempted against a live
656    /// session at all.
657    ///
658    /// # Panics
659    ///
660    /// If the session control lock is poisoned, as
661    /// [the session's panic conditions](Session#panics) describe. Transcript
662    /// poisoning is reported instead as
663    /// [`LeaseError::Transcript`]`(`[`store::Error::Poisoned`]`)`.
664    pub fn replace_if_version(
665        &self,
666        items: Vec<Item>,
667        expected: Version,
668    ) -> Result<Version, LeaseError> {
669        self.begin_transaction().replace_if_version(items, expected)
670    }
671
672    /// Idempotently revokes mutations and makes the session reusable.
673    ///
674    /// Release waits for any in-flight transcript transaction to resolve, so a
675    /// committed mutation always finishes publishing while its authority is
676    /// still live.
677    ///
678    /// # Panics
679    ///
680    /// If the session control lock is poisoned, as
681    /// [the session's panic conditions](Session#panics) describe. Because
682    /// [`Drop`] releases, a poisoned control lock also panics while a `Lease`
683    /// goes out of scope.
684    pub fn release(&self) {
685        let _transaction = self.inner.enter_transaction();
686        self.release_in_transaction();
687    }
688
689    fn release_in_transaction(&self) {
690        #[cfg(test)]
691        probe_control_lock(&self.inner);
692        let mut control = self.inner.control();
693        let owns = control
694            .active
695            .as_ref()
696            .is_some_and(|active| Arc::ptr_eq(&active.token, &self.token));
697        if owns {
698            self.state.release();
699            control.active = None;
700        }
701    }
702}
703
704impl Drop for Lease {
705    fn drop(&mut self) {
706        self.release();
707    }
708}
709
710/// The session's exclusive live transcript-mutation window.
711///
712/// Holding this guard is the sole way to reach a compare-and-set, so the
713/// reservation controller can reserve, commit, and publish without any other
714/// mutation path crossing the sequence. The lock order is always this guard
715/// before the session control lock.
716pub(crate) struct Transaction<'a> {
717    _transaction: MutexGuard<'a, ()>,
718    lease: &'a Lease,
719}
720
721impl Transaction<'_> {
722    /// Reads the live transcript version without materializing the history.
723    ///
724    /// The reservation controller needs the current version to build a mutation
725    /// fact and to drive its compare-and-set. Asking for a [`Snapshot`] instead
726    /// would deep-copy the whole history and discard everything but one integer,
727    /// which is exactly the cost this accessor exists to avoid.
728    /// Liveness is verified first, so a released lease cannot observe a version
729    /// it may no longer mutate. The value cannot go stale while this transaction
730    /// is held.
731    pub(crate) fn version(&self) -> Result<Version, LeaseError> {
732        let control = self.lease.inner.control();
733        active(&control, &self.lease.token)?;
734        self.lease
735            .inner
736            .transcript
737            .snapshot_reader()
738            .version()
739            .map_err(LeaseError::Transcript)
740    }
741
742    /// Appends an owned batch only at `expected`.
743    pub(crate) fn append_batch_if_version(
744        &self,
745        items: Vec<Item>,
746        expected: Version,
747    ) -> Result<Version, LeaseError> {
748        self.commit(|| {
749            self.lease
750                .inner
751                .transcript
752                .appender()
753                .append_batch_if_version(items, expected)
754        })
755    }
756
757    /// Replaces the transcript only at `expected`.
758    pub(crate) fn replace_if_version(
759        &self,
760        items: Vec<Item>,
761        expected: Version,
762    ) -> Result<Version, LeaseError> {
763        self.commit(|| {
764            self.lease
765                .inner
766                .transcript
767                .replacer()
768                .replace_if_version(items, expected)
769        })
770    }
771
772    fn commit<T>(
773        &self,
774        operation: impl FnOnce() -> Result<T, store::Error>,
775    ) -> Result<T, LeaseError> {
776        let control = self.lease.inner.control();
777        active(&control, &self.lease.token)?;
778        #[cfg(test)]
779        pause_at(&self.lease.inner.commit_overlap);
780        operation().map_err(LeaseError::Transcript)
781    }
782}
783
784fn collect_bindings(bindings: Vec<Binding>) -> Result<BTreeMap<String, String>, LeaseError> {
785    let mut presented = BTreeMap::new();
786    for binding in bindings {
787        if presented
788            .insert(binding.name.clone(), binding.identity)
789            .is_some()
790        {
791            return Err(LeaseError::DuplicateBinding(binding.name));
792        }
793    }
794    Ok(presented)
795}
796
797fn active<'a>(
798    control: &'a Control,
799    token: &Arc<LeaseToken>,
800) -> Result<&'a ActiveLease, LeaseError> {
801    control
802        .active
803        .as_ref()
804        .filter(|active| Arc::ptr_eq(&active.token, token))
805        .ok_or(LeaseError::Released)
806}
807
808#[cfg(test)]
809struct TestOverlap {
810    reached: Barrier,
811    proceed: Barrier,
812}
813
814/// Holds the mailbox lock so a `Debug` must observe contention.
815#[cfg(test)]
816pub(super) fn hold_mailbox_lock(mailbox: &InputMailbox, held: &Barrier, release: &Barrier) {
817    let _guard = mailbox
818        .batches
819        .lock()
820        .expect("injection mailbox lock poisoned");
821    held.wait();
822    release.wait();
823}
824
825#[cfg(test)]
826pub(super) struct TestOverlapControl {
827    overlap: Arc<TestOverlap>,
828    inner: Arc<SessionInner>,
829}
830
831#[cfg(test)]
832impl TestOverlapControl {
833    pub(super) fn wait_until_reached(&self) {
834        self.overlap.reached.wait();
835    }
836
837    pub(super) fn assert_control_is_locked(&self) {
838        assert!(matches!(
839            self.inner.control.try_lock(),
840            Err(TryLockError::WouldBlock)
841        ));
842    }
843
844    pub(super) fn proceed(&self) {
845        self.overlap.proceed.wait();
846    }
847}
848
849#[cfg(test)]
850fn pause_at(slot: &Mutex<Option<Arc<TestOverlap>>>) {
851    let overlap = slot.lock().expect("test overlap lock poisoned").take();
852    if let Some(overlap) = overlap {
853        overlap.reached.wait();
854        overlap.proceed.wait();
855    }
856}
857
858#[cfg(test)]
859fn probe_control_lock(inner: &SessionInner) {
860    let overlap = inner
861        .release_probe
862        .lock()
863        .expect("release probe lock poisoned")
864        .take();
865    if let Some(overlap) = overlap {
866        assert!(matches!(
867            inner.control.try_lock(),
868            Err(TryLockError::WouldBlock)
869        ));
870        overlap.reached.wait();
871        overlap.proceed.wait();
872    }
873}
874
875/// Signals one thread's arrival at an already-held transaction lock.
876///
877/// The probe runs before the arriving thread blocks, and it first proves the
878/// lock is held. A test that observes the signal therefore knows the arriving
879/// mutation cannot make progress until the transaction holder resolves, which is
880/// what makes "this path cannot cross an unresolved transaction" a deterministic
881/// assertion instead of a timing race.
882#[cfg(test)]
883fn probe_transaction_lock(inner: &SessionInner) {
884    let arrival = inner
885        .transaction_arrivals
886        .lock()
887        .expect("transaction arrival lock poisoned")
888        .take();
889    if let Some(arrival) = arrival {
890        assert!(matches!(
891            inner.transaction.try_lock(),
892            Err(TryLockError::WouldBlock)
893        ));
894        arrival
895            .send(())
896            .expect("the installing test observes the arrival");
897    }
898}
899
900/// Observes arrivals at an already-held transaction lock.
901///
902/// The signal is one-shot per [`Self::arm`], so a test can walk several distinct
903/// mutation paths into the same held transaction without a later, unblocked
904/// transaction tripping the probe.
905#[cfg(test)]
906pub(crate) struct TransactionArrival {
907    inner: Arc<SessionInner>,
908    sender: mpsc::Sender<()>,
909    arrived: mpsc::Receiver<()>,
910}
911
912#[cfg(test)]
913impl TransactionArrival {
914    /// Arms the signal for the next single thread to enter a transaction.
915    pub(crate) fn arm(&self) {
916        *self
917            .inner
918            .transaction_arrivals
919            .lock()
920            .expect("transaction arrival lock poisoned") = Some(self.sender.clone());
921    }
922
923    /// Blocks until one armed thread has reached the held transaction lock.
924    pub(crate) fn wait_until_blocked(&self) {
925        self.arrived
926            .recv()
927            .expect("the arriving thread signals before it blocks");
928    }
929}
930
931/// Creates an unarmed arrival probe for one session's transaction lock.
932#[cfg(test)]
933pub(crate) fn install_transaction_arrival(session: &Session) -> TransactionArrival {
934    let (sender, arrived) = mpsc::channel();
935    TransactionArrival {
936        inner: Arc::clone(&session.inner),
937        sender,
938        arrived,
939    }
940}
941
942#[cfg(test)]
943fn install_overlap(
944    session: &Session,
945    slot: &Mutex<Option<Arc<TestOverlap>>>,
946) -> TestOverlapControl {
947    let overlap = Arc::new(TestOverlap {
948        reached: Barrier::new(2),
949        proceed: Barrier::new(2),
950    });
951    *slot.lock().expect("test overlap lock poisoned") = Some(Arc::clone(&overlap));
952    TestOverlapControl {
953        overlap,
954        inner: Arc::clone(&session.inner),
955    }
956}
957
958#[cfg(test)]
959pub(super) fn install_admit_before_control(session: &Session) -> TestOverlapControl {
960    install_overlap(session, &session.inner.admit_before_control)
961}
962
963#[cfg(test)]
964pub(super) fn install_admit_with_control(session: &Session) -> TestOverlapControl {
965    install_overlap(session, &session.inner.admit_with_control)
966}
967
968#[cfg(test)]
969pub(super) fn install_commit_overlap(session: &Session) -> TestOverlapControl {
970    install_overlap(session, &session.inner.commit_overlap)
971}
972
973#[cfg(test)]
974pub(super) fn install_release_probe(session: &Session) -> TestOverlapControl {
975    install_overlap(session, &session.inner.release_probe)
976}