reef-core 0.4.0

Provider-neutral primitives for building LLM agents: run lifecycle, transcript, tools, hooks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
//! Exclusive session leases, synchronous admission, and targeted input.
//!
//! Four properties define the module: one active lease at a time, mutation only
//! through a held lease, an explicit admission barrier, and FIFO targeted input.

use std::collections::VecDeque;
use std::error::Error;
use std::fmt;
use std::sync::{Arc, Mutex, MutexGuard};
#[cfg(test)]
use std::sync::{Barrier, TryLockError, mpsc};

use crate::redact::Locked;
use crate::state::session_state::{self, Writer};
use crate::transcript::item::Item;
use crate::transcript::store::{self, Snapshot, SnapshotReader, Store, Version};

/// A lease admission or mutation failure.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum LeaseError {
    /// This lease has already released its authority.
    Released,
    /// Admission was already committed for this lease.
    AlreadyAdmitted,
    /// The underlying transcript rejected the mutation.
    Transcript(store::Error),
}

impl fmt::Display for LeaseError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Released => formatter.write_str("session lease released"),
            Self::AlreadyAdmitted => formatter.write_str("session lease already admitted"),
            Self::Transcript(error) => error.fmt(formatter),
        }
    }
}

impl Error for LeaseError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Transcript(error) => Some(error),
            Self::Released | Self::AlreadyAdmitted => None,
        }
    }
}

/// The lifecycle phase at which an input batch may be admitted.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum InputTarget {
    /// Extend the active turn at its next legal step boundary.
    NextStep,
    /// Open a distinct turn after the active turn ends.
    NextTurn,
}

/// A requested input batch contained no transcript items.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct EmptyInputBatchError;

impl fmt::Display for EmptyInputBatchError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("input batch must not be empty")
    }
}

impl Error for EmptyInputBatchError {}

/// One owned, ordered input batch with an immutable admission target.
#[derive(Clone)]
pub struct InputBatch {
    target: InputTarget,
    items: Vec<Item>,
    /// Session-global position assigned afresh whenever the batch is pushed.
    ///
    /// This belongs to the mailbox implementation rather than the public value:
    /// `Debug` deliberately omits it, and a clone pushed later receives a new
    /// position. An active conserved claim retains it only so Drop can restore
    /// the batch where that push originally placed it.
    enqueue_sequence: u64,
}

impl fmt::Debug for InputBatch {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("InputBatch")
            .field("target", &self.target)
            .field("items", &self.items)
            .finish()
    }
}

impl InputBatch {
    /// Freezes an owned non-empty batch for one admission target.
    ///
    /// # Errors
    ///
    /// [`EmptyInputBatchError`] if `items` is empty. An empty batch would occupy
    /// a place in the mailbox's FIFO order and then open a Turn or Step boundary
    /// with nothing to admit, so it is refused at construction rather than
    /// discarded later, where the discard would be invisible to whoever queued it.
    pub fn new(target: InputTarget, items: Vec<Item>) -> Result<Self, EmptyInputBatchError> {
        if items.is_empty() {
            return Err(EmptyInputBatchError);
        }
        Ok(Self {
            target,
            items,
            enqueue_sequence: 0,
        })
    }

    /// Returns the frozen target.
    #[must_use]
    pub const fn target(&self) -> InputTarget {
        self.target
    }

    /// Returns the ordered owned payload by immutable view.
    #[must_use]
    pub fn items(&self) -> &[Item] {
        &self.items
    }

    /// Transfers the frozen target and owned payload together.
    #[must_use]
    pub fn into_parts(self) -> (InputTarget, Vec<Item>) {
        (self.target, self.items)
    }
}

/// Thread-safe FIFO input storage with target-selective atomic claims.
///
/// # Conservation
///
/// A batch a Run claims from a Session's mailbox ends in exactly one of three
/// states: committed to that Session's transcript, refused by an
/// [`InputAdmitDecision::Reject`](super::hook::InputAdmitDecision::Reject), or —
/// when its admission ends any other way, including cancellation, a hook
/// contract error, a pre-commit transcript failure, or a panic — restored to
/// this mailbox in its original enqueue position, unrewritten, for a later
/// eligible boundary or a successor Run to claim. While an admission is in
/// flight the batch is in none of those places, so a concurrent
/// [`len`](Self::len), [`drain`](Self::drain) or [`claim`](Self::claim) may
/// briefly not see it; read the mailbox after the Run's terminal is resolved to
/// observe the settled state. This public [`claim`](Self::claim) hands the batch
/// over outright and restores nothing.
///
/// # Panics
///
/// Every method here propagates a poisoned queue lock rather than recovering it,
/// per the crate-level [lock-poisoning contract](crate#lock-poisoning). Nothing a
/// caller passes can cause that: the queue holds owned [`InputBatch`] values and
/// no foreign code runs under the lock.
#[derive(Clone, Default)]
pub struct InputMailbox {
    batches: Arc<Mutex<Queue>>,
}

/// The mailbox's queue, ordered by a private monotonic enqueue sequence.
///
/// `push` appends with the next sequence, so entries stay sorted by it, and a
/// restored batch is reinserted by the sequence it was enqueued with. The
/// sequence is what keeps a restore from reordering a batch against interleaved
/// batches of the other target: claims are target-selective, so the front of
/// the queue is not where a claimed batch came from.
#[derive(Default)]
struct Queue {
    next: u64,
    entries: VecDeque<InputBatch>,
}

impl fmt::Debug for InputMailbox {
    /// Reports the queue depth at one non-blocking observation.
    ///
    /// The mailbox is the session's only concurrent write entry point, so a
    /// formatter that waited for the queue lock could stall the very producer
    /// it is describing. On contention it says so rather than guessing.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut mailbox = formatter.debug_struct("InputMailbox");
        match self.batches.try_lock() {
            Ok(queue) => mailbox.field("batches", &queue.entries.len()),
            Err(_contended_or_poisoned) => mailbox.field("batches", &Locked),
        }
        .finish()
    }
}

impl InputMailbox {
    /// Creates an empty mailbox attached to no Session.
    ///
    /// This is for a composition layer assembling its own queue — a test double,
    /// or a staging buffer drained into a real inbox later. It is **not** how you
    /// reach a running Run: [`Session::input_mailbox`] returns a handle onto the
    /// Session's own queue, and a mailbox built here shares nothing with it, so
    /// pushing to one succeeds and is never claimed by anybody.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Moves one already-frozen owned batch into global FIFO order.
    ///
    /// # Panics
    ///
    /// If the queue lock is poisoned, as
    /// [the mailbox's panic conditions](InputMailbox#panics) describe.
    pub fn push(&self, mut batch: InputBatch) {
        let mut queue = self.lock();
        batch.enqueue_sequence = queue.next;
        queue.next += 1;
        queue.entries.push_back(batch);
    }

    /// Atomically removes the oldest batch for `target` without reordering peers.
    ///
    /// The batch is handed over outright: a caller that claims it owns it, and
    /// the mailbox does not take it back. The conservation guarantee in the
    /// [type-level documentation](InputMailbox#conservation) is about the
    /// claims a Run makes, not this one.
    ///
    /// # Panics
    ///
    /// If the queue lock is poisoned, as
    /// [the mailbox's panic conditions](InputMailbox#panics) describe.
    #[must_use]
    pub fn claim(&self, target: InputTarget) -> Option<InputBatch> {
        self.take(target)
    }

    /// Claims the oldest batch for `target` under a restore-on-drop guard.
    ///
    /// The returned [`Claim`] puts the original batch back at its enqueue
    /// position unless it is [settled](Claim::settle) first, so an admission
    /// that ends any way other than a commit or a refusal loses nothing.
    pub(crate) fn claim_conserved(&self, target: InputTarget) -> Option<Claim<'_>> {
        self.take(target).map(|batch| Claim {
            mailbox: self,
            batch: Some(batch),
        })
    }

    fn take(&self, target: InputTarget) -> Option<InputBatch> {
        let mut queue = self.lock();
        let index = queue
            .entries
            .iter()
            .position(|batch| batch.target == target)?;
        queue.entries.remove(index)
    }

    /// Reinserts a batch immediately before the first one enqueued after it.
    fn restore(&self, batch: InputBatch) {
        let mut queue = self.lock();
        let index = queue
            .entries
            .partition_point(|queued| queued.enqueue_sequence < batch.enqueue_sequence);
        queue.entries.insert(index, batch);
    }

    /// Atomically removes every currently queued batch in FIFO order.
    ///
    /// # Panics
    ///
    /// If the queue lock is poisoned, as
    /// [the mailbox's panic conditions](InputMailbox#panics) describe.
    #[must_use]
    pub fn drain(&self) -> Vec<InputBatch> {
        self.lock().entries.drain(..).collect()
    }

    /// Returns the number of queued batches at one lock linearization point.
    ///
    /// # Panics
    ///
    /// If the queue lock is poisoned, as
    /// [the mailbox's panic conditions](InputMailbox#panics) describe.
    #[must_use]
    pub fn len(&self) -> usize {
        self.lock().entries.len()
    }

    /// Reports whether the mailbox is empty at one lock linearization point.
    ///
    /// # Panics
    ///
    /// If the queue lock is poisoned, as
    /// [the mailbox's panic conditions](InputMailbox#panics) describe.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    fn lock(&self) -> MutexGuard<'_, Queue> {
        self.batches
            .lock()
            .expect("injection mailbox lock poisoned")
    }
}

/// One batch a Run has claimed and not yet settled.
///
/// Dropping an unsettled claim restores its original batch to the mailbox it
/// came from, at the position it was enqueued in. Admission settles the claim at
/// exactly two points: the transcript compare-and-set that commits the batch,
/// and a registration's refusal. Every other exit — an error return, a
/// cancellation, an unwind — reaches the drop with the batch still held.
pub(crate) struct Claim<'a> {
    mailbox: &'a InputMailbox,
    batch: Option<InputBatch>,
}

impl Claim<'_> {
    /// Returns the claimed batch, as it was pushed.
    pub(crate) const fn batch(&self) -> &InputBatch {
        self.batch
            .as_ref()
            .expect("an unsettled claim holds its batch")
    }

    /// Ends the claim in a terminal state and hands back the original batch.
    pub(crate) const fn settle(&mut self) -> InputBatch {
        self.batch.take().expect("a claim settles at most once")
    }
}

impl Drop for Claim<'_> {
    fn drop(&mut self) {
        if let Some(batch) = self.batch.take() {
            self.mailbox.restore(batch);
        }
    }
}

struct LeaseToken {
    _identity: u8,
}

struct ActiveLease {
    token: Arc<LeaseToken>,
    admitted: bool,
}

struct Control {
    active: Option<ActiveLease>,
}

struct SessionInner {
    id: String,
    transcript: Store,
    state: session_state::Store,
    input_mailbox: InputMailbox,
    /// The session's sole transcript-transaction authority.
    ///
    /// A hook-governed live transcript mutation is a reserve-commit-publish
    /// transaction that spans more than the store's own lock, so the session owns
    /// one outer lock that every mutation path shares: the reservation controller,
    /// a direct compare-and-set through [`Lease`], lease release, and successor
    /// acquisition. Holding it session-wide rather than per controller instance
    /// is what makes "no second mutation crosses an unresolved transaction"
    /// true for callers the controller does not know about.
    ///
    /// Lock order is always this lock before [`SessionInner::control`], and no
    /// path ever takes them in the other order.
    transaction: Mutex<()>,
    control: Mutex<Control>,
    #[cfg(test)]
    admit_before_control: Mutex<Option<Arc<TestOverlap>>>,
    #[cfg(test)]
    admit_with_control: Mutex<Option<Arc<TestOverlap>>>,
    #[cfg(test)]
    commit_overlap: Mutex<Option<Arc<TestOverlap>>>,
    #[cfg(test)]
    release_probe: Mutex<Option<Arc<TestOverlap>>>,
    #[cfg(test)]
    transaction_arrivals: Mutex<Option<mpsc::Sender<()>>>,
}

impl SessionInner {
    /// Acquires the session's sole transcript-transaction authority.
    ///
    /// Every transcript mutation path funnels through here, so this is the one
    /// place the session-wide transaction domain is entered. The lock is not
    /// reentrant: a caller that already holds a transaction must reuse it rather
    /// than open a second one.
    ///
    /// The controller resumes a reservation panic while its guard is still
    /// alive, which poisons this lock. The lock guards no data of its own, and
    /// such a transaction has already resolved every reservation it held and
    /// either committed fully or not at all, so the poison is recovered instead
    /// of propagated: a successor must still be able to mutate the transcript.
    fn enter_transaction(&self) -> MutexGuard<'_, ()> {
        #[cfg(test)]
        probe_transaction_lock(self);
        self.transaction
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    fn control(&self) -> MutexGuard<'_, Control> {
        self.control.lock().expect("session control lock poisoned")
    }
}

/// A long-lived conversation substrate with a single active lease.
///
/// # Panics
///
/// A session serializes lease admission and release behind one control lock, and
/// every operation on a `Session` or its [`Lease`] that consults that lock
/// propagates a poisoned one rather than recovering it, per the crate-level
/// [lock-poisoning contract](crate#lock-poisoning). The lock guards only the
/// active-lease slot, and no foreign code runs while it is held, so nothing a
/// caller passes can poison it.
///
/// The session's separate transcript-transaction lock is the crate's one
/// deliberate recovery, for the reason that contract records: a mutation is
/// expected to unwind through it, and a successor must still be able to mutate
/// the transcript afterwards.
#[derive(Clone)]
pub struct Session {
    inner: Arc<SessionInner>,
}

impl fmt::Debug for Session {
    /// Prints the session identity, which is what a session is addressed by.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Session")
            .field("id", &self.inner.id)
            .finish()
    }
}

impl Session {
    /// Creates a session from an optional owned transcript snapshot.
    ///
    /// # The seed/live boundary lives with the caller
    ///
    /// `seed` is the replayed prefix, so this caller already holds both
    /// coordinates the boundary can be named in: the prefix length, and the
    /// [`Version`] the epoch resumes at. Both remain valid as live work
    /// appends, and a composition layer that forks or resumes keeps whichever
    /// its own persistence is keyed on.
    ///
    /// The transcript stores no such marker, because no core path treats a
    /// replayed record differently from a live one: projection, the exchange
    /// grammar and replay validity are all properties of the whole history.
    /// Recording the boundary here would be storing a number core neither
    /// produces nor consumes. Session trees, branching and branch replay are
    /// composition-layer concerns built on top of these two coordinates.
    #[must_use]
    pub fn new(id: String, seed: Option<Snapshot>) -> Self {
        let transcript = seed.map_or_else(Store::new, Store::restore);
        Self {
            inner: Arc::new(SessionInner {
                id,
                transcript,
                state: session_state::Store::new(),
                input_mailbox: InputMailbox::new(),
                transaction: Mutex::new(()),
                control: Mutex::new(Control { active: None }),
                #[cfg(test)]
                admit_before_control: Mutex::new(None),
                #[cfg(test)]
                admit_with_control: Mutex::new(None),
                #[cfg(test)]
                commit_overlap: Mutex::new(None),
                #[cfg(test)]
                release_probe: Mutex::new(None),
                #[cfg(test)]
                transaction_arrivals: Mutex::new(None),
            }),
        }
    }

    /// Returns this session's identity.
    #[must_use]
    pub fn id(&self) -> &str {
        &self.inner.id
    }

    /// Returns read-only atomic transcript snapshot authority.
    #[must_use]
    pub fn transcript(&self) -> SnapshotReader {
        self.inner.transcript.snapshot_reader()
    }

    /// Returns read-only owned session-state authority.
    #[must_use]
    pub fn state(&self) -> session_state::Reader {
        self.inner.state.reader()
    }

    /// Returns the shared asynchronous input mailbox.
    ///
    /// **Shared, despite being returned by value.** [`InputMailbox`] is a
    /// handle: this hands back another one onto *this* Session's queue, so
    /// pushing to it reaches a Run that is already running, and two calls to
    /// `input_mailbox` address the same queue.
    ///
    /// The queue belongs to the Session, not to its current Run or lease. Releasing
    /// a lease does not drain unclaimed batches: a successor Run on this Session
    /// may claim them at their next eligible boundary. Call [`InputMailbox::drain`]
    /// explicitly before starting that successor when the composition layer wants
    /// a Run-local queue instead.
    ///
    /// That matters because [`InputMailbox::new`] is also public, and a
    /// mailbox built that way belongs to nobody. Pushing to it succeeds, returns
    /// nothing, and is never claimed — the one way to inject input and observe
    /// no error and no effect. If a batch you pushed never arrived, check that it
    /// went through `session.input_mailbox()`.
    #[must_use]
    pub fn input_mailbox(&self) -> InputMailbox {
        self.inner.input_mailbox.clone()
    }

    /// Atomically acquires the sole active lease, or returns `None` while busy.
    ///
    /// Acquisition waits for any in-flight transcript transaction to resolve, so
    /// a successor can never observe a committed version whose reservations have
    /// not yet published.
    ///
    /// # Panics
    ///
    /// If the session control lock is poisoned, as
    /// [the session's panic conditions](Session#panics) describe.
    #[must_use]
    pub fn try_acquire(&self) -> Option<Lease> {
        let _transaction = self.inner.enter_transaction();
        let mut control = self.inner.control();
        if control.active.is_some() {
            return None;
        }
        let token = Arc::new(LeaseToken { _identity: 0 });
        control.active = Some(ActiveLease {
            token: Arc::clone(&token),
            admitted: false,
        });
        Some(Lease {
            inner: Arc::clone(&self.inner),
            token,
            state: self.inner.state.acquire(),
        })
    }
}

/// Exclusive, explicitly admitted mutation authority for one session use.
pub struct Lease {
    inner: Arc<SessionInner>,
    token: Arc<LeaseToken>,
    state: Writer,
}

impl fmt::Debug for Lease {
    /// Prints the session this exclusive authority was taken over.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Lease")
            .field("session", &self.inner.id)
            .finish()
    }
}

impl Lease {
    /// Atomically commits successful admission for this lease.
    ///
    /// This is a lifecycle barrier, not a dependency-continuity policy. A
    /// composition-layer launcher that needs continuity must validate its own
    /// metadata before calling [`Agent::start`](crate::runtime::agent::Agent::start);
    /// it cannot share this Session's private control lock.
    ///
    /// # Errors
    ///
    /// - [`LeaseError::Released`] if this lease is no longer the session's active
    ///   one, which includes a lease that was released and a session that has
    ///   since admitted a successor.
    /// - [`LeaseError::AlreadyAdmitted`] if this lease already committed
    ///   admission. Admission remains once per lease rather than idempotent.
    ///
    /// A failure leaves the admitted flag unchanged.
    ///
    /// # Panics
    ///
    /// If the session control lock is poisoned, as
    /// [the session's panic conditions](Session#panics) describe. Admission also
    /// asserts that the lease it verified under that lock is still the active one
    /// when it marks it admitted; both hold the same guard, so failing that
    /// assertion would be a defect in this crate rather than a caller error.
    pub fn admit(&self) -> Result<(), LeaseError> {
        #[cfg(test)]
        pause_at(&self.inner.admit_before_control);
        let mut control = self.inner.control();
        if active(&control, &self.token)?.admitted {
            return Err(LeaseError::AlreadyAdmitted);
        }
        #[cfg(test)]
        pause_at(&self.inner.admit_with_control);
        control
            .active
            .as_mut()
            .expect("active lease was verified under the same lock")
            .admitted = true;
        Ok(())
    }

    /// Reports whether this still-active lease has synchronously committed admission.
    ///
    /// # Panics
    ///
    /// If the session control lock is poisoned, as
    /// [the session's panic conditions](Session#panics) describe.
    #[must_use]
    pub fn is_admitted(&self) -> bool {
        let control = self.inner.control();
        control
            .active
            .as_ref()
            .is_some_and(|active| Arc::ptr_eq(&active.token, &self.token) && active.admitted)
    }

    /// Returns this lease's mutable session-state capability.
    #[must_use]
    pub const fn state(&self) -> &Writer {
        &self.state
    }

    /// Atomically captures the transcript; reads remain valid after release.
    ///
    /// # Errors
    ///
    /// [`store::Error::Poisoned`] if a transcript writer panicked while holding
    /// the store lock. Release is deliberately not a failure here: this is a
    /// read, and the shared immutable snapshot stays usable after the authority
    /// that captured it is gone.
    pub fn transcript_snapshot(&self) -> Result<Snapshot, store::Error> {
        self.inner.transcript.snapshot_reader().snapshot()
    }

    pub(crate) fn transcript_reader(&self) -> SnapshotReader {
        self.inner.transcript.snapshot_reader()
    }

    pub(crate) fn fork_transcript(&self) -> Result<Store, store::Error> {
        self.inner.transcript.fork()
    }

    /// Opens the session's sole transcript transaction.
    ///
    /// Every transcript mutation, including the reservation controller's
    /// reserve-commit-publish sequence, runs inside one of these. The returned
    /// guard is the only route to a compare-and-set, so no caller can commit
    /// outside the transaction domain, and a second mutation - a direct
    /// compare-and-set, a release, or a successor acquisition - blocks until this
    /// transaction resolves.
    ///
    /// A reservation callback holds no lease, so it cannot re-enter this
    /// non-reentrant transaction from inside one.
    pub(crate) fn begin_transaction(&self) -> Transaction<'_> {
        Transaction {
            _transaction: self.inner.enter_transaction(),
            lease: self,
        }
    }

    /// Appends an owned batch only at `expected`, inside its own transaction.
    ///
    /// This is a direct composition-layer mutation. It shares the Session's
    /// transaction authority with the Agent runtime, so it waits for any
    /// unresolved transcript reservation, but a [`Lease`] carries no Agent hook
    /// registry and this method does not invoke
    /// [`TranscriptHooks`](super::hook::TranscriptHooks). A caller whose
    /// persistence must include this mutation wraps the compare-and-set in its
    /// own reserve/publish-or-abort protocol.
    ///
    /// # Errors
    ///
    /// [`LeaseError::Released`] if this lease is no longer the session's active
    /// one, checked before the transcript is touched, so a stale authority never
    /// mutates history. Otherwise [`LeaseError::Transcript`] carrying whatever
    /// the store reported: a
    /// [`VersionConflict`](store::Error::VersionConflict) if another writer
    /// advanced past `expected`, a
    /// [`VersionOverflow`](store::Error::VersionOverflow), or a
    /// [`Poisoned`](store::Error::Poisoned) store. Every one of those leaves the
    /// history unchanged.
    ///
    /// # Panics
    ///
    /// If the session control lock is poisoned, as
    /// [the session's panic conditions](Session#panics) describe. Transcript
    /// poisoning is reported instead as
    /// [`LeaseError::Transcript`]`(`[`store::Error::Poisoned`]`)`.
    pub fn append_batch_if_version(
        &self,
        items: Vec<Item>,
        expected: Version,
    ) -> Result<Version, LeaseError> {
        self.begin_transaction()
            .append_batch_if_version(items, expected)
    }

    /// Replaces the transcript only at `expected`, inside its own transaction.
    ///
    /// Like [`Self::append_batch_if_version`], this is a direct composition-layer
    /// mutation: it shares the Session transaction authority but does not invoke
    /// [`TranscriptHooks`](super::hook::TranscriptHooks). A caller whose
    /// persistence must include the replacement owns its reserve/publish-or-abort
    /// protocol.
    ///
    /// # Errors
    ///
    /// [`LeaseError::Released`] if this lease is no longer the session's active
    /// one, or [`LeaseError::Transcript`] carrying a
    /// [`VersionConflict`](store::Error::VersionConflict),
    /// [`VersionOverflow`](store::Error::VersionOverflow), or
    /// [`Poisoned`](store::Error::Poisoned) store. A refused replacement swaps
    /// nothing, which is what lets a compaction be attempted against a live
    /// session at all.
    ///
    /// # Panics
    ///
    /// If the session control lock is poisoned, as
    /// [the session's panic conditions](Session#panics) describe. Transcript
    /// poisoning is reported instead as
    /// [`LeaseError::Transcript`]`(`[`store::Error::Poisoned`]`)`.
    pub fn replace_if_version(
        &self,
        items: Vec<Item>,
        expected: Version,
    ) -> Result<Version, LeaseError> {
        self.begin_transaction().replace_if_version(items, expected)
    }

    /// Idempotently revokes mutations and makes the session reusable.
    ///
    /// Release waits for any in-flight transcript transaction to resolve, so a
    /// controller-managed commit always finishes publishing while its authority
    /// is still live, and a direct compare-and-set always returns first.
    ///
    /// # Panics
    ///
    /// If the session control lock is poisoned, as
    /// [the session's panic conditions](Session#panics) describe. Because
    /// [`Drop`] releases, a poisoned control lock also panics while a `Lease`
    /// goes out of scope.
    pub fn release(&self) {
        let _transaction = self.inner.enter_transaction();
        self.release_in_transaction();
    }

    fn release_in_transaction(&self) {
        #[cfg(test)]
        probe_control_lock(&self.inner);
        let mut control = self.inner.control();
        let owns = control
            .active
            .as_ref()
            .is_some_and(|active| Arc::ptr_eq(&active.token, &self.token));
        if owns {
            self.state.release();
            control.active = None;
        }
    }
}

impl Drop for Lease {
    fn drop(&mut self) {
        self.release();
    }
}

/// The session's exclusive live transcript-mutation window.
///
/// Holding this guard is the sole way to reach a compare-and-set, so the
/// reservation controller can reserve, commit, and publish without any other
/// mutation path crossing the sequence. The lock order is always this guard
/// before the session control lock.
pub(crate) struct Transaction<'a> {
    _transaction: MutexGuard<'a, ()>,
    lease: &'a Lease,
}

impl Transaction<'_> {
    /// Reads the live transcript version without materializing the history.
    ///
    /// Liveness is verified first, so a released lease cannot observe a version
    /// it may no longer mutate. The value cannot go stale while this transaction
    /// is held.
    pub(crate) fn version(&self) -> Result<Version, LeaseError> {
        let control = self.lease.inner.control();
        active(&control, &self.lease.token)?;
        self.lease
            .inner
            .transcript
            .snapshot_reader()
            .version()
            .map_err(LeaseError::Transcript)
    }

    /// Captures live transcript truth while this transaction excludes mutations.
    pub(crate) fn snapshot(&self) -> Result<Snapshot, LeaseError> {
        let control = self.lease.inner.control();
        active(&control, &self.lease.token)?;
        self.lease
            .inner
            .transcript
            .snapshot_reader()
            .snapshot()
            .map_err(LeaseError::Transcript)
    }

    /// Appends an owned batch only at `expected`.
    pub(crate) fn append_batch_if_version(
        &self,
        items: Vec<Item>,
        expected: Version,
    ) -> Result<Version, LeaseError> {
        self.commit(|| {
            self.lease
                .inner
                .transcript
                .appender()
                .append_batch_if_version(items, expected)
        })
    }

    /// Replaces the transcript only at `expected`.
    pub(crate) fn replace_if_version(
        &self,
        items: Vec<Item>,
        expected: Version,
    ) -> Result<Version, LeaseError> {
        self.commit(|| {
            self.lease
                .inner
                .transcript
                .replacer()
                .replace_if_version(items, expected)
        })
    }

    /// Installs an already-shared replacement only at `expected`.
    pub(crate) fn install_snapshot(
        &self,
        snapshot: Snapshot,
        expected: Version,
    ) -> Result<Version, LeaseError> {
        self.commit(|| {
            self.lease
                .inner
                .transcript
                .replacer()
                .install_snapshot_if_version(snapshot, expected)
        })
    }

    fn commit<T>(
        &self,
        operation: impl FnOnce() -> Result<T, store::Error>,
    ) -> Result<T, LeaseError> {
        let control = self.lease.inner.control();
        active(&control, &self.lease.token)?;
        #[cfg(test)]
        pause_at(&self.lease.inner.commit_overlap);
        operation().map_err(LeaseError::Transcript)
    }
}

fn active<'a>(
    control: &'a Control,
    token: &Arc<LeaseToken>,
) -> Result<&'a ActiveLease, LeaseError> {
    control
        .active
        .as_ref()
        .filter(|active| Arc::ptr_eq(&active.token, token))
        .ok_or(LeaseError::Released)
}

#[cfg(test)]
struct TestOverlap {
    reached: Barrier,
    proceed: Barrier,
}

/// Holds the mailbox lock so a `Debug` must observe contention.
#[cfg(test)]
pub(super) fn hold_mailbox_lock(mailbox: &InputMailbox, held: &Barrier, release: &Barrier) {
    let _guard = mailbox
        .batches
        .lock()
        .expect("injection mailbox lock poisoned");
    held.wait();
    release.wait();
}

#[cfg(test)]
pub(super) struct TestOverlapControl {
    overlap: Arc<TestOverlap>,
    inner: Arc<SessionInner>,
}

#[cfg(test)]
impl TestOverlapControl {
    pub(super) fn wait_until_reached(&self) {
        self.overlap.reached.wait();
    }

    pub(super) fn assert_control_is_locked(&self) {
        assert!(matches!(
            self.inner.control.try_lock(),
            Err(TryLockError::WouldBlock)
        ));
    }

    pub(super) fn proceed(&self) {
        self.overlap.proceed.wait();
    }
}

#[cfg(test)]
fn pause_at(slot: &Mutex<Option<Arc<TestOverlap>>>) {
    let overlap = slot.lock().expect("test overlap lock poisoned").take();
    if let Some(overlap) = overlap {
        overlap.reached.wait();
        overlap.proceed.wait();
    }
}

#[cfg(test)]
fn probe_control_lock(inner: &SessionInner) {
    let overlap = inner
        .release_probe
        .lock()
        .expect("release probe lock poisoned")
        .take();
    if let Some(overlap) = overlap {
        assert!(matches!(
            inner.control.try_lock(),
            Err(TryLockError::WouldBlock)
        ));
        overlap.reached.wait();
        overlap.proceed.wait();
    }
}

/// Signals one thread's arrival at an already-held transaction lock.
///
/// The probe runs before the arriving thread blocks, and it first proves the
/// lock is held. A test that observes the signal therefore knows the arriving
/// mutation cannot make progress until the transaction holder resolves, which is
/// what makes "this path cannot cross an unresolved transaction" a deterministic
/// assertion instead of a timing race.
#[cfg(test)]
fn probe_transaction_lock(inner: &SessionInner) {
    let arrival = inner
        .transaction_arrivals
        .lock()
        .expect("transaction arrival lock poisoned")
        .take();
    if let Some(arrival) = arrival {
        assert!(matches!(
            inner.transaction.try_lock(),
            Err(TryLockError::WouldBlock)
        ));
        arrival
            .send(())
            .expect("the installing test observes the arrival");
    }
}

/// Observes arrivals at an already-held transaction lock.
///
/// The signal is one-shot per [`Self::arm`], so a test can walk several distinct
/// mutation paths into the same held transaction without a later, unblocked
/// transaction tripping the probe.
#[cfg(test)]
pub(crate) struct TransactionArrival {
    inner: Arc<SessionInner>,
    sender: mpsc::Sender<()>,
    arrived: mpsc::Receiver<()>,
}

#[cfg(test)]
impl TransactionArrival {
    /// Arms the signal for the next single thread to enter a transaction.
    pub(crate) fn arm(&self) {
        *self
            .inner
            .transaction_arrivals
            .lock()
            .expect("transaction arrival lock poisoned") = Some(self.sender.clone());
    }

    /// Blocks until one armed thread has reached the held transaction lock.
    pub(crate) fn wait_until_blocked(&self) {
        self.arrived
            .recv()
            .expect("the arriving thread signals before it blocks");
    }
}

/// Creates an unarmed arrival probe for one session's transaction lock.
#[cfg(test)]
pub(crate) fn install_transaction_arrival(session: &Session) -> TransactionArrival {
    let (sender, arrived) = mpsc::channel();
    TransactionArrival {
        inner: Arc::clone(&session.inner),
        sender,
        arrived,
    }
}

#[cfg(test)]
fn install_overlap(
    session: &Session,
    slot: &Mutex<Option<Arc<TestOverlap>>>,
) -> TestOverlapControl {
    let overlap = Arc::new(TestOverlap {
        reached: Barrier::new(2),
        proceed: Barrier::new(2),
    });
    *slot.lock().expect("test overlap lock poisoned") = Some(Arc::clone(&overlap));
    TestOverlapControl {
        overlap,
        inner: Arc::clone(&session.inner),
    }
}

#[cfg(test)]
pub(super) fn install_admit_before_control(session: &Session) -> TestOverlapControl {
    install_overlap(session, &session.inner.admit_before_control)
}

#[cfg(test)]
pub(super) fn install_admit_with_control(session: &Session) -> TestOverlapControl {
    install_overlap(session, &session.inner.admit_with_control)
}

#[cfg(test)]
pub(super) fn install_commit_overlap(session: &Session) -> TestOverlapControl {
    install_overlap(session, &session.inner.commit_overlap)
}

#[cfg(test)]
pub(super) fn install_release_probe(session: &Session) -> TestOverlapControl {
    install_overlap(session, &session.inner.release_probe)
}