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
//! Typed, owned-snapshot state shared by successor runs of one session.
//!
//! Ingress, load, and every previous/actual/deleted return are separate logical
//! snapshots; reader capability cannot be upgraded to writer, and after lease
//! release reads remain valid while writes return `LeaseReleased`. Staged
//! resolution builds a complete candidate map before one swap, so a partially
//! resolved map is never observable.
//!
//! # Panics
//!
//! Every method on [`Reader`], [`Writer`], and [`StagedWriter`] can panic for
//! the same two reasons, and no argument a caller can construct reaches either.
//!
//! A poisoned lock — the shared value map, the lease flag, a callback write
//! permit, or a staged overlay — is propagated rather than recovered, per the
//! crate-level [lock-poisoning contract](crate#lock-poisoning). Because the
//! values map is held across the [`SnapshotValue::clone`](Clone::clone) of an ingress or
//! egress snapshot, a [`SnapshotValue`] implementation that panics in `Clone` — which its
//! trust contract forbids — is one way to poison it.
//!
//! A slot holding a value whose type is not the one its [`Key`] names panics as a
//! core invariant violation rather than being reported as an absent slot or a
//! [`WriteError`]. A key is the only way to address a slot and it carries the
//! type, so this can only arise from a defect inside this crate.

use std::any::Any;
use std::collections::HashMap;
use std::error::Error;
use std::fmt::{self, Debug, Formatter};
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard};
#[cfg(test)]
use std::sync::{Barrier, TryLockError};

use crate::redact::Locked;

struct KeyToken {
    _non_zero_sized: u8,
}

#[derive(Clone)]
struct SlotId(Arc<KeyToken>);

impl PartialEq for SlotId {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }
}

impl Eq for SlotId {}

impl Hash for SlotId {
    fn hash<H: Hasher>(&self, state: &mut H) {
        Arc::as_ptr(&self.0).hash(state);
    }
}

/// A typed handle to one session-state slot.
///
/// A fresh key owns a fresh private identity. Clones address the same slot;
/// independently created keys remain distinct even when `T` is the same.
pub struct Key<T> {
    token: Arc<KeyToken>,
    marker: PhantomData<fn(T) -> T>,
}

#[expect(
    clippy::new_without_default,
    reason = "ADR-006 forbids Default because every key creation must be explicit"
)]
impl<T> Key<T> {
    /// Allocates a fresh slot identity.
    #[must_use]
    pub fn new() -> Self {
        Self {
            token: Arc::new(KeyToken { _non_zero_sized: 0 }),
            marker: PhantomData,
        }
    }

    fn slot_id(&self) -> SlotId {
        SlotId(Arc::clone(&self.token))
    }
}

impl<T> Clone for Key<T> {
    fn clone(&self) -> Self {
        Self {
            token: Arc::clone(&self.token),
            marker: PhantomData,
        }
    }
}

impl<T> Debug for Key<T> {
    /// Prints the slot identity, with no `T: Debug` bound to satisfy.
    ///
    /// Clones of one key share an address; independently created keys never do,
    /// which is exactly the identity semantics this type promises.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Key")
            .field("slot", &Arc::as_ptr(&self.token))
            .finish()
    }
}

impl<T> PartialEq for Key<T> {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.token, &other.token)
    }
}

impl<T> Eq for Key<T> {}

impl<T> Hash for Key<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        Arc::as_ptr(&self.token).hash(state);
    }
}

/// Marks a value as safe for owned session snapshots.
///
/// # Trust contract
///
/// This trait deliberately has no blanket implementation. Implementing it is a
/// reviewable assertion that [`Clone::clone`] leaves no shared mutable alias;
/// performs no I/O, callback, lock-dependent protocol action, or intentional
/// panic; and that mutating or dropping any ingress or returned clone cannot
/// affect another snapshot. Cloneable capabilities such as mutex-backed arcs,
/// atomics used as shared state, channels, handles, and callbacks do **not**
/// satisfy this contract merely because they implement [`Clone`].
///
/// A non-cloneable value cannot implement this trait:
///
/// ```compile_fail
/// use reef_core::state::session_state;
/// struct NotClone;
/// impl session_state::SnapshotValue for NotClone {}
/// ```
///
/// Cloneable shared-mutation capabilities are not accepted automatically:
///
/// ```compile_fail
/// use reef_core::state::session_state;
/// use std::sync::{Arc, Mutex};
///
/// fn require_session_value<T: session_state::SnapshotValue>() {}
/// require_session_value::<Arc<Mutex<Vec<u8>>>>();
/// ```
///
/// A dishonest implementation violates Reef's logical ownership contract, but
/// cannot cause memory unsafety in this module.
pub trait SnapshotValue: Clone + Send + Sync + 'static {}

/// The stable error returned by a session-state write.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum WriteError {
    /// The writer's owning session lease has been released.
    LeaseReleased,
}

impl fmt::Display for WriteError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::LeaseReleased => formatter.write_str("session-state lease released"),
        }
    }
}

impl Error for WriteError {}

trait StoredSnapshotValue: Send + Sync {
    fn clone_stored(&self) -> Box<dyn StoredSnapshotValue>;
    fn as_any(&self) -> &dyn Any;
}

impl<T: SnapshotValue> StoredSnapshotValue for T {
    fn clone_stored(&self) -> Box<dyn StoredSnapshotValue> {
        Box::new(self.clone())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

type StoredMap = HashMap<SlotId, Box<dyn StoredSnapshotValue>>;

struct Core {
    values: RwLock<StoredMap>,
}

impl Core {
    /// Renders one capability handle by how many slots stand behind it.
    ///
    /// Stored values are boxed trait objects with no `Debug`, so occupancy is
    /// the only fact a formatter can report, and the read never blocks.
    fn debug_handle(&self, name: &str, formatter: &mut Formatter<'_>) -> fmt::Result {
        let mut handle = formatter.debug_struct(name);
        match self.values.try_read() {
            Ok(values) => handle.field("slots", &values.len()),
            Err(_contended_or_poisoned) => handle.field("slots", &Locked),
        }
        .finish()
    }

    fn new() -> Self {
        Self {
            values: RwLock::new(HashMap::new()),
        }
    }

    fn load<T: SnapshotValue>(&self, key: &Key<T>) -> Option<T> {
        let values = self.values.read().expect("session-state lock poisoned");
        values
            .get(&key.slot_id())
            .map(|value| stored_clone::<T>(&**value))
    }
}

struct Lease {
    active: RwLock<bool>,
    #[cfg(test)]
    write_overlap: Mutex<Option<Arc<WriteOverlap>>>,
}

#[cfg(test)]
struct WriteOverlap {
    admitted: Barrier,
    proceed: Barrier,
}

#[cfg(test)]
impl WriteOverlap {
    fn new() -> Self {
        Self {
            admitted: Barrier::new(2),
            proceed: Barrier::new(2),
        }
    }
}

#[cfg(test)]
pub(super) struct WriteOverlapControl {
    overlap: Arc<WriteOverlap>,
    lease: Arc<Lease>,
}

#[cfg(test)]
impl WriteOverlapControl {
    pub(super) fn wait_for_admission(&self) {
        self.overlap.admitted.wait();
    }

    pub(super) fn assert_release_is_blocked(&self) {
        assert!(
            matches!(self.lease.active.try_write(), Err(TryLockError::WouldBlock)),
            "an admitted write must hold the lease read guard"
        );
    }

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

#[cfg(test)]
impl Lease {
    fn pause_admitted_write(&self) {
        let overlap = self
            .write_overlap
            .lock()
            .expect("test write-overlap lock must be healthy")
            .clone();
        if let Some(overlap) = overlap {
            overlap.admitted.wait();
            overlap.proceed.wait();
            *self
                .write_overlap
                .lock()
                .expect("test write-overlap lock must be healthy") = None;
        }
    }
}

/// A read-only session-state capability.
///
/// Loads return owned clones and remain valid after the corresponding writer's
/// lease is released. There is no conversion from `Reader` back to [`Writer`].
///
/// ```compile_fail
/// use reef_core::state::session_state;
/// fn cannot_upgrade(reader: &session_state::Reader, key: &session_state::Key<MySnapshotValue>, value: &MySnapshotValue) {
///     reader.set(key, value);
/// }
/// # #[derive(Clone)] struct MySnapshotValue;
/// ```
pub struct Reader {
    core: Arc<Core>,
}

impl Debug for Reader {
    /// Reports slot occupancy behind this read capability.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        self.core.debug_handle("Reader", formatter)
    }
}

impl Reader {
    /// Loads an owned snapshot from `key`.
    ///
    /// # Panics
    ///
    /// On a poisoned lock or a violated slot type invariant, as
    /// [this module's panic conditions](self#panics) describe.
    #[must_use]
    pub fn load<T: SnapshotValue>(&self, key: &Key<T>) -> Option<T> {
        self.core.load(key)
    }

    /// Clones this read authority for a crate-managed callback owner.
    pub(crate) fn clone_handle(&self) -> Self {
        Self {
            core: Arc::clone(&self.core),
        }
    }
}

struct CallbackWritePermitInner {
    active: RwLock<bool>,
}

/// Callback-local revocation authority retained by the runtime owner.
///
/// This is deliberately crate-private: ordinary writers carry no permit, while
/// a managed synchronous callback receives a fresh permit that its async owner
/// can revoke before releasing an abort acknowledgement.
#[derive(Clone)]
pub(crate) struct CallbackWritePermit {
    inner: Arc<CallbackWritePermitInner>,
}

impl CallbackWritePermit {
    fn new() -> Self {
        Self {
            inner: Arc::new(CallbackWritePermitInner {
                active: RwLock::new(true),
            }),
        }
    }

    /// Revokes future writes after every already-admitted write has linearized.
    pub(crate) fn revoke(&self) {
        let mut active = self
            .inner
            .active
            .write()
            .expect("callback write-permit lock poisoned");
        *active = false;
    }
}

/// A lease-bound read/write session-state capability.
///
/// Every ingress value is cloned before storage and every returned value is a
/// fresh owned clone. Writes after lease release return
/// [`WriteError::LeaseReleased`], while reads remain valid. A
/// crate-managed callback clone can additionally be revoked without revoking the
/// ordinary lease writer; this internal distinction does not change the public
/// error or capability surface.
pub struct Writer {
    core: Arc<Core>,
    lease: Arc<Lease>,
    callback_permit: Option<Arc<CallbackWritePermitInner>>,
}

impl Debug for Writer {
    /// Reports slot occupancy behind this write capability.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        self.core.debug_handle("Writer", formatter)
    }
}

impl Writer {
    /// Loads an owned snapshot from `key`.
    ///
    /// # Panics
    ///
    /// On a poisoned lock or a violated slot type invariant, as
    /// [this module's panic conditions](self#panics) describe.
    #[must_use]
    pub fn load<T: SnapshotValue>(&self, key: &Key<T>) -> Option<T> {
        self.core.load(key)
    }

    /// Stores an owned clone of `value`, returning an owned prior snapshot.
    ///
    /// # Errors
    ///
    /// [`WriteError::LeaseReleased`] if the session lease behind this writer has
    /// been released, which is the only reason a write is refused. Reads stay
    /// valid afterwards; write authority does not, and it never comes back — a
    /// successor Run acquires its own lease and its own writer. A revoked
    /// callback-local writer reports the same variant, because a callback that
    /// outlived its invocation window has lost write authority for the same
    /// reason and has no separate remedy.
    ///
    /// # Panics
    ///
    /// On a poisoned lock or a violated slot type invariant, as
    /// [this module's panic conditions](self#panics) describe.
    pub fn set<T: SnapshotValue>(&self, key: &Key<T>, value: &T) -> Result<Option<T>, WriteError> {
        self.with_write(|values| {
            values
                .insert(key.slot_id(), Box::new(value.clone()))
                .map(|previous| stored_clone::<T>(&*previous))
        })
    }

    /// Loads an existing snapshot or stores an owned clone of `value`.
    ///
    /// The boolean is `true` when an existing value won.
    ///
    /// # Errors
    ///
    /// [`WriteError::LeaseReleased`] if the session lease behind this writer has
    /// been released. The check happens before the slot is read, so a refused
    /// call reports nothing about what the slot held.
    ///
    /// # Panics
    ///
    /// On a poisoned lock or a violated slot type invariant, as
    /// [this module's panic conditions](self#panics) describe.
    pub fn load_or_store<T: SnapshotValue>(
        &self,
        key: &Key<T>,
        value: &T,
    ) -> Result<(T, bool), WriteError> {
        self.with_write(|values| {
            if let Some(existing) = values.get(&key.slot_id()) {
                (stored_clone::<T>(&**existing), true)
            } else {
                let stored = value.clone();
                let returned = stored.clone();
                values.insert(key.slot_id(), Box::new(stored));
                (returned, false)
            }
        })
    }

    /// Deletes `key`, returning an owned prior snapshot when present.
    ///
    /// # Errors
    ///
    /// [`WriteError::LeaseReleased`] if the session lease behind this writer has
    /// been released. Deleting an absent slot is not an error; it succeeds with
    /// `None`.
    ///
    /// # Panics
    ///
    /// On a poisoned lock or a violated slot type invariant, as
    /// [this module's panic conditions](self#panics) describe.
    pub fn delete<T: SnapshotValue>(&self, key: &Key<T>) -> Result<Option<T>, WriteError> {
        self.with_write(|values| {
            values
                .remove(&key.slot_id())
                .map(|previous| stored_clone::<T>(&*previous))
        })
    }

    /// Creates an unresolved write overlay over this writer.
    #[must_use]
    pub fn staged(&self) -> StagedWriter {
        StagedWriter {
            writer: Self {
                core: Arc::clone(&self.core),
                lease: Arc::clone(&self.lease),
                callback_permit: self.callback_permit.clone(),
            },
            state: Mutex::new(StageState::Active(HashMap::new())),
        }
    }

    /// Narrows this capability to a read-only view.
    #[must_use]
    pub fn reader(&self) -> Reader {
        Reader {
            core: Arc::clone(&self.core),
        }
    }

    /// Creates one callback-local writer plus the owner's revocation authority.
    pub(crate) fn clone_with_callback_permit(&self) -> (Self, CallbackWritePermit) {
        let permit = CallbackWritePermit::new();
        let writer = Self {
            core: Arc::clone(&self.core),
            lease: Arc::clone(&self.lease),
            callback_permit: Some(Arc::clone(&permit.inner)),
        };
        (writer, permit)
    }

    fn admit_callback_write(&self) -> Result<Option<RwLockReadGuard<'_, bool>>, WriteError> {
        let Some(permit) = &self.callback_permit else {
            return Ok(None);
        };
        let active = permit
            .active
            .read()
            .expect("callback write-permit lock poisoned");
        if !*active {
            return Err(WriteError::LeaseReleased);
        }
        Ok(Some(active))
    }

    fn with_write<R>(&self, operation: impl FnOnce(&mut StoredMap) -> R) -> Result<R, WriteError> {
        let _callback_permit = self.admit_callback_write()?;
        let active = self
            .lease
            .active
            .read()
            .expect("session lease lock poisoned");
        if !*active {
            return Err(WriteError::LeaseReleased);
        }
        #[cfg(test)]
        self.lease.pause_admitted_write();
        let mut values = self
            .core
            .values
            .write()
            .expect("session-state lock poisoned");
        Ok(operation(&mut values))
    }

    fn commit(&self, overlay: &HashMap<SlotId, StagedSlot>) -> Result<(), WriteError> {
        self.with_write(|values| {
            let mut candidate = clone_map(values);
            for (id, slot) in overlay {
                match slot {
                    StagedSlot::SnapshotValue(value) => {
                        candidate.insert(id.clone(), value.clone_stored());
                    }
                    StagedSlot::Deleted => {
                        candidate.remove(id);
                    }
                }
            }
            *values = candidate;
        })
    }

    /// Revokes this writer after all older writes have linearized.
    pub(crate) fn release(&self) {
        let mut active = self
            .lease
            .active
            .write()
            .expect("session lease lock poisoned");
        *active = false;
    }
}

enum StagedSlot {
    SnapshotValue(Box<dyn StoredSnapshotValue>),
    Deleted,
}

enum StageState {
    Active(HashMap<SlotId, StagedSlot>),
    Resolved,
}

impl Debug for StageState {
    /// Reports how many slots the overlay holds, or that it has resolved.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Active(overlay) => formatter
                .debug_tuple("Active")
                .field(&overlay.len())
                .finish(),
            Self::Resolved => formatter.write_str("Resolved"),
        }
    }
}

/// A write overlay that resolves exactly once by commit or discard.
///
/// Before resolution, reads are overlay-first and changes are hidden from base
/// readers. Commit builds a complete candidate map and publishes it with one
/// swap. After either resolution, retained operations forward to the base
/// [`Writer`], including its later lease revocation.
pub struct StagedWriter {
    writer: Writer,
    state: Mutex<StageState>,
}

impl Debug for StagedWriter {
    /// Shows the base capability and whether the overlay is still open.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        let mut staged = formatter.debug_struct("StagedWriter");
        staged.field("writer", &self.writer);
        match self.state.try_lock() {
            Ok(state) => staged.field("stage", &*state),
            Err(_contended_or_poisoned) => staged.field("stage", &Locked),
        }
        .finish()
    }
}

impl StagedWriter {
    /// Loads an owned overlay-first snapshot from `key`.
    ///
    /// # Panics
    ///
    /// On a poisoned lock or a violated slot type invariant, as
    /// [this module's panic conditions](self#panics) describe.
    #[must_use]
    pub fn load<T: SnapshotValue>(&self, key: &Key<T>) -> Option<T> {
        let state = self.state.lock().expect("staged-state lock poisoned");
        match &*state {
            StageState::Active(overlay) => staged_load(overlay, &self.writer, key),
            StageState::Resolved => self.writer.load(key),
        }
    }

    /// Stages an owned clone of `value`, returning the effective prior snapshot.
    ///
    /// # Errors
    ///
    /// [`WriteError::LeaseReleased`] if this staged writer's callback-local write
    /// permit has been revoked while the overlay is still open, or, once the
    /// overlay has resolved and calls forward to the base [`Writer`], if the
    /// session lease has been released. Staging into an open overlay does not
    /// otherwise consult the lease: the lease is what publication needs, and
    /// [`StagedWriter::commit`] is where that is checked.
    ///
    /// # Panics
    ///
    /// On a poisoned lock or a violated slot type invariant, as
    /// [this module's panic conditions](self#panics) describe.
    pub fn set<T: SnapshotValue>(&self, key: &Key<T>, value: &T) -> Result<Option<T>, WriteError> {
        let mut state = self.state.lock().expect("staged-state lock poisoned");
        match &mut *state {
            StageState::Active(overlay) => {
                let _callback_permit = self.writer.admit_callback_write()?;
                let previous = staged_load(overlay, &self.writer, key);
                overlay.insert(
                    key.slot_id(),
                    StagedSlot::SnapshotValue(Box::new(value.clone())),
                );
                Ok(previous)
            }
            StageState::Resolved => self.writer.set(key, value),
        }
    }

    /// Loads the effective snapshot or stages an owned clone of `value`.
    ///
    /// The boolean is `true` when an existing value won.
    ///
    /// # Errors
    ///
    /// [`WriteError::LeaseReleased`] on a revoked callback-local write permit
    /// while the overlay is open, or on a released lease once the overlay has
    /// resolved and this call forwards to the base [`Writer`].
    ///
    /// # Panics
    ///
    /// On a poisoned lock or a violated slot type invariant, as
    /// [this module's panic conditions](self#panics) describe.
    pub fn load_or_store<T: SnapshotValue>(
        &self,
        key: &Key<T>,
        value: &T,
    ) -> Result<(T, bool), WriteError> {
        let mut state = self.state.lock().expect("staged-state lock poisoned");
        match &mut *state {
            StageState::Active(overlay) => {
                let _callback_permit = self.writer.admit_callback_write()?;
                if let Some(existing) = staged_load(overlay, &self.writer, key) {
                    Ok((existing, true))
                } else {
                    let stored = value.clone();
                    let returned = stored.clone();
                    overlay.insert(key.slot_id(), StagedSlot::SnapshotValue(Box::new(stored)));
                    Ok((returned, false))
                }
            }
            StageState::Resolved => self.writer.load_or_store(key, value),
        }
    }

    /// Stages deletion of `key`, returning the effective prior snapshot.
    ///
    /// # Errors
    ///
    /// [`WriteError::LeaseReleased`] on a revoked callback-local write permit
    /// while the overlay is open, or on a released lease once the overlay has
    /// resolved and this call forwards to the base [`Writer`].
    ///
    /// # Panics
    ///
    /// On a poisoned lock or a violated slot type invariant, as
    /// [this module's panic conditions](self#panics) describe.
    pub fn delete<T: SnapshotValue>(&self, key: &Key<T>) -> Result<Option<T>, WriteError> {
        let mut state = self.state.lock().expect("staged-state lock poisoned");
        match &mut *state {
            StageState::Active(overlay) => {
                let _callback_permit = self.writer.admit_callback_write()?;
                let previous = staged_load(overlay, &self.writer, key);
                overlay.insert(key.slot_id(), StagedSlot::Deleted);
                Ok(previous)
            }
            StageState::Resolved => self.writer.delete(key),
        }
    }

    /// Atomically publishes the overlay, or does nothing if already resolved.
    ///
    /// A released lease rejects the whole candidate; no touched slot becomes
    /// visible. Resolution is idempotent and the first commit/discard wins.
    ///
    /// # Errors
    ///
    /// [`WriteError::LeaseReleased`] if the session lease has been released, or
    /// this staged writer's callback-local write permit revoked, by the time the
    /// overlay would publish. The whole overlay is refused, not the slots that
    /// arrived too late: a caller that has staged several related values can
    /// therefore treat this as "none of it happened" rather than reconciling a
    /// partial write. A commit on an already-resolved overlay is `Ok(())` and
    /// publishes nothing.
    ///
    /// # Panics
    ///
    /// On a poisoned lock or a violated slot type invariant, as
    /// [this module's panic conditions](self#panics) describe. A panic here
    /// leaves the overlay resolved and the base map unchanged, because the
    /// candidate is built in full before it replaces the base.
    pub fn commit(&self) -> Result<(), WriteError> {
        let mut state = self.state.lock().expect("staged-state lock poisoned");
        let StageState::Active(overlay) = std::mem::replace(&mut *state, StageState::Resolved)
        else {
            return Ok(());
        };
        self.writer.commit(&overlay)
    }

    /// Discards the overlay, or does nothing if already resolved.
    ///
    /// # Panics
    ///
    /// If the staged overlay lock is poisoned, per the crate-level
    /// [lock-poisoning contract](crate#lock-poisoning).
    pub fn discard(&self) {
        let mut state = self.state.lock().expect("staged-state lock poisoned");
        *state = StageState::Resolved;
    }
}

/// Holds the shared value lock so a `Debug` must observe contention.
#[cfg(test)]
pub(super) fn hold_value_lock(reader: &Reader, held: &Barrier, release: &Barrier) {
    let _guard = reader
        .core
        .values
        .write()
        .expect("test lock starts healthy");
    held.wait();
    release.wait();
}

/// Holds the overlay lock so a `Debug` must observe contention.
#[cfg(test)]
pub(super) fn hold_stage_lock(staged: &StagedWriter, held: &Barrier, release: &Barrier) {
    let _guard = staged.state.lock().expect("staged-state lock poisoned");
    held.wait();
    release.wait();
}

fn staged_load<T: SnapshotValue>(
    overlay: &HashMap<SlotId, StagedSlot>,
    writer: &Writer,
    key: &Key<T>,
) -> Option<T> {
    match overlay.get(&key.slot_id()) {
        Some(StagedSlot::SnapshotValue(value)) => Some(stored_clone::<T>(&**value)),
        Some(StagedSlot::Deleted) => None,
        None => writer.load(key),
    }
}

fn stored_clone<T: SnapshotValue>(value: &dyn StoredSnapshotValue) -> T {
    value
        .as_any()
        .downcast_ref::<T>()
        .unwrap_or_else(|| panic!("session-state slot type invariant violated"))
        .clone()
}

fn clone_map(values: &StoredMap) -> StoredMap {
    values
        .iter()
        .map(|(id, value)| (id.clone(), value.clone_stored()))
        .collect()
}

/// Internal owner used by the session layer to mint lease-bound capabilities.
pub(crate) struct Store {
    core: Arc<Core>,
}

impl Store {
    /// Creates an empty session-state owner.
    pub(crate) fn new() -> Self {
        Self {
            core: Arc::new(Core::new()),
        }
    }

    /// Creates a reader that has no upgrade path to write authority.
    pub(crate) fn reader(&self) -> Reader {
        Reader {
            core: Arc::clone(&self.core),
        }
    }

    /// Acquires a new independently revocable writer over this state.
    pub(crate) fn acquire(&self) -> Writer {
        Writer {
            core: Arc::clone(&self.core),
            lease: Arc::new(Lease {
                active: RwLock::new(true),
                #[cfg(test)]
                write_overlap: Mutex::new(None),
            }),
            callback_permit: None,
        }
    }

    #[cfg(test)]
    pub(super) fn corrupt<T, U>(&self, key: &Key<T>, value: U)
    where
        U: SnapshotValue,
    {
        self.core
            .values
            .write()
            .expect("session-state lock poisoned")
            .insert(key.slot_id(), Box::new(value));
    }
}

#[cfg(test)]
pub(super) fn install_write_overlap(writer: &Writer) -> WriteOverlapControl {
    let overlap = Arc::new(WriteOverlap::new());
    *writer
        .lease
        .write_overlap
        .lock()
        .expect("test write-overlap lock must be healthy") = Some(Arc::clone(&overlap));
    WriteOverlapControl {
        overlap,
        lease: Arc::clone(&writer.lease),
    }
}