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(mut 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        entries.extend(self.compact_migration_state()?);
77        let before = self.journal_entries;
78        self.log_store.compact_log_entries(&entries)?;
79        self.journal_entries = entries.len();
80        if self.trace {
81            crate::diagnostics::stderr!(
82                "[Transactions] Compacted journal from {before} to {} entries.",
83                entries.len()
84            );
85        }
86        Ok(())
87    }
88
89    /// The retained journal, or `None` while any retained record's owner
90    /// is still undecided.
91    fn compacted_journal(&self) -> Option<Vec<String>> {
92        let mut owners = Vec::new();
93        let mut seen = HashSet::new();
94        for record in &self.log {
95            if seen.insert(record.transaction_id) {
96                owners.push(record.transaction_id);
97            }
98        }
99        let mut decisions = Vec::with_capacity(owners.len() + 1);
100        for owner in owners {
101            let prefix = if self.committed.contains(&owner) {
102                COMMIT_MARKER_PREFIX
103            } else if self.rolled_back.contains(&owner) {
104                ROLLBACK_MARKER_PREFIX
105            } else {
106                return None;
107            };
108            decisions.push(format!("{prefix}{owner:032x}"));
109        }
110        if let Some(last) = &self.last_decision {
111            if !decisions.contains(last) {
112                decisions.push(last.clone());
113            }
114        }
115        let mut entries = Vec::with_capacity(self.log.len() * 2 + decisions.len() + 2);
116        if self.sequence_counter > 0 {
117            entries.push(format!("{SEQUENCE_MARKER_PREFIX}{}", self.sequence_counter));
118        }
119        let applied_retained = self
120            .log
121            .iter()
122            .any(|record| record.sequence == self.applied_sequence);
123        if self.applied_sequence > 0 && !applied_retained {
124            entries.push(format!("{APPLIED_MARKER_PREFIX}{}", self.applied_sequence));
125        }
126        for record in &self.log {
127            entries.push(format!("{TRANSITION_NAME_PREFIX}{}", record.serialize()));
128        }
129        entries.extend(decisions);
130        for record in &self.log {
131            if self.applied.contains(&record.sequence) {
132                entries.push(format!("{APPLIED_MARKER_PREFIX}{}", record.sequence));
133            }
134        }
135        Some(entries)
136    }
137}