Skip to main content

link_cli/transactions/
compaction.rs

1//! Bounds the durable journal by the retention policy (issue #195).
2//!
3//! Retention trims the in-memory history after each commit or rollback.
4//! Without compaction the journal on disk kept every entry ever written, so
5//! each process start re-read the complete history and every write grew a
6//! file that no policy could shrink. When the log supports it, the journal
7//! is rewritten to the entries that still matter once it has grown to
8//! about twice that size, so the rewrite is amortized over many appends.
9//!
10//! A compacted journal keeps, in order:
11//!
12//! 1. a `__transactions:sequence:<n>` watermark, so sequence numbers (which
13//!    version-control tags and branches reference) are never reused;
14//! 2. an applied marker for the highest applied sequence;
15//! 3. every retained record, unchanged;
16//! 4. the commit or rollback decision of every retained record's owner and
17//!    the newest decision, which version-control publication recovery reads;
18//! 5. the applied markers of retained records.
19//!
20//! Undo images belong to undecided owners only while a transaction is open
21//! or recovery is pending; compaction never runs then, so decided images are
22//! dropped. A journal with any undecided record is left untouched.
23
24use std::collections::HashSet;
25
26use doublets::data::LinkReference;
27
28use super::types::{
29    LogRetentionPolicy, APPLIED_MARKER_PREFIX, COMMIT_MARKER_PREFIX, ROLLBACK_MARKER_PREFIX,
30    SEQUENCE_MARKER_PREFIX, TRANSITION_NAME_PREFIX,
31};
32use super::{GenericTransactionsDecorator, LinkError, LinksStorage, TransitionLogStore};
33
34/// Entries a journal may grow by beyond twice its live size before it is
35/// compacted, so small retention windows do not rewrite on every commit.
36const COMPACTION_SLACK: usize = 256;
37
38impl<T, S, L> GenericTransactionsDecorator<T, S, L>
39where
40    T: LinkReference,
41    S: LinksStorage<T>,
42    L: TransitionLogStore,
43{
44    /// Appends one journal entry, counting it towards the compaction budget.
45    pub(super) fn append_journal_entry(&mut self, entry: &str) -> Result<(), LinkError> {
46        // Count even a failed append: it may have reached the file.
47        self.journal_entries = self.journal_entries.saturating_add(1);
48        self.log_store.append_log_entry(entry)
49    }
50
51    /// Number of entries the durable journal currently holds.
52    pub fn journal_entry_count(&self) -> usize {
53        self.journal_entries
54    }
55
56    /// Rewrites the durable journal to its retained entries when it has
57    /// outgrown them, see the module documentation.
58    pub(super) fn compact_journal_if_needed(&mut self) -> Result<(), LinkError> {
59        if matches!(self.retention_policy, LogRetentionPolicy::Infinite)
60            || !self.log_store.supports_compaction()
61            || self.has_open_transaction()
62        {
63            return Ok(());
64        }
65        // Each retained record needs at most itself, a decision and an
66        // applied marker; the estimate avoids building entries every commit.
67        let live = self.log.len().saturating_mul(3).saturating_add(3);
68        if self.journal_entries <= live.saturating_mul(2).saturating_add(COMPACTION_SLACK) {
69            return Ok(());
70        }
71        let Some(entries) = self.compacted_journal() else {
72            return Ok(());
73        };
74        // Appends are durable before their replacement is published.
75        self.log_store.flush_log()?;
76        let before = self.journal_entries;
77        self.log_store.compact_log_entries(&entries)?;
78        self.journal_entries = entries.len();
79        if self.trace {
80            crate::diagnostics::stderr!(
81                "[Transactions] Compacted journal from {before} to {} entries.",
82                entries.len()
83            );
84        }
85        Ok(())
86    }
87
88    /// The retained journal, or `None` while any retained record's owner
89    /// is still undecided.
90    fn compacted_journal(&self) -> Option<Vec<String>> {
91        let mut owners = Vec::new();
92        let mut seen = HashSet::new();
93        for record in &self.log {
94            if seen.insert(record.transaction_id) {
95                owners.push(record.transaction_id);
96            }
97        }
98        let mut decisions = Vec::with_capacity(owners.len() + 1);
99        for owner in owners {
100            let prefix = if self.committed.contains(&owner) {
101                COMMIT_MARKER_PREFIX
102            } else if self.rolled_back.contains(&owner) {
103                ROLLBACK_MARKER_PREFIX
104            } else {
105                return None;
106            };
107            decisions.push(format!("{prefix}{owner:032x}"));
108        }
109        if let Some(last) = &self.last_decision {
110            if !decisions.contains(last) {
111                decisions.push(last.clone());
112            }
113        }
114        let mut entries = Vec::with_capacity(self.log.len() * 2 + decisions.len() + 2);
115        if self.sequence_counter > 0 {
116            entries.push(format!("{SEQUENCE_MARKER_PREFIX}{}", self.sequence_counter));
117        }
118        let applied_retained = self
119            .log
120            .iter()
121            .any(|record| record.sequence == self.applied_sequence);
122        if self.applied_sequence > 0 && !applied_retained {
123            entries.push(format!("{APPLIED_MARKER_PREFIX}{}", self.applied_sequence));
124        }
125        for record in &self.log {
126            entries.push(format!("{TRANSITION_NAME_PREFIX}{}", record.serialize()));
127        }
128        entries.extend(decisions);
129        for record in &self.log {
130            if self.applied.contains(&record.sequence) {
131                entries.push(format!("{APPLIED_MARKER_PREFIX}{}", record.sequence));
132            }
133        }
134        Some(entries)
135    }
136}