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