Skip to main content

reef_core/runtime/
session.rs

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