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
//! Hook-governed mutation over the active lease's sole transaction authority.
//!
//! A controller-managed live transcript mutation is not one operation but three
//! that must not be separated: hooks reserve the proposed mutation, the store
//! commits it under compare-and-set, and the reservations publish the committed
//! fact. The [`Store`](crate::transcript::store::Store) lock only protects the
//! middle step, so the whole sequence runs inside the session's
//! [`Transaction`](crate::runtime::session::Transaction). Without it a second
//! mutation could observe the committed version and commit again before the
//! first transaction's publishers had run — the commit-to-publish gap this
//! module exists to forbid.
//!
//! The transaction authority lives on the session rather than on the controller,
//! because a controller-owned lock would only serialize controllers. Every other
//! mutation path - a direct [`Lease`] compare-and-set, lease release, and
//! successor lease acquisition - shares the same authority, so none of them can
//! cross an unresolved transaction either.
//!
//! The resulting contract is:
//!
//! - Reservations run in hook registration order while the transaction is held.
//! - Any pre-commit failure - a callback error, a cancellation, an invalid
//!   version transition, a compare-and-set conflict, a version overflow, or a
//!   callback panic - aborts every already-held reservation in reverse
//!   acquisition order and commits nothing.
//! - Once the compare-and-set succeeds the transaction is committed. Every held
//!   reservation is published in acquisition order, and no committed reservation
//!   is ever aborted, not even when an earlier publisher panics.
//! - A reservation callback panic is the transaction's outcome. Aborting still
//!   visits every held reservation, but an abort panic never displaces the
//!   original callback panic.

use std::panic::{AssertUnwindSafe, catch_unwind};

use crate::cancel::Token;

use crate::runtime::hook::{
    self, DispatchError, Emitter, TranscriptMutation, TranscriptReservation,
};
use crate::runtime::session::{Lease, LeaseError, Transaction};
use crate::state::run_state::{self};
use crate::state::session_state::{self};
use crate::transcript::item::Item;
use crate::transcript::store::{self, Snapshot, Version};
use crate::value::lifecycle::Coord;

/// A live transcript mutation failure.
///
/// Every variant is a pre-commit outcome: the transcript is unchanged and every
/// held reservation has already been aborted in reverse order.
#[derive(Debug)]
pub(crate) enum ControllerError {
    /// A reservation callback failed, or a cancellation was observed.
    Dispatch(DispatchError),
    /// The lease rejected the compare-and-set, or it was already released.
    Lease(LeaseError),
    /// The proposed transition would leave the closed `V`-to-`V+n` shape.
    ///
    /// This is reported before any reservation runs, so no hook observes a
    /// mutation fact that the store could not have produced.
    InvalidTransition {
        /// The version observed before the mutation.
        previous: Version,
        /// The number of versions the mutation would advance.
        delta: u64,
    },
}

impl core::fmt::Display for ControllerError {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Dispatch(DispatchError::Callback(failure)) => write!(
                formatter,
                "transcript reservation rejected by hook {}: {}",
                failure.name(),
                failure.error()
            ),
            Self::Dispatch(DispatchError::Cancelled) => {
                formatter.write_str("transcript mutation cancelled before commit")
            }
            Self::Lease(error) => write!(formatter, "transcript mutation rejected: {error}"),
            Self::InvalidTransition { previous, delta } => write!(
                formatter,
                "invalid transcript transition: previous {previous}, increment {delta}"
            ),
        }
    }
}

impl std::error::Error for ControllerError {
    /// Returns the hook or lease failure this mutation stopped on.
    ///
    /// The version-shape rejection is computed here rather than reported by
    /// something else, so it is its own leaf and has nothing underneath it.
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Dispatch(error) => Some(error),
            Self::Lease(error) => Some(error),
            Self::InvalidTransition { .. } => None,
        }
    }
}

/// Per-registration resources the controller lends to reservation callbacks.
///
/// `OnTranscriptMutation` runs pre-commit inside the outer transaction lock, so
/// it receives a read-only scope. The controller therefore needs one independent
/// [`run_state::Store`] per registration plus a session-state reader; it deliberately
/// holds no session-state writer, because a pre-commit callback must not be able
/// to stage session state that outlives a mutation the store may still refuse.
pub(crate) struct ReservationResources {
    run_states: Vec<run_state::Store>,
    session_state: session_state::Reader,
}

impl ReservationResources {
    /// Allocates one independent run-state store per registration.
    ///
    /// Indices are registry positions, so a registration that omits the
    /// transcript family still owns a slot and can never share another
    /// registration's state.
    #[must_use]
    #[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
    pub(crate) fn new(registrations: usize, session_state: session_state::Reader) -> Self {
        Self {
            run_states: (0..registrations)
                .map(|_| run_state::Store::new())
                .collect(),
            session_state,
        }
    }

    /// Shares the caller's existing per-registration Run-state identities.
    #[must_use]
    pub(crate) fn shared(
        run_states: &[run_state::Store],
        session_state: session_state::Reader,
    ) -> Self {
        Self {
            run_states: run_states
                .iter()
                .map(run_state::Store::clone_handle)
                .collect(),
            session_state,
        }
    }
}

/// Serializes reservation, commit, and publication for one session lease.
///
/// The controller borrows the session's transaction authority through the lease.
/// It never exposes a transaction, a reservation, or a partially resolved
/// mutation, so no caller can commit without reserving or publish without
/// committing.
pub(crate) struct TranscriptController<'a> {
    lease: &'a Lease,
    registry: &'a hook::RuntimeRegistry,
    resources: &'a ReservationResources,
    coord: &'a Coord,
    emitter: &'a dyn Emitter,
}

impl<'a> TranscriptController<'a> {
    /// Binds the controller to one lease, registry, and callback resource set.
    #[must_use]
    pub(crate) fn new(
        lease: &'a Lease,
        registry: &'a hook::RuntimeRegistry,
        resources: &'a ReservationResources,
        coord: &'a Coord,
        emitter: &'a dyn Emitter,
    ) -> Self {
        Self {
            lease,
            registry,
            resources,
            coord,
            emitter,
        }
    }

    /// Rebinds only the callback coordinate for one live mutation boundary.
    ///
    /// The lease, registry, per-registration state, and emitter remain identical;
    /// only the generation fact lent to reservation callbacks changes. This is the
    /// controller equivalent of `CallbackResources::with_coord` in the runtime
    /// hook module.
    #[must_use]
    pub(crate) const fn with_coord<'b>(&self, coord: &'b Coord) -> TranscriptController<'b>
    where
        'a: 'b,
    {
        TranscriptController {
            lease: self.lease,
            registry: self.registry,
            resources: self.resources,
            coord,
            emitter: self.emitter,
        }
    }

    /// Forks the current transcript into an isolated copy-on-write staging store.
    pub(crate) fn staging_store(&self) -> Result<store::Store, store::Error> {
        self.lease.fork_transcript()
    }

    /// Returns read-only live transcript access for non-staged hook boundaries.
    pub(crate) fn snapshot_reader(&self) -> store::SnapshotReader {
        self.lease.transcript_reader()
    }

    /// Reads the live transcript version inside a transaction.
    ///
    /// A version observed outside the transaction is immediately stale, because
    /// another mutation may commit before the caller uses it. Reading it here
    /// lets a caller pair the value with [`Self::replace_snapshot`] without racing.
    #[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
    pub(crate) fn version(&self) -> Result<Version, ControllerError> {
        self.lease
            .begin_transaction()
            .version()
            .map_err(ControllerError::Lease)
    }

    /// Appends one ordered owned batch as a single live mutation.
    ///
    /// An empty batch is a successful no-op that runs no callback: there is no
    /// transition to reserve.
    pub(crate) fn append_batch(
        &self,
        items: Vec<Item>,
        cancellation: &Token,
    ) -> Result<Version, ControllerError> {
        self.append_batch_settling(items, cancellation, &mut || {})
    }

    /// Appends like [`Self::append_batch`], calling `on_commit` at the commit.
    ///
    /// `on_commit` runs once, immediately after the compare-and-set linearizes
    /// and before any reservation publishes. From that instant the transcript
    /// holds the batch whatever a publisher does afterwards — including panic —
    /// so a caller that must know *whether the batch committed* learns it here
    /// rather than from this method returning. It never runs when the
    /// transaction fails or unwinds before the commit, nor for an empty batch,
    /// which commits nothing.
    pub(crate) fn append_batch_settling(
        &self,
        items: Vec<Item>,
        cancellation: &Token,
        on_commit: &mut dyn FnMut(),
    ) -> Result<Version, ControllerError> {
        let transaction = self.lease.begin_transaction();
        let transcript = transaction.snapshot().map_err(ControllerError::Lease)?;
        let previous = transcript.version();
        if items.is_empty() {
            return Ok(previous);
        }
        self.transact(
            &transaction,
            Candidate::Append(items),
            previous,
            transcript,
            cancellation,
            on_commit,
        )
    }

    /// Reserves and installs one shared replacement as a single live mutation.
    pub(crate) fn replace_snapshot(
        &self,
        snapshot: Snapshot,
        expected: Version,
        cancellation: &Token,
    ) -> Result<Version, ControllerError> {
        let transaction = self.lease.begin_transaction();
        let transcript = transaction.snapshot().map_err(ControllerError::Lease)?;
        if transcript.version() != expected {
            return Err(ControllerError::Lease(LeaseError::Transcript(
                store::Error::VersionConflict {
                    expected,
                    actual: transcript.version(),
                },
            )));
        }
        self.transact(
            &transaction,
            Candidate::Replace(snapshot),
            expected,
            transcript,
            cancellation,
            &mut || {},
        )
    }

    /// Runs one whole transaction: validate, reserve, commit, report, publish.
    ///
    /// Both entry points funnel through this one non-generic body, so the
    /// transition check, the abort direction, and the publication direction exist
    /// exactly once and cannot drift apart. The caller owns the transaction
    /// guard, so it outlives every resolution below.
    fn transact(
        &self,
        transaction: &Transaction<'_>,
        candidate: Candidate,
        previous: Version,
        transcript: Snapshot,
        cancellation: &Token,
        on_commit: &mut dyn FnMut(),
    ) -> Result<Version, ControllerError> {
        let delta = candidate.delta();
        let version = previous
            .as_u64()
            .checked_add(delta)
            .map(Version::from_u64)
            .ok_or(ControllerError::InvalidTransition { previous, delta })?;
        let mutation = candidate.into_mutation(previous, version);
        let mut held: Vec<Box<dyn TranscriptReservation>> = Vec::new();
        let reserved = self.reserve_all(&transcript, &mutation, cancellation, &mut held);
        drop(transcript);
        let pre_commit = reserved.and_then(|()| {
            // Last pre-commit cancellation check. Once the compare-and-set
            // below succeeds, cancellation alone must never reclassify the
            // transaction.
            if cancellation.is_cancelled() {
                return Err(Reserve::Failed(ControllerError::Dispatch(
                    DispatchError::Cancelled,
                )));
            }
            Ok(Candidate::commit(transaction, mutation, previous))
        });

        match pre_commit {
            Ok(version) => {
                // The live mutation has linearized. From here the infallible
                // publishers run in acquisition order and no reservation may be
                // aborted, even when a publisher panics. The commit is reported
                // first, so a publisher panic cannot hide it from the caller.
                on_commit();
                publish_all(held);
                Ok(version)
            }
            Err(Reserve::Failed(error)) => {
                abort_all(held);
                Err(error)
            }
            Err(Reserve::Panicked(payload)) => {
                // A reservation callback panicked. Abort every reservation this
                // transaction already held, then resume the original unwind so
                // the panic is not silently downgraded to an error. An abort
                // that panics in turn must not displace this payload, so the
                // abort's own unwind is discarded.
                let _ = catch_unwind(AssertUnwindSafe(|| abort_all(held)));
                std::panic::resume_unwind(payload);
            }
        }
    }

    /// Fans the reservation callback out in registration order.
    ///
    /// Every successful reservation is pushed into `held` before the next
    /// callback runs, so a later failure can abort exactly the reservations this
    /// transaction acquired, in reverse order.
    fn reserve_all(
        &self,
        transcript: &Snapshot,
        mutation: &TranscriptMutation,
        cancellation: &Token,
        held: &mut Vec<Box<dyn TranscriptReservation>>,
    ) -> Result<(), Reserve> {
        for adapter in self.registry.transcript_hooks() {
            if cancellation.is_cancelled() {
                return Err(Reserve::Failed(ControllerError::Dispatch(
                    DispatchError::Cancelled,
                )));
            }
            let run_state = self
                .resources
                .run_states
                .get(adapter.index())
                .expect("reservation resources cover every registry index");
            let resources = crate::runtime::hook::CallbackResources::new(
                self.coord,
                run_state,
                &self.resources.session_state,
                None,
                self.emitter,
            );
            let reserved = catch_unwind(AssertUnwindSafe(|| {
                adapter.invoke_reserve(resources, transcript, mutation)
            }))
            .map_err(Reserve::Panicked)?;
            match reserved {
                Ok(reservation) => held.push(reservation),
                Err(error) => {
                    return Err(Reserve::Failed(ControllerError::Dispatch(error)));
                }
            }
            if cancellation.is_cancelled() {
                return Err(Reserve::Failed(ControllerError::Dispatch(
                    DispatchError::Cancelled,
                )));
            }
        }
        Ok(())
    }
}

/// Which closed live mutation a transaction proposes.
///
/// The candidate constructs both the immutable fact reservations observe and the
/// lease compare-and-set payload, so the two can never disagree.
enum Candidate {
    /// Append the batch at `previous`, advancing by its length.
    Append(Vec<Item>),
    /// Replace the whole history at `previous`, advancing by one.
    Replace(Snapshot),
}

impl Candidate {
    /// How many versions committing this candidate advances the transcript.
    fn delta(&self) -> u64 {
        match self {
            // Rust's supported targets have pointer widths no greater than 64
            // bits, so every possible Vec length is representable as u64.
            Self::Append(items) => items.len() as u64,
            // A replacement always advances exactly one version, whatever its
            // length.
            Self::Replace(_) => 1,
        }
    }

    fn into_mutation(self, previous: Version, version: Version) -> TranscriptMutation {
        match self {
            Self::Append(items) => TranscriptMutation::Append {
                previous,
                version,
                items,
            },
            Self::Replace(snapshot) => TranscriptMutation::Replace {
                previous,
                snapshot: snapshot.with_version(version),
            },
        }
    }

    fn commit(
        transaction: &Transaction<'_>,
        mutation: TranscriptMutation,
        previous: Version,
    ) -> Version {
        match mutation {
            TranscriptMutation::Append { items, .. } => transaction
                .append_batch_if_version(items, previous)
                .expect("validated transaction append remains committable"),
            TranscriptMutation::Replace { snapshot, .. } => transaction
                .install_snapshot(snapshot, previous)
                .expect("validated transaction replacement remains committable"),
        }
    }
}

/// Why the pre-commit reservation phase stopped.
enum Reserve {
    /// A typed pre-commit failure; the caller aborts and returns it.
    Failed(ControllerError),
    /// A callback panicked; the caller aborts and resumes the unwind.
    Panicked(Box<dyn core::any::Any + Send>),
}

/// Aborts every held reservation in reverse acquisition order.
///
/// A panicking abort must not skip the remaining reservations, so the whole set
/// is still released before the first captured panic is resumed. When the
/// transaction is already unwinding from a reservation callback panic the caller
/// discards this resumption, because that original panic is the outcome.
fn abort_all(held: Vec<Box<dyn TranscriptReservation>>) {
    resolve_all(held.into_iter().rev(), TranscriptReservation::abort);
}

/// Publishes every held reservation in acquisition order.
///
/// The transcript mutation is already durable, so a panicking publisher must not
/// stop the remaining publishers and must never cause an abort. The whole set
/// still publishes before the first captured panic is resumed.
fn publish_all(held: Vec<Box<dyn TranscriptReservation>>) {
    resolve_all(held, TranscriptReservation::publish);
}

/// Resolves every reservation exactly once, isolating each resolution.
///
/// One shared body keeps the abort and publish phases from drifting: both must
/// visit every reservation even when one panics, and both resume only the first
/// captured panic, after the last reservation has been resolved.
fn resolve_all(
    held: impl IntoIterator<Item = Box<dyn TranscriptReservation>>,
    resolve: fn(Box<dyn TranscriptReservation>),
) {
    let mut first_panic = None;
    for reservation in held {
        // MSRV 1.85 has no `let` chains, so the two conditions stay nested.
        if let Err(payload) = catch_unwind(AssertUnwindSafe(|| resolve(reservation))) {
            if first_panic.is_none() {
                first_panic = Some(payload);
            }
        }
    }
    if let Some(payload) = first_panic {
        std::panic::resume_unwind(payload);
    }
}