Skip to main content

link_cli/engine/
group.rs

1//! Opt-in coordination of independent sessions at one durability boundary.
2use super::{error, Engine, EngineTransaction, MemoryLog, State};
3use crate::{LinkError, TransitionLogStore};
4use doublets::data::LinkReference;
5use std::sync::Arc;
6
7/// One independent session's result, in the caller's input order.
8#[derive(Debug, PartialEq, Eq)]
9pub enum GroupCommitOutcome {
10    /// Acknowledged after the shared flush (or no journal I/O was necessary).
11    Committed(u64),
12    /// Validation failed before this session appended any physical record.
13    Aborted(String),
14    /// No acknowledgement: reopening must discover which prefix persisted.
15    Indeterminate(String),
16}
17
18impl<T: LinkReference, L: TransitionLogStore> Engine<T, L> {
19    /// Consume independent sessions and share one flush across accepted writes.
20    /// Validation follows input order and retains the configured isolation rules.
21    /// Each write session retains its own revision; this is not an atomic batch.
22    /// An uncertain append/flush fences the engine and retains its old visible
23    /// state. All provisionally accepted members then return `Indeterminate`,
24    /// including read-only members that may depend on a tentative revision.
25    ///
26    /// Foreign sessions cause an outer error before I/O; consumed sessions are
27    /// rolled back on that path. A log that syncs on every append still performs
28    /// those syncs; select buffered append with durable flush to amortize them.
29    /// Private preparation retains history/map metadata and selected logical
30    /// revision records until publication. Ordinary commits keep their own path.
31    pub fn commit_group(
32        &self,
33        mut sessions: Vec<EngineTransaction<T, L>>,
34    ) -> Result<Vec<GroupCommitOutcome>, LinkError> {
35        if sessions
36            .iter()
37            .any(|tx| !Arc::ptr_eq(&self.state, &tx.engine.state))
38        {
39            return Err(error("group sessions must belong to the same engine"));
40        }
41        let mut state = self.lock()?;
42        let mut options = state.options.clone();
43        options.trace = false;
44        let mut working = State {
45            log: MemoryLog::default(),
46            current: state.current.clone(),
47            history: state.history.clone(),
48            changed: state.changed.clone(),
49            write_owners: state.write_owners.clone(),
50            lock_waits: None,
51            next: state.next,
52            committed_next: state.committed_next,
53            active: state.active,
54            poisoned: false,
55            compacted_revision: state.compacted_revision,
56            options,
57            constraint_index: state.constraint_index.clone(),
58        };
59        let mut outcomes = Vec::with_capacity(sessions.len());
60        for tx in &mut sessions {
61            let base = tx.base.clone();
62            let outcome = match tx.commit_locked(&mut working) {
63                Ok(revision) => GroupCommitOutcome::Committed(revision),
64                Err(cause) => GroupCommitOutcome::Aborted(cause.to_string()),
65            };
66            tx.base = base;
67            outcomes.push(outcome);
68        }
69        // Only ownership/admission cleanup is real until durability succeeds.
70        // Read-committed sessions outside this group must retain the old view
71        // if the physical log fails after writing an unknown prefix.
72        state.active = working.active;
73        state.write_owners = working.write_owners;
74        if let Some(waits) = &mut state.lock_waits {
75            waits.wake_all();
76        }
77        let persisted = (|| {
78            for record in &working.log.entries {
79                state.log.append_log_entry(record)?;
80            }
81            if !working.log.entries.is_empty() {
82                state.log.flush_log()?;
83            }
84            Ok::<(), LinkError>(())
85        })();
86        if let Err(cause) = persisted {
87            state.poisoned = true;
88            if state.active == 0 {
89                state.changed.clear();
90            }
91            let message = format!("indeterminate group commit: {cause}; reopen the engine");
92            for outcome in &mut outcomes {
93                if matches!(outcome, GroupCommitOutcome::Committed(_)) {
94                    *outcome = GroupCommitOutcome::Indeterminate(message.clone());
95                }
96            }
97            return Ok(outcomes);
98        }
99        state.current = working.current;
100        state.constraint_index = working.constraint_index;
101        state.history = working.history;
102        state.changed = working.changed;
103        state.committed_next = working.committed_next;
104        if state.options.trace && !working.log.entries.is_empty() {
105            crate::diagnostics::stderr!(
106                "[Engine] group committed revision={} records={}",
107                state.current.revision,
108                working.log.entries.len()
109            );
110        }
111        Ok(outcomes)
112    }
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118    use crate::{
119        engine::{ConcurrencyControl, EngineOptions},
120        LinksStorage,
121    };
122    struct Unavailable;
123    impl TransitionLogStore for Unavailable {
124        fn read_log_entries(&mut self) -> Result<Vec<String>, LinkError> {
125            Ok(vec![])
126        }
127        fn append_log_entry(&mut self, _: &str) -> Result<(), LinkError> {
128            Err(error("append unavailable"))
129        }
130        fn flush_log(&mut self) -> Result<(), LinkError> {
131            Ok(())
132        }
133    }
134    #[test]
135    fn uncertain_and_already_fenced_groups_release_admission_and_point_ownership() {
136        for concurrency in [
137            ConcurrencyControl::Exclusive,
138            ConcurrencyControl::Pessimistic,
139        ] {
140            let db = Engine::<u32, _>::open(
141                Unavailable,
142                EngineOptions {
143                    concurrency,
144                    ..Default::default()
145                },
146            )
147            .unwrap();
148            let mut first = db.begin().unwrap();
149            first.create_link(0, 0).unwrap();
150            assert!(matches!(
151                db.commit_group(vec![first]).unwrap()[0],
152                GroupCommitOutcome::Indeterminate(_)
153            ));
154            let state = db.state.lock().unwrap();
155            assert_eq!(state.active, 0);
156            assert!(state.write_owners.is_empty());
157            assert!(state.changed.is_empty());
158            drop(state);
159            // A group rejected at admission still consumes/rolls back its open
160            // members. Use a fresh engine to retain an owner before fencing it.
161            let db = Engine::<u32, _>::open(
162                Unavailable,
163                EngineOptions {
164                    concurrency,
165                    ..Default::default()
166                },
167            )
168            .unwrap();
169            let mut held = db.begin().unwrap();
170            held.create_link(0, 0).unwrap();
171            assert!(db.with_log::<()>(|_| Err(error("unknown"))).is_err());
172            assert!(db.commit_group(vec![held]).is_err());
173            let state = db.state.lock().unwrap();
174            assert_eq!(state.active, 0);
175            assert!(state.write_owners.is_empty());
176        }
177    }
178}