link-cli 3.5.2

A CLI tool and reusable library for links manipulation backed by a LiNo-notation doublet storage engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
//! Optional transactions layer for the Rust link-cli.
//!
//! Mirrors the C# `TransactionsDecorator` in
//! `csharp/Foundation.Data.Doublets.Cli.Library/TransactionsDecorator.cs`.
//!
//! The decorator records every `create` / `update` / `delete` as a
//! reversible [`GenericTransition`] in a sidecar log. It supports
//! explicit transactions, sync commits, three retention policies, and
//! crash recovery (R1-R7, R10).
//!
//! Optional — when not opted in, the bare
//! [`NamedTypesDecorator`] behaves
//! identically (R8, R9, R17).
//!
//! # Reuse outside the CLI
//!
//! [`GenericTransactionsDecorator`] is generic over three things:
//!
//! * `T` — the doublets address type (`u32`, `u64`, `usize`, ...);
//! * `S` — the wrapped store, any [`LinksStorage<T>`] implementation,
//!   including [`DoubletsStorage`](crate::DoubletsStorage) over a
//!   file-mapped or caller-owned `doublets::unit::Store`;
//! * `L` — the transitions log, any [`TransitionLogStore`].
//!
//! [`TransactionsDecorator`] is the `u32` + `NamedTypesDecorator`
//! specialisation used by `clink` itself.
//!
//! ```no_run
//! use link_cli::transactions::{
//!     CommitMode, FileTransitionLog, GenericTransactionsDecorator, LogRetentionPolicy,
//! };
//! use link_cli::DoubletsStorage;
//!
//! # fn main() -> Result<(), link_cli::LinkError> {
//! let store = DoubletsStorage::<usize, _>::open_exclusive("db.links")?;
//! let log = FileTransitionLog::open("db.transitions.log")?;
//! let mut tx = GenericTransactionsDecorator::new(
//!     store,
//!     log,
//!     LogRetentionPolicy::default(),
//!     CommitMode::default(),
//!     false,
//! )?;
//!
//! tx.begin_transaction()?;
//! let link = tx.create(0, 0)?;
//! tx.commit()?;
//! tx.save()?;
//! # let _ = link;
//! # Ok(())
//! # }
//! ```
//!
//! # Durability
//!
//! Transitions are durably logged before commit is acknowledged. Commit then
//! flushes the wrapped data before persisting its applied markers. Recovery
//! replays committed-but-unapplied transitions and undoes logged uncommitted
//! changes, reporting replay and flush failures.
//!
//! The default [`RowUndoPolicy::Observed`] mutates the store before recording
//! callbacks and leaves a crash window for unlogged changes. Select
//! [`RowUndoPolicy::WriteAheadImage`] to flush a complete logical undo image
//! before the first effect and reconcile complete history after each write.
//! It requires exclusive ownership and an adapter supporting logical replay;
//! it does not repair torn physical storage. The optional
//! [`crate::engine::Engine`] stages private changes until durable publication.

mod log;
// Replay, recovery and retention live in a submodule; see transactions/recovery.rs.
mod commit;
mod compaction;
mod journal_file;
mod journal_validation;
mod migration_state;
mod names;
mod record;
mod recording;
mod recovery;
mod row_undo;
mod types;
mod undo_image;
mod version_replay;

use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use web_time::{SystemTime, UNIX_EPOCH};

use doublets::data::LinkReference;

use crate::error::LinkError;
use crate::link::GenericLink;
use crate::named_types::NamedTypesDecorator;
use crate::storage::{LinksStorage, LinksStorageRef};

pub use journal_file::{
    import_links_journal, is_links_journal, make_legacy_transitions_filename,
    make_transitions_log_filename, open_transitions_journal,
};
pub use log::{FileTransitionLog, ReplaceableTransitionLogStore, TransitionLogStore};
pub use record::{JournalRecord, NameChange};
pub use types::{
    CommitMode, DoubletLink, GenericDoubletLink, GenericTransition, LogRetentionPolicy, Transition,
    TransitionKind,
};
use types::{COMMIT_MARKER_PREFIX, ROLLBACK_MARKER_PREFIX, TRANSITION_NAME_PREFIX};
pub use undo_image::RowUndoPolicy;

/// Pending state of a transaction (used by the explicit transaction
/// handle and by per-write auto-transactions).
#[derive(Clone)]
struct PendingTransaction<T> {
    id: u128,
    transitions: Vec<JournalRecord<T>>,
    auto_commit: bool,
    rollback_only: bool,
    commit_attempted: bool,
    started_ms: i64,
    image: Option<undo_image::UndoImage<T>>,
}

/// One link address and the `(before, after)` states a single logical
/// write left it in, after collapsing repeated callbacks for that address.
type ObservedChange<T> = (T, GenericDoubletLink<T>, GenericDoubletLink<T>);
type TransitionChange<T> = (TransitionKind, GenericDoubletLink<T>, GenericDoubletLink<T>);

/// Folds one `(before, after)` callback into `observed`.
///
/// Mirrors the handler `TransactionsDecorator.RunWrite` installs in the C#
/// implementation: repeated callbacks for the same address are collapsed into
/// a single change that keeps the *first* `before` (the state the rollback has
/// to restore) and the *last* `after` (the state the write ended at), and the
/// first-seen order of addresses is preserved so the transitions replay in the
/// order the storage produced them.
fn record_observed<T: LinkReference>(
    observed: &mut Vec<ObservedChange<T>>,
    before: GenericLink<T>,
    after: GenericLink<T>,
) {
    let zero = T::from_byte(0);
    let key = if before.index != zero {
        before.index
    } else {
        after.index
    };
    if key == zero {
        return;
    }
    let before = GenericDoubletLink::from_link(&before);
    let after = GenericDoubletLink::from_link(&after);
    match observed.iter_mut().find(|(index, _, _)| *index == key) {
        Some(entry) => {
            // A null first before means the address did not exist. A later
            // update must not replace it with the intermediate created row.
            entry.2 = after;
        }
        None => observed.push((key, before, after)),
    }
}

/// Snapshot of an open transaction (returned by [`GenericTransactionsDecorator::begin_transaction`]).
#[derive(Debug, Clone)]
pub struct TransactionHandle {
    pub id: u128,
    pub started_ms: i64,
}

/// The transactions decorator wraps any [`LinksStorage`] and records
/// every write as a reversible [`GenericTransition`] in `log_store`.
pub struct GenericTransactionsDecorator<T, S, L>
where
    T: LinkReference,
    S: LinksStorage<T>,
    L: TransitionLogStore,
{
    inner: S,
    log_store: L,
    log: Vec<JournalRecord<T>>,
    committed: HashSet<u128>,
    rolled_back: HashSet<u128>,
    applied: HashSet<i64>,
    current: Option<PendingTransaction<T>>,
    sequence_counter: i64,
    applied_sequence: i64,
    retention_policy: LogRetentionPolicy,
    commit_mode: CommitMode,
    version_replay: bool,
    recovery_pending: bool,
    reload_pending: bool,
    trace: bool,
    defer_checkpoint: bool,
    row_undo: RowUndoPolicy,
    /// Entries in the durable journal, and its newest commit/rollback marker.
    journal_entries: usize,
    last_decision: Option<String>,
}

/// The `u32` + [`NamedTypesDecorator`] specialisation with the original
/// links-backed sidecar log.
pub type TransactionsDecorator =
    GenericTransactionsDecorator<u32, NamedTypesDecorator, NamedTypesDecorator>;

/// The specialisation `clink` uses: an append-only [`FileTransitionLog`]
/// journal, whose cost per write does not grow with history (issue #195).
pub type FileTransactionsDecorator =
    GenericTransactionsDecorator<u32, NamedTypesDecorator, FileTransitionLog>;

impl<T, S, L> GenericTransactionsDecorator<T, S, L>
where
    T: LinkReference,
    S: LinksStorage<T>,
    L: TransitionLogStore,
{
    /// Creates a new transactions decorator wrapping `inner`, using
    /// `log_store` as the sidecar log. Runs crash recovery before
    /// returning.
    pub fn new(
        inner: S,
        log_store: L,
        retention_policy: LogRetentionPolicy,
        commit_mode: CommitMode,
        trace: bool,
    ) -> Result<Self, LinkError> {
        let mut decorator = Self {
            inner,
            log_store,
            log: Vec::new(),
            committed: HashSet::new(),
            rolled_back: HashSet::new(),
            applied: HashSet::new(),
            current: None,
            sequence_counter: 0,
            applied_sequence: 0,
            retention_policy,
            commit_mode,
            version_replay: false,
            recovery_pending: false,
            reload_pending: false,
            trace,
            defer_checkpoint: false,
            row_undo: RowUndoPolicy::Observed,
            journal_entries: 0,
            last_decision: None,
        };
        decorator.recover()?;
        Ok(decorator)
    }

    /// Conventional filename of the links-backed transitions log
    /// (`<stem>.transitions.links`). `clink` now keeps its journal in
    /// [`make_transitions_log_filename`] and imports this store once.
    pub fn make_transitions_database_filename<P: AsRef<Path>>(database_filename: P) -> PathBuf {
        let path = database_filename.as_ref();
        let stem = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or_default();
        let name = format!("{stem}.transitions.links");
        match path.parent() {
            Some(parent) if !parent.as_os_str().is_empty() => parent.join(name),
            _ => PathBuf::from(name),
        }
    }

    pub fn retention_policy(&self) -> &LogRetentionPolicy {
        &self.retention_policy
    }

    pub fn set_retention_policy(&mut self, policy: LogRetentionPolicy) {
        self.retention_policy = policy;
    }

    pub fn commit_mode(&self) -> CommitMode {
        self.commit_mode
    }

    pub fn set_commit_mode(&mut self, mode: CommitMode) {
        self.commit_mode = mode;
    }

    pub fn applied_sequence(&self) -> i64 {
        self.applied_sequence
    }

    pub fn last_logged_sequence(&self) -> i64 {
        self.sequence_counter
    }

    /// Higher layers must distinguish a durable decision from a failed
    /// checkpoint before deciding whether cleanup may undo the transaction.
    pub(crate) fn is_transaction_committed(&self, id: u128) -> bool {
        self.committed.contains(&id)
    }

    pub(crate) fn is_transaction_rolled_back(&self, id: u128) -> bool {
        self.rolled_back.contains(&id)
    }

    pub(crate) fn has_open_transaction(&self) -> bool {
        self.current.is_some() || self.version_replay || self.recovery_pending
    }

    pub(crate) fn must_finish_commit(&self, id: u128) -> bool {
        self.is_transaction_committed(id)
            || self
                .current
                .as_ref()
                .is_some_and(|pending| pending.id == id && pending.commit_attempted)
    }

    /// Returns a snapshot of the transitions log in sequence order.
    pub fn log(&self) -> Vec<GenericTransition<T>> {
        self.log.iter().map(|record| record.transition).collect()
    }

    /// Complete retained records, including optional name payloads.
    pub fn journal(&self) -> Vec<JournalRecord<T>> {
        self.log.clone()
    }

    pub fn inner(&self) -> &S {
        &self.inner
    }

    pub fn inner_mut(&mut self) -> &mut S {
        &mut self.inner
    }

    pub fn log_store(&self) -> &L {
        &self.log_store
    }

    pub fn log_store_mut(&mut self) -> &mut L {
        &mut self.log_store
    }

    pub fn into_inner(self) -> (S, L) {
        (self.inner, self.log_store)
    }

    /// Makes both the data store and the transitions log durable.
    pub fn flush(&mut self) -> Result<(), LinkError> {
        if self.recovery_pending {
            return self.recover();
        }
        self.ensure_no_version_replay()?;
        if self
            .current
            .as_ref()
            .is_some_and(|pending| pending.commit_attempted)
        {
            return self.commit_current();
        }
        if self.defer_checkpoint && self.current.is_some() {
            return Ok(());
        }
        self.inner.flush()?;
        self.log_store.flush_log()?;
        Ok(())
    }

    /// Alias of [`flush`](Self::flush), kept for parity with the other
    /// decorators and with the C# API.
    pub fn save(&mut self) -> Result<(), LinkError> {
        self.flush()
    }

    /// Cheap check for "has another process written to the wrapped
    /// store since we last read or wrote it?".
    pub fn has_external_changes(&self) -> Result<bool, LinkError> {
        self.inner.has_external_changes()
    }

    /// Re-reads the wrapped store and rebuilds the transactions state
    /// from the log — the recovery path after another process wrote.
    pub fn reload(&mut self) -> Result<(), LinkError> {
        if self.current.is_some() || self.version_replay {
            return Err(LinkError::Transaction(
                "Cannot reload while a transaction is open.".to_string(),
            ));
        }
        self.recovery_pending = true;
        self.reload_pending = true;
        self.recover()
    }

    // ----- Write API ------------------------------------------------------

    pub fn create(&mut self, source: T, target: T) -> Result<T, LinkError> {
        let names_before = self.inner.capture_names()?;
        let owns = self.ensure_open_transaction()?;
        let mut observed = Vec::new();
        let outcome = self
            .inner
            .create_link_observed(source, target, &mut |before, after| {
                record_observed(&mut observed, before, after)
            });
        self.record_observed_transitions(&observed, owns, names_before.as_ref())?;
        let id = match outcome {
            Ok(id) => id,
            Err(error) => {
                self.fence_failed_image();
                if owns {
                    if observed.is_empty()
                        && self
                            .current
                            .as_ref()
                            .is_none_or(|owner| owner.image.is_none())
                    {
                        self.current = None;
                    } else {
                        self.rollback()?;
                    }
                }
                return Err(error);
            }
        };
        self.complete_image_observations(owns)?;
        if owns {
            self.commit_current()?;
        }
        Ok(id)
    }

    pub fn update(&mut self, id: T, source: T, target: T) -> Result<GenericLink<T>, LinkError> {
        self.update_observed(id, source, target, &mut |_, _| {})
    }

    /// [`Self::update`], reporting every change the underlying store made.
    ///
    /// An update that would duplicate an existing doublet is resolved into a
    /// merge that deletes the updated link, so one call can report several
    /// changes, exactly like C#'s `links.Update(restriction, substitution, handler)`.
    pub fn update_observed(
        &mut self,
        id: T,
        source: T,
        target: T,
        observer: &mut dyn FnMut(GenericLink<T>, GenericLink<T>),
    ) -> Result<GenericLink<T>, LinkError> {
        let before = self.snapshot(id);
        let names_before = self.inner.capture_names()?;
        let owns = self.ensure_open_transaction()?;
        let mut observed: Vec<ObservedChange<T>> = Vec::new();
        let outcome = self
            .inner
            .update_link_observed(id, source, target, &mut |before, after| {
                observer(before, after);
                record_observed(&mut observed, before, after)
            });
        let prev = match outcome {
            Ok(prev) => prev,
            Err(err) => {
                self.fence_failed_image();
                // Callbacks describe changes already made, even if a later
                // part of the storage operation fails.
                self.record_observed_transitions(&observed, owns, names_before.as_ref())?;
                if owns {
                    if observed.is_empty()
                        && self
                            .current
                            .as_ref()
                            .is_none_or(|owner| owner.image.is_none())
                    {
                        self.current = None;
                    } else {
                        self.rollback()?;
                    }
                }
                return Err(err);
            }
        };
        if observed.is_empty() {
            let after = self
                .inner
                .get_link(id)
                .map(|link| GenericDoubletLink::from_link(&link))
                .unwrap_or_else(|| GenericDoubletLink::new(id, source, target));
            self.record_transition(
                TransitionKind::Update,
                before,
                after,
                owns,
                names_before.as_ref(),
            )?;
        } else {
            self.record_observed_transitions(&observed, owns, names_before.as_ref())?;
        }
        self.complete_image_observations(owns)?;
        if owns {
            self.commit_current()?;
        }
        Ok(prev)
    }

    pub fn delete(&mut self, id: T) -> Result<GenericLink<T>, LinkError> {
        self.delete_observed(id, &mut |_, _| {})
    }

    /// [`Self::delete`], reporting every change the underlying store made.
    ///
    /// Deleting a link cascades into every link that still used it, and those
    /// deletions are changes of their own: the C# CLI hands
    /// `AdvancedMixedQueryProcessor.RemoveLinks` a handler that `links.Delete`
    /// calls once per removed link, so `--changes` lists the usages too. The
    /// observer is the same seam, threaded through the decorator stack.
    pub fn delete_observed(
        &mut self,
        id: T,
        observer: &mut dyn FnMut(GenericLink<T>, GenericLink<T>),
    ) -> Result<GenericLink<T>, LinkError> {
        let before = self.snapshot(id);
        let names_before = self.inner.capture_names()?;
        let owns = self.ensure_open_transaction()?;
        let mut observed: Vec<ObservedChange<T>> = Vec::new();
        let outcome = self.inner.delete_link_observed(id, &mut |before, after| {
            observer(before, after);
            record_observed(&mut observed, before, after)
        });
        let deleted = match outcome {
            Ok(d) => d,
            Err(err) => {
                self.fence_failed_image();
                // Callbacks describe changes already made, even if a later
                // part of the storage operation fails.
                self.record_observed_transitions(&observed, owns, names_before.as_ref())?;
                if owns {
                    if observed.is_empty()
                        && self
                            .current
                            .as_ref()
                            .is_none_or(|owner| owner.image.is_none())
                    {
                        self.current = None;
                    } else {
                        self.rollback()?;
                    }
                }
                return Err(err);
            }
        };
        if observed.is_empty() {
            self.record_transition(
                TransitionKind::Delete,
                before,
                GenericDoubletLink::empty(),
                owns,
                names_before.as_ref(),
            )?;
        } else {
            self.record_observed_transitions(&observed, owns, names_before.as_ref())?;
        }
        self.complete_image_observations(owns)?;
        if owns {
            self.commit_current()?;
        }
        Ok(deleted)
    }

    /// Composite create-and-update used by callers that want a link
    /// initialised with source/target in a single pair of transitions
    /// (matches the C# `CreateAndUpdate` extension semantics, which
    /// always emits a Create followed by an Update transition).
    pub fn create_and_update(&mut self, source: T, target: T) -> Result<T, LinkError> {
        let owns = self.ensure_open_transaction()?;
        let zero = T::from_byte(0);
        let outcome = self.create(zero, zero).and_then(|id| {
            self.update(id, source, target)?;
            Ok(id)
        });
        let id = match outcome {
            Ok(id) => id,
            Err(error) => {
                self.fence_failed_image();
                if owns {
                    self.rollback()?;
                }
                return Err(error);
            }
        };
        if owns {
            self.commit_current()?;
        }
        Ok(id)
    }

    pub fn exists(&self, id: T) -> bool {
        self.inner.link_exists(id)
    }

    pub fn search(&self, source: T, target: T) -> Option<T> {
        self.inner.search_link(source, target)
    }

    pub fn get_or_create(&mut self, source: T, target: T) -> Result<T, LinkError> {
        if let Some(existing) = self.inner.search_link(source, target) {
            return Ok(existing);
        }
        self.create(source, target)
    }

    pub fn ensure_created(&mut self, id: T) -> Result<T, LinkError> {
        if id == T::from_byte(0) || self.inner.link_exists(id) {
            return Ok(id);
        }
        let names_before = self.inner.capture_names()?;
        let owns = self.ensure_open_transaction()?;
        let mut observed = Vec::new();
        let outcome = self
            .inner
            .ensure_link_created_observed(id, &mut |before, after| {
                record_observed(&mut observed, before, after)
            });
        self.record_observed_transitions(&observed, owns, names_before.as_ref())?;
        match outcome {
            Ok(created) => {
                self.complete_image_observations(owns)?;
                if owns {
                    self.commit_current()?;
                }
                Ok(created)
            }
            Err(error) => {
                self.fence_failed_image();
                if owns {
                    self.rollback()?;
                }
                Err(error)
            }
        }
    }

    /// Current state of `id` as a doublet, or an empty one at `id`.
    fn snapshot(&self, id: T) -> GenericDoubletLink<T> {
        let zero = T::from_byte(0);
        self.inner
            .get_link(id)
            .map(|link| GenericDoubletLink::from_link(&link))
            .unwrap_or_else(|| GenericDoubletLink::new(id, zero, zero))
    }

    pub(crate) fn ensure_write_allowed(&self) -> Result<(), LinkError> {
        self.ensure_no_version_replay()?;
        self.ensure_recovery_complete()?;
        if self
            .current
            .as_ref()
            .is_some_and(|pending| pending.commit_attempted)
        {
            return Err(LinkError::Transaction(
                "Retry transaction commit before further writes; its outcome may be unknown."
                    .into(),
            ));
        }
        if self.current.as_ref().is_some_and(|tx| tx.rollback_only) {
            return Err(LinkError::Transaction(
                "Transaction requires rollback before further writes.".into(),
            ));
        }
        Ok(())
    }

    fn ensure_open_transaction(&mut self) -> Result<bool, LinkError> {
        self.ensure_write_allowed()?;
        if self.sequence_counter == i64::MAX {
            return Err(LinkError::Transaction(
                "Transaction sequence space is exhausted.".into(),
            ));
        }
        let owns = self.current.is_none();
        if owns {
            self.current = Some(PendingTransaction {
                id: self.allocate_transaction_id(),
                transitions: Vec::new(),
                auto_commit: true,
                rollback_only: false,
                commit_attempted: false,
                started_ms: now_unix_ms(),
                image: None,
            });
        }
        if let Err(error) = self.prepare_row_undo() {
            self.current
                .as_mut()
                .expect("open transaction")
                .rollback_only = true;
            if owns {
                self.rollback()?;
            }
            return Err(error);
        }
        Ok(owns)
    }

    fn write_marker(&mut self, name: &str) -> Result<(), LinkError> {
        if name.starts_with(COMMIT_MARKER_PREFIX) || name.starts_with(ROLLBACK_MARKER_PREFIX) {
            self.last_decision = Some(name.to_string());
        }
        self.append_journal_entry(name)
    }

    // ----- Transaction handle --------------------------------------------

    fn allocate_transaction_id(&self) -> u128 {
        // Realtime can repeat after restart while the process counter resets.
        // Durable decisions outlive retained payloads, so consult the existing
        // recovered indexes before assigning an ID to either kind of owner.
        let mut collided = false;
        loop {
            let id = new_transaction_id();
            if id != 0 && !self.committed.contains(&id) && !self.rolled_back.contains(&id) {
                if collided && self.trace {
                    crate::diagnostics::stderr!(
                        "[Transactions] Skipped previously decided transaction IDs."
                    );
                }
                return id;
            }
            collided = true;
        }
    }

    pub fn begin_transaction(&mut self) -> Result<TransactionHandle, LinkError> {
        self.ensure_no_version_replay()?;
        self.ensure_recovery_complete()?;
        if self.current.is_some() {
            return Err(LinkError::Transaction(
                "Nested transactions are not supported.".to_string(),
            ));
        }
        let id = self.allocate_transaction_id();
        let started_ms = now_unix_ms();
        self.current = Some(PendingTransaction {
            id,
            transitions: Vec::new(),
            auto_commit: false,
            rollback_only: false,
            commit_attempted: false,
            started_ms,
            image: None,
        });
        Ok(TransactionHandle { id, started_ms })
    }

    /// Finish the transaction. An append/flush error can have an unknown
    /// outcome: retry commit, rollback or save to finish the attempted decision.
    /// Further writes remain fenced until that work succeeds.
    pub fn commit(&mut self) -> Result<(), LinkError> {
        if self.recovery_pending {
            return self.recover();
        }
        if self.current.is_none() {
            return Ok(());
        }
        self.commit_current()
    }

    /// Undo an open transaction, or finish its attempted commit if a previous
    /// commit failed with a possibly durable decision.
    pub fn rollback(&mut self) -> Result<(), LinkError> {
        if self.recovery_pending {
            return self.recover();
        }
        if self
            .current
            .as_ref()
            .is_some_and(|pending| pending.commit_attempted)
        {
            // A commit append/flush may have persisted before returning an error.
            return self.commit_current();
        }
        // Once undo begins, an error can leave the data partially restored.
        // Keep the abort decision until every rollback step succeeds.
        if let Some(current) = self.current.as_mut() {
            current.rollback_only = true;
        }
        let pending = match self.current.clone() {
            Some(p) => p,
            None => return Ok(()),
        };
        if self.defer_checkpoint && pending.transitions.is_empty() && pending.image.is_none() {
            self.current = None;
            return Ok(());
        }
        let result = if let Some(image) = &pending.image {
            self.restore_image(image)
        } else {
            pending
                .transitions
                .iter()
                .rev()
                .try_for_each(|transition| self.try_revert_record(transition))
        };
        result?;
        self.inner.flush()?;
        self.write_marker(&format!("{ROLLBACK_MARKER_PREFIX}{:032x}", pending.id))?;
        self.log_store.flush_log()?;
        self.rolled_back.insert(pending.id);
        self.current = None;
        if self.trace {
            crate::diagnostics::stderr!(
                "[Transactions] Rolled back tx {:032x} ({} transitions).",
                pending.id,
                pending.transitions.len(),
            );
        }
        self.enforce_retention()?;
        Ok(())
    }
}

impl FileTransactionsDecorator {
    /// Defer file writes requested within a CLI batch to its final checkpoint.
    /// The named store keeps edits in memory and the commit still syncs the
    /// journal before saving data and again after writing the applied markers.
    pub fn defer_batch_checkpoint(&mut self) {
        self.defer_checkpoint = true;
        self.log_store.set_sync_on_append(false);
    }
}

/// Read paths that lend out references, available whenever the wrapped
/// store keeps its links resident in memory.
impl<T, S, L> GenericTransactionsDecorator<T, S, L>
where
    T: LinkReference,
    S: LinksStorageRef<T>,
    L: TransitionLogStore,
{
    pub fn get(&self, id: T) -> Option<&GenericLink<T>> {
        self.inner.get_link_ref(id)
    }

    pub fn all(&self) -> Vec<&GenericLink<T>> {
        self.inner.all_link_refs()
    }

    pub fn query(
        &self,
        index: Option<T>,
        source: Option<T>,
        target: Option<T>,
    ) -> Vec<&GenericLink<T>> {
        self.inner.query_link_refs(index, source, target)
    }
}

// ----- Helpers ----------------------------------------------------------

static TX_COUNTER: AtomicU64 = AtomicU64::new(0);

fn new_transaction_id() -> u128 {
    // Produce a candidate; journal ownership additionally excludes recovered
    // decisions because this timestamp/counter pair can repeat after restart.
    let count = TX_COUNTER.fetch_add(1, Ordering::Relaxed) as u128;
    let now = now_unix_ms() as u128;
    (now << 64) | count
}

fn now_unix_ms() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as i64)
        .unwrap_or(0)
}

#[cfg(test)]
mod contract_tests;
#[cfg(test)]
mod tests;