Skip to main content

link_cli/engine/
mod.rs

1//! Optional staged links engine: concurrency, immutable history, and a
2//! replaceable commit log. See `docs/ENGINE-STRATEGIES.md` for costs and limits.
3//!
4//! Unlike the legacy undo decorator, no underlying mapped data is modified
5//! while a transaction is open. A checksummed logical revision is flushed
6//! before it becomes visible. The log is the authoritative storage.
7#[cfg(feature = "address-reservations")]
8pub mod address_allocator;
9#[cfg(feature = "author-fencing")]
10pub mod author_fence;
11#[cfg(not(target_arch = "wasm32"))]
12mod background_compaction;
13#[cfg(test)]
14mod boundary_tests;
15mod branch;
16#[cfg(feature = "causal")]
17pub mod causal;
18#[cfg(feature = "causal-batches")]
19pub mod causal_batch;
20#[cfg(feature = "causal-merkle")]
21pub mod causal_merkle;
22#[cfg(feature = "causal-sessions")]
23pub mod causal_named;
24#[cfg(feature = "causal-projection")]
25pub mod causal_projection;
26#[cfg(feature = "causal")]
27pub mod causal_replica;
28#[cfg(feature = "causal-sessions")]
29pub mod causal_session;
30mod changes;
31mod checkpoint;
32pub mod cluster;
33mod commit;
34#[cfg(test)]
35mod constraint_cost_tests;
36mod constraint_index;
37#[cfg(test)]
38mod cost_tests;
39mod delta;
40#[cfg(feature = "etcd")]
41pub mod etcd;
42mod group;
43mod journal;
44#[cfg(feature = "physical-lsm")]
45pub mod lsm;
46pub mod maintenance;
47mod named;
48mod object_cache;
49pub mod paged;
50pub mod partitioned;
51mod pessimistic;
52mod query_reservation;
53mod query_scratch;
54pub mod raft;
55pub mod reclaiming;
56pub mod recovery;
57pub mod replication;
58mod rows;
59mod savepoint;
60#[cfg(test)]
61mod shared_cost_tests;
62mod sorted_runs;
63#[cfg(all(feature = "sqlite", not(target_arch = "wasm32")))]
64pub mod sqlite;
65mod timed_log;
66mod transaction;
67mod validation;
68
69use crate::{GenericLink, LinkError, TransitionLogStore};
70use doublets::data::LinkReference;
71use std::collections::BTreeMap;
72use std::sync::{Arc, Mutex, MutexGuard};
73
74#[cfg(not(target_arch = "wasm32"))]
75pub use background_compaction::BackgroundCompaction;
76pub use branch::Branch;
77pub use checkpoint::restore_backup;
78pub use delta::DeltaLog;
79pub use group::GroupCommitOutcome;
80pub use journal::MemoryLog;
81use rows::Rows;
82pub use savepoint::Savepoint;
83pub use timed_log::{revision_at, TimedLog};
84pub use transaction::EngineTransaction;
85pub use validation::SerializableValidation;
86
87/// In-memory revision representation, independent of durability and isolation.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
89pub enum StateStructure {
90    /// Clone complete sorted rows for each changed revision (the existing path).
91    #[default]
92    Flat,
93    /// Share immutable entries and path-copy an ordered tree for changed rows.
94    Shared,
95    /// Share immutable sorted runs; merge occupied event-count tiers on writes.
96    SortedRuns,
97}
98
99/// Logical journal payload, independent of the physical log's encoding.
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
101pub enum RevisionEncoding {
102    /// Existing complete engine1 revisions.
103    #[default]
104    Snapshot,
105    /// Canonical engine2 changed-row records bound to the preceding revision.
106    Changes,
107}
108
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
110pub enum ConcurrencyControl {
111    #[default]
112    Optimistic,
113    /// A second transaction fails immediately rather than blocking indefinitely.
114    Exclusive,
115    /// Reserve written addresses until session end; competing writes fail fast
116    /// unless `lock_wait` is selected.
117    Pessimistic,
118}
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
121pub enum IsolationLevel {
122    ReadCommitted,
123    Snapshot,
124    /// Serializable commits; whole-revision validation is the default strategy.
125    #[default]
126    Serializable,
127}
128
129#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
130pub enum HistoryPolicy {
131    #[default]
132    None,
133    /// Includes the current revision; active transactions pin their own snapshot.
134    Last(usize),
135    All,
136}
137
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub enum Constraint {
140    /// Every nonzero source/target must reference a row in the committed state.
141    References,
142    /// Reject duplicate source/target pairs instead of silently merging them.
143    UniquePairs,
144    UniqueNames,
145}
146
147/// Constraint maintenance, independent of concurrency and serializable reads.
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
149pub enum ConstraintValidation {
150    /// Scan the complete candidate; no retained constraint indexes.
151    #[default]
152    Scan,
153    /// Retain immutable indexes only for selected constraints; update changed rows.
154    Indexed,
155}
156
157#[derive(Debug, Clone, Default)]
158pub struct EngineOptions {
159    pub state_structure: StateStructure,
160    pub revision_encoding: RevisionEncoding,
161    pub concurrency: ConcurrencyControl,
162    /// How long a pessimistic write waits for another session's address, instead
163    /// of failing at once. Native only: a wasm32 thread cannot wait for another.
164    pub lock_wait: Option<std::time::Duration>,
165    pub isolation: IsolationLevel,
166    pub serializable_validation: SerializableValidation,
167    pub history: HistoryPolicy,
168    pub constraints: Vec<Constraint>,
169    pub constraint_validation: ConstraintValidation,
170    pub trace: bool,
171    /// Reject volatile or unknown log adapters, rather than claiming durability.
172    pub require_durable_flush: bool,
173}
174
175impl EngineOptions {
176    fn tracks_generations(&self) -> bool {
177        self.concurrency == ConcurrencyControl::Pessimistic
178            || (self.concurrency == ConcurrencyControl::Optimistic
179                && (self.isolation != IsolationLevel::Serializable
180                    || self.serializable_validation == SerializableValidation::ReadSet))
181    }
182}
183
184#[derive(Debug, Clone, PartialEq, Eq)]
185pub struct Row<T> {
186    pub link: GenericLink<T>,
187    pub name: Option<String>,
188}
189
190/// Immutable revision, safe to keep after history retention or transaction end.
191#[derive(Debug, Clone)]
192pub struct Snapshot<T> {
193    pub revision: u64,
194    rows: Arc<Rows<T>>,
195}
196impl<T: LinkReference> Snapshot<T> {
197    pub fn links(&self) -> Vec<GenericLink<T>> {
198        self.rows.values().map(|row| row.link).collect()
199    }
200    pub fn get(&self, id: T) -> Option<&Row<T>> {
201        self.rows.get(&id)
202    }
203    /// Legacy sorted-map view. Shared snapshots lazily copy O(N) rows/names on
204    /// the first call; snapshot clones share that cache. Prefer `iter` or `get`.
205    pub fn rows(&self) -> &BTreeMap<T, Row<T>> {
206        self.rows.materialize()
207    }
208    /// Sorted borrowed rows without materializing the legacy BTreeMap view.
209    pub fn iter(&self) -> impl Iterator<Item = (&T, &Row<T>)> {
210        self.rows.iter()
211    }
212}
213
214struct State<T, L> {
215    log: L,
216    current: Snapshot<T>,
217    history: BTreeMap<u64, (Snapshot<T>, u128)>,
218    changed: BTreeMap<T, u64>,
219    write_owners: BTreeMap<T, Arc<()>>,
220    lock_waits: Option<pessimistic::LockWaits>,
221    next: u128,
222    committed_next: u128,
223    active: usize,
224    poisoned: bool,
225    /// The revision the last compaction published, for `compact_journal_after`.
226    compacted_revision: u64,
227    options: EngineOptions,
228    constraint_index: Option<constraint_index::ConstraintIndex<T>>,
229}
230
231/// Share clones of this handle across threads. All writes must use its sessions;
232/// opening multiple independent writers on the same log is not supported.
233pub struct Engine<T, L> {
234    state: Arc<Mutex<State<T, L>>>,
235}
236impl<T, L> Clone for Engine<T, L> {
237    fn clone(&self) -> Self {
238        Self {
239            state: self.state.clone(),
240        }
241    }
242}
243
244fn error(message: &str) -> LinkError {
245    LinkError::Transaction(message.into())
246}
247
248impl<T: LinkReference, L: TransitionLogStore> Engine<T, L> {
249    pub fn open(mut log: L, options: EngineOptions) -> Result<Self, LinkError> {
250        if options.serializable_validation == SerializableValidation::ReadSet
251            && options.isolation != IsolationLevel::Serializable
252        {
253            return Err(error("read-set validation requires serializable isolation"));
254        }
255        if options.lock_wait.is_some() && options.concurrency != ConcurrencyControl::Pessimistic {
256            return Err(error("lock waiting requires pessimistic concurrency"));
257        }
258        if options.require_durable_flush && !log.supports_durable_flush() {
259            return Err(error("selected log does not support durable flush"));
260        }
261        if options.history == HistoryPolicy::Last(0) {
262            return Err(error("history limit must be positive"));
263        }
264        let entries = log.read_log_entries()?;
265        let mut state = State::empty(log, options);
266        for (index, entry) in entries.iter().enumerate() {
267            state.replay(index, entry)?;
268        }
269        // No transaction predates open, so recovered rows need no conflict
270        // generations. Track only changes made while a session can be stale.
271        if state.options.constraint_validation == ConstraintValidation::Indexed {
272            state.constraint_index = constraint_index::ConstraintIndex::build(
273                &state.options.constraints,
274                &state.current.rows,
275            )?;
276        }
277        Ok(Self {
278            state: Arc::new(Mutex::new(state)),
279        })
280    }
281
282    fn lock(&self) -> Result<MutexGuard<'_, State<T, L>>, LinkError> {
283        let state = self
284            .state
285            .lock()
286            .map_err(|_| error("engine mutex poisoned"))?;
287        if state.poisoned {
288            return Err(error(
289                "indeterminate journal outcome; close and reopen before continuing",
290            ));
291        }
292        Ok(state)
293    }
294    pub fn snapshot(&self) -> Result<Snapshot<T>, LinkError> {
295        Ok(self.lock()?.current.clone())
296    }
297    pub fn snapshot_at(&self, revision: u64) -> Result<Snapshot<T>, LinkError> {
298        let state = self.lock()?;
299        if revision == state.current.revision {
300            return Ok(state.current.clone());
301        }
302        state
303            .history
304            .get(&revision)
305            .map(|(snapshot, _)| snapshot.clone())
306            .ok_or_else(|| error("revision is not retained"))
307    }
308    pub fn begin(&self) -> Result<EngineTransaction<T, L>, LinkError> {
309        let mut state = self.lock()?;
310        if state.options.concurrency == ConcurrencyControl::Exclusive && state.active > 0 {
311            return Err(error("busy: an exclusive transaction is active"));
312        }
313        state.active += 1;
314        Ok(EngineTransaction {
315            engine: self.clone(),
316            base: state.current.clone(),
317            writes: BTreeMap::new(),
318            savepoints: Vec::new(),
319            reserved: std::collections::VecDeque::new(),
320            closed: false,
321            isolation: state.options.isolation,
322            reads: (state.options.serializable_validation == SerializableValidation::ReadSet
323                && state.options.concurrency != ConcurrencyControl::Exclusive)
324                .then(|| Mutex::new(validation::ReadSet::default())),
325            locks: (state.options.concurrency == ConcurrencyControl::Pessimistic)
326                .then(pessimistic::WriteLocks::default),
327        })
328    }
329    /// Run a caller's replication/catch-up/diagnostics operation under the same
330    /// mutex as commits. An error poisons the engine because its outcome may be unknown.
331    pub fn with_log<R>(
332        &self,
333        operation: impl FnOnce(&mut L) -> Result<R, LinkError>,
334    ) -> Result<R, LinkError> {
335        let mut state = self.lock()?;
336        match operation(&mut state.log) {
337            Ok(result) => Ok(result),
338            Err(error) => {
339                state.poisoned = true;
340                Err(error)
341            }
342        }
343    }
344    /// Extract the authoritative log once every other handle/session is dropped.
345    pub fn into_log(self) -> Result<L, Self> {
346        match Arc::try_unwrap(self.state) {
347            Ok(mutex) => Ok(mutex
348                .into_inner()
349                .unwrap_or_else(|poison| poison.into_inner())
350                .log),
351            Err(state) => Err(Self { state }),
352        }
353    }
354}
355
356impl<T: LinkReference, L> State<T, L> {
357    /// Revision zero, before any record is replayed.
358    fn empty(log: L, options: EngineOptions) -> Self {
359        let mut state = State {
360            current: Snapshot {
361                revision: 0,
362                rows: Arc::new(Rows::new(options.state_structure)),
363            },
364            history: BTreeMap::new(),
365            changed: BTreeMap::new(),
366            write_owners: BTreeMap::new(),
367            lock_waits: options.lock_wait.map(pessimistic::LockWaits::new),
368            next: 1,
369            committed_next: 1,
370            active: 0,
371            poisoned: false,
372            compacted_revision: 0,
373            options,
374            constraint_index: None,
375            log,
376        };
377        state.retain();
378        state
379    }
380    /// Apply one recovered record with every rule `Engine::open` enforces.
381    /// Only a first record may be an engine3 checkpoint.
382    fn replay(&mut self, index: usize, entry: &str) -> Result<(), LinkError> {
383        let (snapshot, next) = if index == 0 && entry.starts_with("engine3|") {
384            let decoded = journal::decode_checkpoint(entry, self.options.state_structure)?;
385            self.history.clear();
386            decoded
387        } else {
388            journal::decode_after(
389                entry,
390                &self.current,
391                self.next,
392                self.options.state_structure,
393            )?
394        };
395        self.validate(&snapshot.rows)?;
396        self.next = next;
397        self.committed_next = next;
398        self.current = snapshot;
399        self.retain();
400        Ok(())
401    }
402    fn retain(&mut self) {
403        match self.options.history {
404            HistoryPolicy::None => {}
405            HistoryPolicy::All => {
406                self.history.insert(
407                    self.current.revision,
408                    (self.current.clone(), self.committed_next),
409                );
410            }
411            HistoryPolicy::Last(limit) => {
412                self.history.insert(
413                    self.current.revision,
414                    (self.current.clone(), self.committed_next),
415                );
416                while self.history.len() > limit {
417                    self.history.pop_first();
418                }
419            }
420        }
421    }
422    fn validate(&self, rows: &Rows<T>) -> Result<(), LinkError> {
423        let zero = T::from_byte(0);
424        for constraint in &self.options.constraints {
425            match constraint {
426                Constraint::References => {
427                    for row in rows.values() {
428                        if [row.link.source, row.link.target]
429                            .iter()
430                            .any(|id| *id != zero && !rows.contains_key(id))
431                        {
432                            return Err(error("constraint: dangling link reference"));
433                        }
434                    }
435                }
436                Constraint::UniquePairs => {
437                    let mut pairs = std::collections::BTreeSet::new();
438                    for row in rows.values() {
439                        if !pairs.insert((row.link.source, row.link.target)) {
440                            return Err(error("constraint: duplicate pair"));
441                        }
442                    }
443                }
444                Constraint::UniqueNames => {
445                    let mut names = std::collections::BTreeSet::new();
446                    for name in rows.values().filter_map(|row| row.name.as_ref()) {
447                        if !names.insert(name) {
448                            return Err(error("constraint: duplicate name"));
449                        }
450                    }
451                }
452            }
453        }
454        Ok(())
455    }
456}