reef-core 0.4.0

Provider-neutral primitives for building LLM agents: run lifecycle, transcript, tools, hooks
Documentation
#![cfg(loom)]

//! Synchronous loom specification for transcript transaction ordering.
//!
//! The model follows the outer transaction authority of
//! `SessionInner::enter_transaction` and `Transaction` in `runtime::session`,
//! and the reserve/CAS/resolve protocol of `TranscriptController::transact` and
//! `Shape::commit` in `transcript::controller`. It is an executable abstract
//! synchronization spec, not a replacement for the real controller or Tokio
//! runtime tests. No Tokio support is assumed or modeled here.

use loom::sync::{Arc, Mutex};
use loom::thread;

const REGISTRATIONS: usize = 2;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Event {
    Reserve {
        transaction: u8,
        registration: usize,
    },
    Commit {
        transaction: u8,
    },
    Publish {
        transaction: u8,
        registration: usize,
    },
    Abort {
        transaction: u8,
        registration: usize,
    },
}

struct Kernel {
    transaction: Mutex<()>,
    version: Mutex<usize>,
    journal: Mutex<Vec<Event>>,
}

impl Kernel {
    fn new() -> Arc<Self> {
        Arc::new(Self {
            transaction: Mutex::new(()),
            version: Mutex::new(0),
            journal: Mutex::new(Vec::new()),
        })
    }

    fn record(&self, event: Event) {
        self.journal
            .lock()
            .expect("journal lock remains healthy")
            .push(event);
    }

    fn abort_all(&self, transaction: u8, held: &[usize]) {
        for &registration in held.iter().rev() {
            self.record(Event::Abort {
                transaction,
                registration,
            });
        }
    }

    fn transact(&self, transaction: u8, expected: usize, fail_after: Option<usize>) -> bool {
        // The outer guard deliberately outlives reserve, the store's CAS lock, and
        // every resolution. Yielding after commit makes a missing lock-domain edge
        // observable as an interleaved successor reservation.
        let _transaction = self
            .transaction
            .lock()
            .expect("transaction lock remains healthy");
        let mut held = Vec::new();
        for registration in 0..REGISTRATIONS {
            self.record(Event::Reserve {
                transaction,
                registration,
            });
            held.push(registration);
            if fail_after == Some(registration) {
                self.abort_all(transaction, &held);
                return false;
            }
        }

        let committed = {
            let mut version = self.version.lock().expect("version lock remains healthy");
            if *version == expected {
                *version += 1;
                true
            } else {
                false
            }
        };
        if !committed {
            self.abort_all(transaction, &held);
            return false;
        }

        self.record(Event::Commit { transaction });
        thread::yield_now();
        for registration in held {
            self.record(Event::Publish {
                transaction,
                registration,
            });
        }
        true
    }

    fn version(&self) -> usize {
        *self.version.lock().expect("version lock remains healthy")
    }

    fn journal(&self) -> Vec<Event> {
        self.journal
            .lock()
            .expect("journal lock remains healthy")
            .clone()
    }
}

fn committed_sequence(transaction: u8) -> Vec<Event> {
    vec![
        Event::Reserve {
            transaction,
            registration: 0,
        },
        Event::Reserve {
            transaction,
            registration: 1,
        },
        Event::Commit { transaction },
        Event::Publish {
            transaction,
            registration: 0,
        },
        Event::Publish {
            transaction,
            registration: 1,
        },
    ]
}

fn aborted_sequence(transaction: u8) -> Vec<Event> {
    vec![
        Event::Reserve {
            transaction,
            registration: 0,
        },
        Event::Reserve {
            transaction,
            registration: 1,
        },
        Event::Abort {
            transaction,
            registration: 1,
        },
        Event::Abort {
            transaction,
            registration: 0,
        },
    ]
}

#[test]
fn commit_to_publish_has_no_successor_gap() {
    loom::model(|| {
        let kernel = Kernel::new();
        let first_kernel = Arc::clone(&kernel);
        let second_kernel = Arc::clone(&kernel);

        let first = thread::spawn(move || first_kernel.transact(1, 0, None));
        let second = thread::spawn(move || second_kernel.transact(2, 0, None));
        let first_committed = first.join().expect("first transaction does not panic");
        let second_committed = second.join().expect("second transaction does not panic");

        assert_ne!(first_committed, second_committed);
        let (winner, loser) = if first_committed { (1, 2) } else { (2, 1) };
        let mut expected = committed_sequence(winner);
        expected.extend(aborted_sequence(loser));
        assert_eq!(kernel.journal(), expected);
        assert_eq!(kernel.version(), 1);
    });
}

#[test]
fn precommit_failure_aborts_in_reverse_registration_order() {
    loom::model(|| {
        let kernel = Kernel::new();
        assert!(!kernel.transact(1, 0, Some(1)));
        assert_eq!(kernel.journal(), aborted_sequence(1));
        assert_eq!(kernel.version(), 0);
    });
}

#[test]
fn postcommit_publishes_in_registration_order_without_abort() {
    loom::model(|| {
        let kernel = Kernel::new();
        assert!(kernel.transact(1, 0, None));
        assert_eq!(kernel.journal(), committed_sequence(1));
        assert_eq!(kernel.version(), 1);
    });
}