Skip to main content

link_cli/transactions/
recovery.rs

1//! Transition replay, crash recovery and log retention for
2//! [`GenericTransactionsDecorator`].
3//!
4//! Extracted from `transactions/mod.rs` for issue #100: the file had grown
5//! past the 1000-line limit enforced by `rust/scripts/check-file-size.rs`.
6//! These are the paths that read the sidecar log back — applying and
7//! reverting individual transitions, replaying an interrupted run, and
8//! trimming or archiving the log once it grows — as opposed to the write
9//! paths that record new transitions in the parent module.
10
11use std::path::Path;
12
13use doublets::data::LinkReference;
14
15use crate::error::LinkError;
16use crate::storage::LinksStorage;
17
18use super::journal_validation::RecoveryJournal;
19use super::log::TransitionLogStore;
20use super::types::{
21    GenericTransition, LogRetentionPolicy, TransitionKind, APPLIED_MARKER_PREFIX,
22    ROLLBACK_MARKER_PREFIX,
23};
24use super::{new_transaction_id, now_unix_ms, GenericTransactionsDecorator, JournalRecord};
25
26impl<T, S, L> GenericTransactionsDecorator<T, S, L>
27where
28    T: LinkReference,
29    S: LinksStorage<T>,
30    L: TransitionLogStore,
31{
32    /// Public helper for higher-level decorators (e.g. version control)
33    /// — applies a single transition without writing a new log entry.
34    /// Rejects replay while a transaction or its cleanup still owns the data.
35    pub fn apply_transition(&mut self, transition: &GenericTransition<T>) -> Result<(), LinkError> {
36        self.ensure_replay_allowed()?;
37        self.try_apply_transition(transition)
38    }
39
40    /// Reverts one transition, reporting storage errors to the caller.
41    /// Rejects replay while a transaction or its cleanup still owns the data.
42    pub fn revert_transition(
43        &mut self,
44        transition: &GenericTransition<T>,
45    ) -> Result<(), LinkError> {
46        self.ensure_replay_allowed()?;
47        self.try_revert_transition(transition)
48    }
49
50    /// Replays a complete record, including names, without logging another write.
51    pub fn apply_record(&mut self, record: &JournalRecord<T>) -> Result<(), LinkError> {
52        self.ensure_replay_allowed()?;
53        self.validate_record_backend(record)?;
54        self.try_apply_record(record, false)
55    }
56
57    /// Undoes a complete record, including names, without logging another write.
58    pub fn revert_record(&mut self, record: &JournalRecord<T>) -> Result<(), LinkError> {
59        self.ensure_replay_allowed()?;
60        self.validate_record_backend(record)?;
61        self.try_revert_record(record)
62    }
63
64    fn validate_record_backend(&mut self, record: &JournalRecord<T>) -> Result<(), LinkError> {
65        record.validate()?;
66        if !record.names.is_empty() && self.inner.capture_names()?.is_none() {
67            return Err(LinkError::StorageError(
68                "journal requires a named storage adapter".into(),
69            ));
70        }
71        Ok(())
72    }
73
74    pub(super) fn try_apply_record(
75        &mut self,
76        record: &JournalRecord<T>,
77        record_applied: bool,
78    ) -> Result<(), LinkError> {
79        if !record.name_only {
80            self.try_apply_transition(&record.transition)?;
81        }
82        self.replay_names(record, false)?;
83        if record_applied {
84            self.inner.flush()?;
85            self.mark_applied(record)?;
86            self.log_store.flush_log()?;
87        }
88        Ok(())
89    }
90
91    pub(super) fn try_revert_record(&mut self, record: &JournalRecord<T>) -> Result<(), LinkError> {
92        if !record.name_only {
93            self.try_revert_transition(&record.transition)?;
94        }
95        self.replay_names(record, true)
96    }
97
98    fn ensure_replay_allowed(&self) -> Result<(), LinkError> {
99        if self.has_open_transaction() {
100            return Err(LinkError::Transaction(
101                "Complete the current transaction or its cleanup before unlogged replay.".into(),
102            ));
103        }
104        Ok(())
105    }
106
107    pub(super) fn try_apply_transition(
108        &mut self,
109        transition: &GenericTransition<T>,
110    ) -> Result<(), LinkError> {
111        let zero = T::from_byte(0);
112        let result: Result<(), LinkError> = match transition.kind {
113            TransitionKind::Create => {
114                if transition.after.index != zero {
115                    self.inner
116                        .ensure_link_created(transition.after.index)
117                        .and_then(|_| {
118                            self.inner
119                                .restore_link(
120                                    transition.after.index,
121                                    transition.after.source,
122                                    transition.after.target,
123                                )
124                                .map(|_| ())
125                        })
126                } else {
127                    Ok(())
128                }
129            }
130            TransitionKind::Update => {
131                if transition.after.index != zero && self.inner.link_exists(transition.after.index)
132                {
133                    self.inner
134                        .restore_link(
135                            transition.after.index,
136                            transition.after.source,
137                            transition.after.target,
138                        )
139                        .map(|_| ())
140                } else {
141                    Ok(())
142                }
143            }
144            TransitionKind::Delete => {
145                if transition.before.index != zero
146                    && self.inner.link_exists(transition.before.index)
147                {
148                    self.inner.delete_link(transition.before.index).map(|_| ())
149                } else {
150                    Ok(())
151                }
152            }
153        };
154        result?;
155        Ok(())
156    }
157
158    pub(super) fn try_revert_transition(
159        &mut self,
160        transition: &GenericTransition<T>,
161    ) -> Result<(), LinkError> {
162        let zero = T::from_byte(0);
163        let result: Result<(), LinkError> = match transition.kind {
164            TransitionKind::Create => {
165                if transition.after.index != zero && self.inner.link_exists(transition.after.index)
166                {
167                    self.inner.delete_link(transition.after.index).map(|_| ())
168                } else {
169                    Ok(())
170                }
171            }
172            TransitionKind::Update => {
173                if transition.before.index != zero
174                    && self.inner.link_exists(transition.before.index)
175                {
176                    self.inner
177                        .restore_link(
178                            transition.before.index,
179                            transition.before.source,
180                            transition.before.target,
181                        )
182                        .map(|_| ())
183                } else {
184                    Ok(())
185                }
186            }
187            TransitionKind::Delete => {
188                if transition.before.index != zero {
189                    // Restoring a higher mapped address can allocate this
190                    // address as an empty intermediate slot. Existence alone
191                    // does not mean its original contents were restored.
192                    self.inner
193                        .ensure_link_created(transition.before.index)
194                        .and_then(|_| {
195                            self.inner
196                                .restore_link(
197                                    transition.before.index,
198                                    transition.before.source,
199                                    transition.before.target,
200                                )
201                                .map(|_| ())
202                        })
203                } else {
204                    Ok(())
205                }
206            }
207        };
208        result
209    }
210
211    pub(super) fn mark_applied(
212        &mut self,
213        transition: &GenericTransition<T>,
214    ) -> Result<(), LinkError> {
215        if !self.applied.contains(&transition.sequence) {
216            self.write_marker(&format!("{APPLIED_MARKER_PREFIX}{}", transition.sequence))?;
217            self.applied.insert(transition.sequence);
218            if transition.sequence > self.applied_sequence {
219                self.applied_sequence = transition.sequence;
220            }
221        }
222        Ok(())
223    }
224
225    // ----- Recovery -------------------------------------------------------
226
227    pub(super) fn ensure_recovery_complete(&self) -> Result<(), LinkError> {
228        if self.recovery_pending {
229            return Err(LinkError::Transaction(
230                "Retry recovery before further transaction writes or replay.".into(),
231            ));
232        }
233        Ok(())
234    }
235
236    /// Validates the sidecar journal before rebuilding history and replaying it.
237    /// Unrelated names are ignored; malformed or contradictory transaction
238    /// records fail before rows or live indexes change. Identical retries are
239    /// collapsed. A failure retains write admission until recovery succeeds.
240    pub fn recover(&mut self) -> Result<(), LinkError> {
241        if self.current.is_some() || self.version_replay {
242            return Err(LinkError::Transaction(
243                "Cannot recover while a transaction is open.".into(),
244            ));
245        }
246        self.recovery_pending = true;
247        match self.recover_journal() {
248            Ok(()) => {
249                self.recovery_pending = false;
250                Ok(())
251            }
252            Err(error) => {
253                if self.trace {
254                    crate::diagnostics::stderr!(
255                        "[Transactions] Recovery failed; admission retained: {error}."
256                    );
257                }
258                Err(error)
259            }
260        }
261    }
262
263    fn recover_journal(&mut self) -> Result<(), LinkError> {
264        let journal = RecoveryJournal::<T>::parse(self.log_store.read_log_entries()?)?;
265        // Parsing already validates every payload. Probe optional adapter
266        // capability once, avoiding a full sidecar scan per retained record.
267        if let Some(record) = journal.log.iter().find(|record| !record.names.is_empty()) {
268            self.validate_record_backend(record)?;
269        }
270        if journal.images.iter().any(|image| image.names.is_some())
271            && self.inner.capture_names()?.is_none()
272        {
273            return Err(LinkError::StorageError(
274                "undo image requires a named storage adapter".into(),
275            ));
276        }
277        if self.reload_pending {
278            self.inner.reload()?;
279            self.reload_pending = false;
280        }
281        self.log = journal.log;
282        self.committed = journal.committed;
283        self.rolled_back = journal.rolled_back;
284        self.applied = journal.applied;
285        self.sequence_counter = journal.sequence;
286        self.applied_sequence = journal.applied_sequence;
287
288        // An older failed checkpoint can precede a later applied commit. Redo
289        // the whole committed suffix in order, including already-applied rows.
290        let log_snapshot: Vec<JournalRecord<T>> = self.log.clone();
291        let mut replay_from = log_snapshot
292            .iter()
293            .position(|transition| {
294                self.committed.contains(&transition.transaction_id)
295                    && !self.applied.contains(&transition.sequence)
296            })
297            .unwrap_or(log_snapshot.len());
298        let pending_images = journal
299            .images
300            .into_iter()
301            .filter(|image| {
302                !self.committed.contains(&image.owner) && !self.rolled_back.contains(&image.owner)
303            })
304            .collect::<Vec<_>>();
305        if let Some(base) = pending_images.iter().map(|image| image.base).min() {
306            replay_from =
307                replay_from.min(log_snapshot.partition_point(|record| record.sequence <= base));
308        }
309        let result = (|| -> Result<Vec<u128>, LinkError> {
310            let mut pending_tx_ids = Vec::new();
311            let mut pending_seen = std::collections::HashSet::new();
312            let imaged = pending_images
313                .iter()
314                .map(|image| image.owner)
315                .collect::<std::collections::HashSet<_>>();
316            if !pending_images.is_empty() {
317                // Undo newest effects first, interleaving legacy records and
318                // complete images by their base sequence. The parser rejects
319                // ambiguous equal-base owners, independent of physical order.
320                let mut images = pending_images.iter().collect::<Vec<_>>();
321                images.sort_by_key(|image| image.base);
322                let mut records = log_snapshot
323                    .iter()
324                    .rev()
325                    .filter(|record| {
326                        !self.committed.contains(&record.transaction_id)
327                            && !self.rolled_back.contains(&record.transaction_id)
328                            && !imaged.contains(&record.transaction_id)
329                    })
330                    .collect::<Vec<_>>()
331                    .into_iter()
332                    .peekable();
333                for image in images.into_iter().rev() {
334                    while records
335                        .peek()
336                        .is_some_and(|record| record.sequence > image.base)
337                    {
338                        let record = records.next().expect("peeked record");
339                        self.try_revert_record(record)?;
340                        if pending_seen.insert(record.transaction_id) {
341                            pending_tx_ids.push(record.transaction_id);
342                        }
343                    }
344                    self.restore_image(image)?;
345                    if pending_seen.insert(image.owner) {
346                        pending_tx_ids.push(image.owner);
347                    }
348                }
349                for record in records {
350                    self.try_revert_record(record)?;
351                    if pending_seen.insert(record.transaction_id) {
352                        pending_tx_ids.push(record.transaction_id);
353                    }
354                }
355            }
356            for transition in &log_snapshot[replay_from..] {
357                if !self.committed.contains(&transition.transaction_id) {
358                    continue;
359                }
360                self.try_apply_record(transition, false)?;
361            }
362            // Auto-rollback transitions written but never committed and never rolled back (R10).
363            for transition in log_snapshot
364                .iter()
365                .rev()
366                .filter(|_| pending_images.is_empty())
367            {
368                if self.committed.contains(&transition.transaction_id) {
369                    continue;
370                }
371                if self.rolled_back.contains(&transition.transaction_id) {
372                    continue;
373                }
374                self.try_revert_record(transition)?;
375                if pending_seen.insert(transition.transaction_id) {
376                    pending_tx_ids.push(transition.transaction_id);
377                }
378            }
379            Ok(pending_tx_ids)
380        })();
381        let pending_tx_ids = result?;
382        self.inner.flush()?;
383        // The gap must remain a restart anchor until the complete final state
384        // (including undo) is durable, even if a later marker append fails.
385        for transition in &log_snapshot[replay_from..] {
386            if self.committed.contains(&transition.transaction_id) {
387                self.mark_applied(transition)?;
388            }
389        }
390        for tx_id in pending_tx_ids {
391            self.rolled_back.insert(tx_id);
392            self.write_marker(&format!("{ROLLBACK_MARKER_PREFIX}{tx_id:032x}"))?;
393        }
394        self.log_store.flush_log()?;
395        Ok(())
396    }
397
398    pub(super) fn enforce_retention(&mut self) -> Result<(), LinkError> {
399        match self.retention_policy.clone() {
400            LogRetentionPolicy::Infinite => Ok(()),
401            LogRetentionPolicy::Sized { max_transitions } => self.enforce_sized(max_transitions),
402            LogRetentionPolicy::Chunked {
403                chunk_size,
404                archive_directory,
405            } => self.enforce_chunked(chunk_size, &archive_directory),
406        }
407    }
408
409    fn enforce_sized(&mut self, max_transitions: u64) -> Result<(), LinkError> {
410        if max_transitions == 0 {
411            return Ok(());
412        }
413        while self.log.len() as u64 > max_transitions {
414            let head = self.log[0].clone();
415            if !self.rolled_back.contains(&head.transaction_id)
416                && !self.applied.contains(&head.sequence)
417            {
418                if !self.committed.contains(&head.transaction_id) {
419                    break; // A pending transaction is not reclaimable.
420                }
421                self.try_apply_record(&head, true)?;
422                if !self.applied.contains(&head.sequence) {
423                    break; // R7: never drop an un-applied transition.
424                }
425            }
426            self.log.remove(0);
427            if self.trace {
428                crate::diagnostics::stderr!(
429                    "[Transactions] Dropped completed transition seq={} per sized retention.",
430                    head.sequence
431                );
432            }
433        }
434        Ok(())
435    }
436
437    fn enforce_chunked(
438        &mut self,
439        chunk_size: u64,
440        archive_directory: &Path,
441    ) -> Result<(), LinkError> {
442        if chunk_size == 0 {
443            return Ok(());
444        }
445        if (self.log.len() as u64) < chunk_size {
446            return Ok(());
447        }
448        let chunk: Vec<JournalRecord<T>> =
449            self.log.iter().take(chunk_size as usize).cloned().collect();
450        // Rollback has already durably undone these writes. Reapplying them
451        // would resurrect aborted data; archives contain committed changes only.
452        let archived: Vec<_> = chunk
453            .iter()
454            .filter(|transition| !self.rolled_back.contains(&transition.transaction_id))
455            .cloned()
456            .collect();
457        for transition in &archived {
458            if !self.applied.contains(&transition.sequence) {
459                if !self.committed.contains(&transition.transaction_id) {
460                    return Ok(()); // Never apply or discard a pending chunk.
461                }
462                self.try_apply_record(transition, true)?;
463                if !self.applied.contains(&transition.sequence) {
464                    return Ok(()); // never drop un-applied
465                }
466            }
467        }
468        if archived.is_empty() {
469            self.log.drain(0..chunk.len());
470            return Ok(());
471        }
472        std::fs::create_dir_all(archive_directory).map_err(|error| {
473            LinkError::StorageError(format!(
474                "failed to create archive dir {}: {error}",
475                archive_directory.display()
476            ))
477        })?;
478        let timestamp = now_unix_ms();
479        // Independent journals may share this directory and restart their
480        // counters at the same realtime. Claim the path in the open itself;
481        // an existence check followed by create could still replace a writer.
482        let (mut file, path) = loop {
483            let file_name = format!(
484                "transitions-chunk-{timestamp}-{:032x}.log",
485                new_transaction_id()
486            );
487            let path = archive_directory.join(file_name);
488            match std::fs::OpenOptions::new()
489                .write(true)
490                .create_new(true)
491                .open(&path)
492            {
493                Ok(file) => break (file, path),
494                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
495                    if self.trace {
496                        crate::diagnostics::stderr!(
497                            "[Transactions] Archive entry already owned: {}.",
498                            path.display()
499                        );
500                    }
501                }
502                Err(error) => {
503                    return Err(LinkError::StorageError(format!(
504                        "failed to create archive file {}: {error}",
505                        path.display()
506                    )))
507                }
508            }
509        };
510        use std::io::Write;
511        for transition in &archived {
512            writeln!(file, "{}", transition.serialize())?;
513        }
514        file.flush()?;
515        if self.trace {
516            crate::diagnostics::stderr!(
517                "[Transactions] Archived {} transitions to {}.",
518                archived.len(),
519                path.display()
520            );
521        }
522        self.log.drain(0..chunk.len());
523        Ok(())
524    }
525}