Skip to main content

link_cli/transactions/
mod.rs

1//! Optional transactions layer for the Rust link-cli.
2//!
3//! Mirrors the C# `TransactionsDecorator` in
4//! `csharp/Foundation.Data.Doublets.Cli.Library/TransactionsDecorator.cs`.
5//!
6//! The decorator records every `create` / `update` / `delete` as a
7//! reversible [`GenericTransition`] in a sidecar log. It supports
8//! explicit transactions, sync commits, three retention policies, and
9//! crash recovery (R1-R7, R10).
10//!
11//! Optional — when not opted in, the bare
12//! [`NamedTypesDecorator`] behaves
13//! identically (R8, R9, R17).
14//!
15//! # Reuse outside the CLI
16//!
17//! [`GenericTransactionsDecorator`] is generic over three things:
18//!
19//! * `T` — the doublets address type (`u32`, `u64`, `usize`, ...);
20//! * `S` — the wrapped store, any [`LinksStorage<T>`] implementation,
21//!   including [`DoubletsStorage`](crate::DoubletsStorage) over a
22//!   file-mapped or caller-owned `doublets::unit::Store`;
23//! * `L` — the transitions log, any [`TransitionLogStore`].
24//!
25//! [`TransactionsDecorator`] is the `u32` + `NamedTypesDecorator`
26//! specialisation used by `clink` itself.
27//!
28//! ```no_run
29//! use link_cli::transactions::{
30//!     CommitMode, FileTransitionLog, GenericTransactionsDecorator, LogRetentionPolicy,
31//! };
32//! use link_cli::DoubletsStorage;
33//!
34//! # fn main() -> Result<(), link_cli::LinkError> {
35//! let store = DoubletsStorage::<usize, _>::open_exclusive("db.links")?;
36//! let log = FileTransitionLog::open("db.transitions.log")?;
37//! let mut tx = GenericTransactionsDecorator::new(
38//!     store,
39//!     log,
40//!     LogRetentionPolicy::default(),
41//!     CommitMode::default(),
42//!     false,
43//! )?;
44//!
45//! tx.begin_transaction()?;
46//! let link = tx.create(0, 0)?;
47//! tx.commit()?;
48//! tx.save()?;
49//! # let _ = link;
50//! # Ok(())
51//! # }
52//! ```
53//!
54//! # Durability
55//!
56//! Transitions are durably logged before commit is acknowledged. Commit then
57//! flushes the wrapped data before persisting its applied markers. Recovery
58//! replays committed-but-unapplied transitions and undoes logged uncommitted
59//! changes, reporting replay and flush failures.
60//!
61//! The default [`RowUndoPolicy::Observed`] mutates the store before recording
62//! callbacks and leaves a crash window for unlogged changes. Select
63//! [`RowUndoPolicy::WriteAheadImage`] to flush a complete logical undo image
64//! before the first effect and reconcile complete history after each write.
65//! It requires exclusive ownership and an adapter supporting logical replay;
66//! it does not repair torn physical storage. The optional
67//! [`crate::engine::Engine`] stages private changes until durable publication.
68
69mod log;
70// Replay, recovery and retention live in a submodule; see transactions/recovery.rs.
71mod commit;
72mod compaction;
73mod journal_file;
74mod journal_validation;
75mod migration_state;
76mod names;
77mod record;
78mod recording;
79mod recovery;
80mod row_undo;
81mod types;
82mod undo_image;
83mod version_replay;
84
85use std::collections::HashSet;
86use std::path::{Path, PathBuf};
87use std::sync::atomic::{AtomicU64, Ordering};
88use web_time::{SystemTime, UNIX_EPOCH};
89
90use doublets::data::LinkReference;
91
92use crate::error::LinkError;
93use crate::link::GenericLink;
94use crate::named_types::NamedTypesDecorator;
95use crate::storage::{LinksStorage, LinksStorageRef};
96
97pub use journal_file::{
98    import_links_journal, is_links_journal, make_legacy_transitions_filename,
99    make_transitions_log_filename, open_transitions_journal,
100};
101pub use log::{FileTransitionLog, ReplaceableTransitionLogStore, TransitionLogStore};
102pub use record::{JournalRecord, NameChange};
103pub use types::{
104    CommitMode, DoubletLink, GenericDoubletLink, GenericTransition, LogRetentionPolicy, Transition,
105    TransitionKind,
106};
107use types::{COMMIT_MARKER_PREFIX, ROLLBACK_MARKER_PREFIX, TRANSITION_NAME_PREFIX};
108pub use undo_image::RowUndoPolicy;
109
110/// Pending state of a transaction (used by the explicit transaction
111/// handle and by per-write auto-transactions).
112#[derive(Clone)]
113struct PendingTransaction<T> {
114    id: u128,
115    transitions: Vec<JournalRecord<T>>,
116    auto_commit: bool,
117    rollback_only: bool,
118    commit_attempted: bool,
119    started_ms: i64,
120    image: Option<undo_image::UndoImage<T>>,
121}
122
123/// One link address and the `(before, after)` states a single logical
124/// write left it in, after collapsing repeated callbacks for that address.
125type ObservedChange<T> = (T, GenericDoubletLink<T>, GenericDoubletLink<T>);
126type TransitionChange<T> = (TransitionKind, GenericDoubletLink<T>, GenericDoubletLink<T>);
127
128/// Folds one `(before, after)` callback into `observed`.
129///
130/// Mirrors the handler `TransactionsDecorator.RunWrite` installs in the C#
131/// implementation: repeated callbacks for the same address are collapsed into
132/// a single change that keeps the *first* `before` (the state the rollback has
133/// to restore) and the *last* `after` (the state the write ended at), and the
134/// first-seen order of addresses is preserved so the transitions replay in the
135/// order the storage produced them.
136fn record_observed<T: LinkReference>(
137    observed: &mut Vec<ObservedChange<T>>,
138    before: GenericLink<T>,
139    after: GenericLink<T>,
140) {
141    let zero = T::from_byte(0);
142    let key = if before.index != zero {
143        before.index
144    } else {
145        after.index
146    };
147    if key == zero {
148        return;
149    }
150    let before = GenericDoubletLink::from_link(&before);
151    let after = GenericDoubletLink::from_link(&after);
152    match observed.iter_mut().find(|(index, _, _)| *index == key) {
153        Some(entry) => {
154            // A null first before means the address did not exist. A later
155            // update must not replace it with the intermediate created row.
156            entry.2 = after;
157        }
158        None => observed.push((key, before, after)),
159    }
160}
161
162/// Snapshot of an open transaction (returned by [`GenericTransactionsDecorator::begin_transaction`]).
163#[derive(Debug, Clone)]
164pub struct TransactionHandle {
165    pub id: u128,
166    pub started_ms: i64,
167}
168
169/// The transactions decorator wraps any [`LinksStorage`] and records
170/// every write as a reversible [`GenericTransition`] in `log_store`.
171pub struct GenericTransactionsDecorator<T, S, L>
172where
173    T: LinkReference,
174    S: LinksStorage<T>,
175    L: TransitionLogStore,
176{
177    inner: S,
178    log_store: L,
179    log: Vec<JournalRecord<T>>,
180    committed: HashSet<u128>,
181    rolled_back: HashSet<u128>,
182    applied: HashSet<i64>,
183    current: Option<PendingTransaction<T>>,
184    sequence_counter: i64,
185    applied_sequence: i64,
186    retention_policy: LogRetentionPolicy,
187    commit_mode: CommitMode,
188    version_replay: bool,
189    recovery_pending: bool,
190    reload_pending: bool,
191    trace: bool,
192    defer_checkpoint: bool,
193    row_undo: RowUndoPolicy,
194    /// Entries in the durable journal, and its newest commit/rollback marker.
195    journal_entries: usize,
196    last_decision: Option<String>,
197}
198
199/// The `u32` + [`NamedTypesDecorator`] specialisation with the original
200/// links-backed sidecar log.
201pub type TransactionsDecorator =
202    GenericTransactionsDecorator<u32, NamedTypesDecorator, NamedTypesDecorator>;
203
204/// The specialisation `clink` uses: an append-only [`FileTransitionLog`]
205/// journal, whose cost per write does not grow with history (issue #195).
206pub type FileTransactionsDecorator =
207    GenericTransactionsDecorator<u32, NamedTypesDecorator, FileTransitionLog>;
208
209impl<T, S, L> GenericTransactionsDecorator<T, S, L>
210where
211    T: LinkReference,
212    S: LinksStorage<T>,
213    L: TransitionLogStore,
214{
215    /// Creates a new transactions decorator wrapping `inner`, using
216    /// `log_store` as the sidecar log. Runs crash recovery before
217    /// returning.
218    pub fn new(
219        inner: S,
220        log_store: L,
221        retention_policy: LogRetentionPolicy,
222        commit_mode: CommitMode,
223        trace: bool,
224    ) -> Result<Self, LinkError> {
225        let mut decorator = Self {
226            inner,
227            log_store,
228            log: Vec::new(),
229            committed: HashSet::new(),
230            rolled_back: HashSet::new(),
231            applied: HashSet::new(),
232            current: None,
233            sequence_counter: 0,
234            applied_sequence: 0,
235            retention_policy,
236            commit_mode,
237            version_replay: false,
238            recovery_pending: false,
239            reload_pending: false,
240            trace,
241            defer_checkpoint: false,
242            row_undo: RowUndoPolicy::Observed,
243            journal_entries: 0,
244            last_decision: None,
245        };
246        decorator.recover()?;
247        Ok(decorator)
248    }
249
250    /// Conventional filename of the links-backed transitions log
251    /// (`<stem>.transitions.links`). `clink` now keeps its journal in
252    /// [`make_transitions_log_filename`] and imports this store once.
253    pub fn make_transitions_database_filename<P: AsRef<Path>>(database_filename: P) -> PathBuf {
254        let path = database_filename.as_ref();
255        let stem = path
256            .file_stem()
257            .and_then(|s| s.to_str())
258            .unwrap_or_default();
259        let name = format!("{stem}.transitions.links");
260        match path.parent() {
261            Some(parent) if !parent.as_os_str().is_empty() => parent.join(name),
262            _ => PathBuf::from(name),
263        }
264    }
265
266    pub fn retention_policy(&self) -> &LogRetentionPolicy {
267        &self.retention_policy
268    }
269
270    pub fn set_retention_policy(&mut self, policy: LogRetentionPolicy) {
271        self.retention_policy = policy;
272    }
273
274    pub fn commit_mode(&self) -> CommitMode {
275        self.commit_mode
276    }
277
278    pub fn set_commit_mode(&mut self, mode: CommitMode) {
279        self.commit_mode = mode;
280    }
281
282    pub fn applied_sequence(&self) -> i64 {
283        self.applied_sequence
284    }
285
286    pub fn last_logged_sequence(&self) -> i64 {
287        self.sequence_counter
288    }
289
290    /// Higher layers must distinguish a durable decision from a failed
291    /// checkpoint before deciding whether cleanup may undo the transaction.
292    pub(crate) fn is_transaction_committed(&self, id: u128) -> bool {
293        self.committed.contains(&id)
294    }
295
296    pub(crate) fn is_transaction_rolled_back(&self, id: u128) -> bool {
297        self.rolled_back.contains(&id)
298    }
299
300    pub(crate) fn has_open_transaction(&self) -> bool {
301        self.current.is_some() || self.version_replay || self.recovery_pending
302    }
303
304    pub(crate) fn must_finish_commit(&self, id: u128) -> bool {
305        self.is_transaction_committed(id)
306            || self
307                .current
308                .as_ref()
309                .is_some_and(|pending| pending.id == id && pending.commit_attempted)
310    }
311
312    /// Returns a snapshot of the transitions log in sequence order.
313    pub fn log(&self) -> Vec<GenericTransition<T>> {
314        self.log.iter().map(|record| record.transition).collect()
315    }
316
317    /// Complete retained records, including optional name payloads.
318    pub fn journal(&self) -> Vec<JournalRecord<T>> {
319        self.log.clone()
320    }
321
322    pub fn inner(&self) -> &S {
323        &self.inner
324    }
325
326    pub fn inner_mut(&mut self) -> &mut S {
327        &mut self.inner
328    }
329
330    pub fn log_store(&self) -> &L {
331        &self.log_store
332    }
333
334    pub fn log_store_mut(&mut self) -> &mut L {
335        &mut self.log_store
336    }
337
338    pub fn into_inner(self) -> (S, L) {
339        (self.inner, self.log_store)
340    }
341
342    /// Makes both the data store and the transitions log durable.
343    pub fn flush(&mut self) -> Result<(), LinkError> {
344        if self.recovery_pending {
345            return self.recover();
346        }
347        self.ensure_no_version_replay()?;
348        if self
349            .current
350            .as_ref()
351            .is_some_and(|pending| pending.commit_attempted)
352        {
353            return self.commit_current();
354        }
355        if self.defer_checkpoint && self.current.is_some() {
356            return Ok(());
357        }
358        self.inner.flush()?;
359        self.log_store.flush_log()?;
360        Ok(())
361    }
362
363    /// Alias of [`flush`](Self::flush), kept for parity with the other
364    /// decorators and with the C# API.
365    pub fn save(&mut self) -> Result<(), LinkError> {
366        self.flush()
367    }
368
369    /// Cheap check for "has another process written to the wrapped
370    /// store since we last read or wrote it?".
371    pub fn has_external_changes(&self) -> Result<bool, LinkError> {
372        self.inner.has_external_changes()
373    }
374
375    /// Re-reads the wrapped store and rebuilds the transactions state
376    /// from the log — the recovery path after another process wrote.
377    pub fn reload(&mut self) -> Result<(), LinkError> {
378        if self.current.is_some() || self.version_replay {
379            return Err(LinkError::Transaction(
380                "Cannot reload while a transaction is open.".to_string(),
381            ));
382        }
383        self.recovery_pending = true;
384        self.reload_pending = true;
385        self.recover()
386    }
387
388    // ----- Write API ------------------------------------------------------
389
390    pub fn create(&mut self, source: T, target: T) -> Result<T, LinkError> {
391        let names_before = self.inner.capture_names()?;
392        let owns = self.ensure_open_transaction()?;
393        let mut observed = Vec::new();
394        let outcome = self
395            .inner
396            .create_link_observed(source, target, &mut |before, after| {
397                record_observed(&mut observed, before, after)
398            });
399        self.record_observed_transitions(&observed, owns, names_before.as_ref())?;
400        let id = match outcome {
401            Ok(id) => id,
402            Err(error) => {
403                self.fence_failed_image();
404                if owns {
405                    if observed.is_empty()
406                        && self
407                            .current
408                            .as_ref()
409                            .is_none_or(|owner| owner.image.is_none())
410                    {
411                        self.current = None;
412                    } else {
413                        self.rollback()?;
414                    }
415                }
416                return Err(error);
417            }
418        };
419        self.complete_image_observations(owns)?;
420        if owns {
421            self.commit_current()?;
422        }
423        Ok(id)
424    }
425
426    pub fn update(&mut self, id: T, source: T, target: T) -> Result<GenericLink<T>, LinkError> {
427        self.update_observed(id, source, target, &mut |_, _| {})
428    }
429
430    /// [`Self::update`], reporting every change the underlying store made.
431    ///
432    /// An update that would duplicate an existing doublet is resolved into a
433    /// merge that deletes the updated link, so one call can report several
434    /// changes, exactly like C#'s `links.Update(restriction, substitution, handler)`.
435    pub fn update_observed(
436        &mut self,
437        id: T,
438        source: T,
439        target: T,
440        observer: &mut dyn FnMut(GenericLink<T>, GenericLink<T>),
441    ) -> Result<GenericLink<T>, LinkError> {
442        let before = self.snapshot(id);
443        let names_before = self.inner.capture_names()?;
444        let owns = self.ensure_open_transaction()?;
445        let mut observed: Vec<ObservedChange<T>> = Vec::new();
446        let outcome = self
447            .inner
448            .update_link_observed(id, source, target, &mut |before, after| {
449                observer(before, after);
450                record_observed(&mut observed, before, after)
451            });
452        let prev = match outcome {
453            Ok(prev) => prev,
454            Err(err) => {
455                self.fence_failed_image();
456                // Callbacks describe changes already made, even if a later
457                // part of the storage operation fails.
458                self.record_observed_transitions(&observed, owns, names_before.as_ref())?;
459                if owns {
460                    if observed.is_empty()
461                        && self
462                            .current
463                            .as_ref()
464                            .is_none_or(|owner| owner.image.is_none())
465                    {
466                        self.current = None;
467                    } else {
468                        self.rollback()?;
469                    }
470                }
471                return Err(err);
472            }
473        };
474        if observed.is_empty() {
475            let after = self
476                .inner
477                .get_link(id)
478                .map(|link| GenericDoubletLink::from_link(&link))
479                .unwrap_or_else(|| GenericDoubletLink::new(id, source, target));
480            self.record_transition(
481                TransitionKind::Update,
482                before,
483                after,
484                owns,
485                names_before.as_ref(),
486            )?;
487        } else {
488            self.record_observed_transitions(&observed, owns, names_before.as_ref())?;
489        }
490        self.complete_image_observations(owns)?;
491        if owns {
492            self.commit_current()?;
493        }
494        Ok(prev)
495    }
496
497    pub fn delete(&mut self, id: T) -> Result<GenericLink<T>, LinkError> {
498        self.delete_observed(id, &mut |_, _| {})
499    }
500
501    /// [`Self::delete`], reporting every change the underlying store made.
502    ///
503    /// Deleting a link cascades into every link that still used it, and those
504    /// deletions are changes of their own: the C# CLI hands
505    /// `AdvancedMixedQueryProcessor.RemoveLinks` a handler that `links.Delete`
506    /// calls once per removed link, so `--changes` lists the usages too. The
507    /// observer is the same seam, threaded through the decorator stack.
508    pub fn delete_observed(
509        &mut self,
510        id: T,
511        observer: &mut dyn FnMut(GenericLink<T>, GenericLink<T>),
512    ) -> Result<GenericLink<T>, LinkError> {
513        let before = self.snapshot(id);
514        let names_before = self.inner.capture_names()?;
515        let owns = self.ensure_open_transaction()?;
516        let mut observed: Vec<ObservedChange<T>> = Vec::new();
517        let outcome = self.inner.delete_link_observed(id, &mut |before, after| {
518            observer(before, after);
519            record_observed(&mut observed, before, after)
520        });
521        let deleted = match outcome {
522            Ok(d) => d,
523            Err(err) => {
524                self.fence_failed_image();
525                // Callbacks describe changes already made, even if a later
526                // part of the storage operation fails.
527                self.record_observed_transitions(&observed, owns, names_before.as_ref())?;
528                if owns {
529                    if observed.is_empty()
530                        && self
531                            .current
532                            .as_ref()
533                            .is_none_or(|owner| owner.image.is_none())
534                    {
535                        self.current = None;
536                    } else {
537                        self.rollback()?;
538                    }
539                }
540                return Err(err);
541            }
542        };
543        if observed.is_empty() {
544            self.record_transition(
545                TransitionKind::Delete,
546                before,
547                GenericDoubletLink::empty(),
548                owns,
549                names_before.as_ref(),
550            )?;
551        } else {
552            self.record_observed_transitions(&observed, owns, names_before.as_ref())?;
553        }
554        self.complete_image_observations(owns)?;
555        if owns {
556            self.commit_current()?;
557        }
558        Ok(deleted)
559    }
560
561    /// Composite create-and-update used by callers that want a link
562    /// initialised with source/target in a single pair of transitions
563    /// (matches the C# `CreateAndUpdate` extension semantics, which
564    /// always emits a Create followed by an Update transition).
565    pub fn create_and_update(&mut self, source: T, target: T) -> Result<T, LinkError> {
566        let owns = self.ensure_open_transaction()?;
567        let zero = T::from_byte(0);
568        let outcome = self.create(zero, zero).and_then(|id| {
569            self.update(id, source, target)?;
570            Ok(id)
571        });
572        let id = match outcome {
573            Ok(id) => id,
574            Err(error) => {
575                self.fence_failed_image();
576                if owns {
577                    self.rollback()?;
578                }
579                return Err(error);
580            }
581        };
582        if owns {
583            self.commit_current()?;
584        }
585        Ok(id)
586    }
587
588    pub fn exists(&self, id: T) -> bool {
589        self.inner.link_exists(id)
590    }
591
592    pub fn search(&self, source: T, target: T) -> Option<T> {
593        self.inner.search_link(source, target)
594    }
595
596    pub fn get_or_create(&mut self, source: T, target: T) -> Result<T, LinkError> {
597        if let Some(existing) = self.inner.search_link(source, target) {
598            return Ok(existing);
599        }
600        self.create(source, target)
601    }
602
603    pub fn ensure_created(&mut self, id: T) -> Result<T, LinkError> {
604        if id == T::from_byte(0) || self.inner.link_exists(id) {
605            return Ok(id);
606        }
607        let names_before = self.inner.capture_names()?;
608        let owns = self.ensure_open_transaction()?;
609        let mut observed = Vec::new();
610        let outcome = self
611            .inner
612            .ensure_link_created_observed(id, &mut |before, after| {
613                record_observed(&mut observed, before, after)
614            });
615        self.record_observed_transitions(&observed, owns, names_before.as_ref())?;
616        match outcome {
617            Ok(created) => {
618                self.complete_image_observations(owns)?;
619                if owns {
620                    self.commit_current()?;
621                }
622                Ok(created)
623            }
624            Err(error) => {
625                self.fence_failed_image();
626                if owns {
627                    self.rollback()?;
628                }
629                Err(error)
630            }
631        }
632    }
633
634    /// Current state of `id` as a doublet, or an empty one at `id`.
635    fn snapshot(&self, id: T) -> GenericDoubletLink<T> {
636        let zero = T::from_byte(0);
637        self.inner
638            .get_link(id)
639            .map(|link| GenericDoubletLink::from_link(&link))
640            .unwrap_or_else(|| GenericDoubletLink::new(id, zero, zero))
641    }
642
643    pub(crate) fn ensure_write_allowed(&self) -> Result<(), LinkError> {
644        self.ensure_no_version_replay()?;
645        self.ensure_recovery_complete()?;
646        if self
647            .current
648            .as_ref()
649            .is_some_and(|pending| pending.commit_attempted)
650        {
651            return Err(LinkError::Transaction(
652                "Retry transaction commit before further writes; its outcome may be unknown."
653                    .into(),
654            ));
655        }
656        if self.current.as_ref().is_some_and(|tx| tx.rollback_only) {
657            return Err(LinkError::Transaction(
658                "Transaction requires rollback before further writes.".into(),
659            ));
660        }
661        Ok(())
662    }
663
664    fn ensure_open_transaction(&mut self) -> Result<bool, LinkError> {
665        self.ensure_write_allowed()?;
666        if self.sequence_counter == i64::MAX {
667            return Err(LinkError::Transaction(
668                "Transaction sequence space is exhausted.".into(),
669            ));
670        }
671        let owns = self.current.is_none();
672        if owns {
673            self.current = Some(PendingTransaction {
674                id: self.allocate_transaction_id(),
675                transitions: Vec::new(),
676                auto_commit: true,
677                rollback_only: false,
678                commit_attempted: false,
679                started_ms: now_unix_ms(),
680                image: None,
681            });
682        }
683        if let Err(error) = self.prepare_row_undo() {
684            self.current
685                .as_mut()
686                .expect("open transaction")
687                .rollback_only = true;
688            if owns {
689                self.rollback()?;
690            }
691            return Err(error);
692        }
693        Ok(owns)
694    }
695
696    fn write_marker(&mut self, name: &str) -> Result<(), LinkError> {
697        if name.starts_with(COMMIT_MARKER_PREFIX) || name.starts_with(ROLLBACK_MARKER_PREFIX) {
698            self.last_decision = Some(name.to_string());
699        }
700        self.append_journal_entry(name)
701    }
702
703    // ----- Transaction handle --------------------------------------------
704
705    fn allocate_transaction_id(&self) -> u128 {
706        // Realtime can repeat after restart while the process counter resets.
707        // Durable decisions outlive retained payloads, so consult the existing
708        // recovered indexes before assigning an ID to either kind of owner.
709        let mut collided = false;
710        loop {
711            let id = new_transaction_id();
712            if id != 0 && !self.committed.contains(&id) && !self.rolled_back.contains(&id) {
713                if collided && self.trace {
714                    crate::diagnostics::stderr!(
715                        "[Transactions] Skipped previously decided transaction IDs."
716                    );
717                }
718                return id;
719            }
720            collided = true;
721        }
722    }
723
724    pub fn begin_transaction(&mut self) -> Result<TransactionHandle, LinkError> {
725        self.ensure_no_version_replay()?;
726        self.ensure_recovery_complete()?;
727        if self.current.is_some() {
728            return Err(LinkError::Transaction(
729                "Nested transactions are not supported.".to_string(),
730            ));
731        }
732        let id = self.allocate_transaction_id();
733        let started_ms = now_unix_ms();
734        self.current = Some(PendingTransaction {
735            id,
736            transitions: Vec::new(),
737            auto_commit: false,
738            rollback_only: false,
739            commit_attempted: false,
740            started_ms,
741            image: None,
742        });
743        Ok(TransactionHandle { id, started_ms })
744    }
745
746    /// Finish the transaction. An append/flush error can have an unknown
747    /// outcome: retry commit, rollback or save to finish the attempted decision.
748    /// Further writes remain fenced until that work succeeds.
749    pub fn commit(&mut self) -> Result<(), LinkError> {
750        if self.recovery_pending {
751            return self.recover();
752        }
753        if self.current.is_none() {
754            return Ok(());
755        }
756        self.commit_current()
757    }
758
759    /// Undo an open transaction, or finish its attempted commit if a previous
760    /// commit failed with a possibly durable decision.
761    pub fn rollback(&mut self) -> Result<(), LinkError> {
762        if self.recovery_pending {
763            return self.recover();
764        }
765        if self
766            .current
767            .as_ref()
768            .is_some_and(|pending| pending.commit_attempted)
769        {
770            // A commit append/flush may have persisted before returning an error.
771            return self.commit_current();
772        }
773        // Once undo begins, an error can leave the data partially restored.
774        // Keep the abort decision until every rollback step succeeds.
775        if let Some(current) = self.current.as_mut() {
776            current.rollback_only = true;
777        }
778        let pending = match self.current.clone() {
779            Some(p) => p,
780            None => return Ok(()),
781        };
782        if self.defer_checkpoint && pending.transitions.is_empty() && pending.image.is_none() {
783            self.current = None;
784            return Ok(());
785        }
786        let result = if let Some(image) = &pending.image {
787            self.restore_image(image)
788        } else {
789            pending
790                .transitions
791                .iter()
792                .rev()
793                .try_for_each(|transition| self.try_revert_record(transition))
794        };
795        result?;
796        self.inner.flush()?;
797        self.write_marker(&format!("{ROLLBACK_MARKER_PREFIX}{:032x}", pending.id))?;
798        self.log_store.flush_log()?;
799        self.rolled_back.insert(pending.id);
800        self.current = None;
801        if self.trace {
802            crate::diagnostics::stderr!(
803                "[Transactions] Rolled back tx {:032x} ({} transitions).",
804                pending.id,
805                pending.transitions.len(),
806            );
807        }
808        self.enforce_retention()?;
809        Ok(())
810    }
811}
812
813impl FileTransactionsDecorator {
814    /// Defer file writes requested within a CLI batch to its final checkpoint.
815    /// The named store keeps edits in memory and the commit still syncs the
816    /// journal before saving data and again after writing the applied markers.
817    pub fn defer_batch_checkpoint(&mut self) {
818        self.defer_checkpoint = true;
819        self.log_store.set_sync_on_append(false);
820    }
821}
822
823/// Read paths that lend out references, available whenever the wrapped
824/// store keeps its links resident in memory.
825impl<T, S, L> GenericTransactionsDecorator<T, S, L>
826where
827    T: LinkReference,
828    S: LinksStorageRef<T>,
829    L: TransitionLogStore,
830{
831    pub fn get(&self, id: T) -> Option<&GenericLink<T>> {
832        self.inner.get_link_ref(id)
833    }
834
835    pub fn all(&self) -> Vec<&GenericLink<T>> {
836        self.inner.all_link_refs()
837    }
838
839    pub fn query(
840        &self,
841        index: Option<T>,
842        source: Option<T>,
843        target: Option<T>,
844    ) -> Vec<&GenericLink<T>> {
845        self.inner.query_link_refs(index, source, target)
846    }
847}
848
849// ----- Helpers ----------------------------------------------------------
850
851static TX_COUNTER: AtomicU64 = AtomicU64::new(0);
852
853fn new_transaction_id() -> u128 {
854    // Produce a candidate; journal ownership additionally excludes recovered
855    // decisions because this timestamp/counter pair can repeat after restart.
856    let count = TX_COUNTER.fetch_add(1, Ordering::Relaxed) as u128;
857    let now = now_unix_ms() as u128;
858    (now << 64) | count
859}
860
861fn now_unix_ms() -> i64 {
862    SystemTime::now()
863        .duration_since(UNIX_EPOCH)
864        .map(|d| d.as_millis() as i64)
865        .unwrap_or(0)
866}
867
868#[cfg(test)]
869mod contract_tests;
870#[cfg(test)]
871mod tests;