Skip to main content

lora_wal/recorder/
recorder.rs

1//! [`WalRecorder`] — adapter from `MutationRecorder` to the durable
2//! [`Wal`].
3//!
4//! Lifecycle, viewed from `lora-database::Database::execute_with_params`:
5//!
6//! 1. Acquire the store write lock.
7//! 2. `recorder.arm()` — marks the recorder as inside-a-query but
8//!    appends nothing to the WAL yet. A pure read query that fires
9//!    no `MutationEvent` therefore touches the WAL zero times.
10//! 3. Run analyze + compile + execute. The executor mutates the
11//!    in-memory store, which fires `MutationRecorder::record` for each
12//!    primitive mutation. The adapter buffers those events in memory.
13//! 4. On Ok: `recorder.commit()` drains the buffered events and hands
14//!    them to [`Wal::commit_tx`], which writes `TxBegin` +
15//!    `MutationBatch` + `TxCommit` in one critical section and applies
16//!    the configured single-thread flush policy. A read-only query returns
17//!    `WroteCommit::No` and the WAL never wakes up.
18//! 5. On Err / panic: `recorder.abort()` discards the buffered events.
19//!    Because `commit_tx` writes the begin/batch/commit triple
20//!    atomically, an aborted query has *no* on-disk presence — there
21//!    is no `TxBegin` to pair with a later `TxAbort`, so the WAL stays
22//!    consistent without an explicit abort marker.
23//! 6. Before returning, the host inspects `recorder.poisoned()` once.
24//!    If `Some`, the query fails loudly with a durability error so
25//!    the caller can act on it; the WAL is now refusing further
26//!    appends until the operator restarts the database, which
27//!    recovers from the last consistent snapshot + WAL.
28//!
29//! ### Hot-path cost
30//!
31//! `record` is called once per primitive mutation. It takes only the
32//! recorder mutex and pushes the event into a query-local buffer; the
33//! WAL mutex, framing, checksum, and segment append happen once at
34//! commit time inside `Wal::commit_tx`.
35//!
36//! ### When `record` fires after a failed in-memory mutation
37//!
38//! `InMemoryGraph::emit` only calls the recorder *after* the mutation
39//! has been committed to the in-memory state. If the subsequent WAL
40//! append fails, the live in-memory store is briefly ahead of disk:
41//! the next query sees the partial state, but the next query also
42//! observes `poisoned() = Some(_)` and is rejected. Recovery from a
43//! snapshot + WAL after operator restart will not include the failed
44//! mutation, so durable state stays consistent. The cost is "the live
45//! process is wrong until the next restart"; the gain is that the
46//! storage trait does not need to learn about durability.
47
48use std::sync::{Arc, Mutex, MutexGuard};
49
50use lora_store::{MutationEvent, MutationRecorder};
51
52use super::errors::{WalBufferedCommitError, WalPoisonError, WroteCommit};
53use super::mirror::WalMirror;
54use crate::errors::WalError;
55use crate::lsn::Lsn;
56use crate::wal::Wal;
57
58#[derive(Default)]
59struct RecorderState {
60    /// True between `arm()` and the matching `commit()` / `abort()`.
61    /// Marks the host's critical section so [`MutationRecorder::record`]
62    /// knows whether to buffer fresh events or poison itself for an
63    /// out-of-scope call.
64    armed: bool,
65    /// Query-local mutation buffer. Drained by `commit()` and passed
66    /// to [`Wal::commit_tx`] as one batched WAL transaction; cleared
67    /// by `abort()` without ever touching the durable log.
68    buffer: Vec<MutationEvent>,
69    /// Sticky failure flag. Once set, [`MutationRecorder::record`]
70    /// becomes a no-op (we cannot append safely) and `poisoned`
71    /// surfaces the message.
72    poisoned: Option<String>,
73}
74
75/// Adapter that lets a [`Wal`] act as a [`MutationRecorder`] on
76/// [`lora_store::InMemoryGraph::set_mutation_recorder`].
77pub struct WalRecorder {
78    wal: Arc<Wal>,
79    mirror: Option<Arc<dyn WalMirror>>,
80    state: Mutex<RecorderState>,
81}
82
83impl WalRecorder {
84    pub fn new(wal: Arc<Wal>) -> Self {
85        Self::new_with_mirror(wal, None)
86    }
87
88    pub fn new_with_mirror(wal: Arc<Wal>, mirror: Option<Arc<dyn WalMirror>>) -> Self {
89        Self {
90            wal,
91            mirror,
92            state: Mutex::new(RecorderState::default()),
93        }
94    }
95
96    /// Underlying log handle. Exposed so admin paths
97    /// (`Database::checkpoint_to`, `truncate_up_to`) can hit the WAL
98    /// directly without going through the recorder's transaction
99    /// state machine.
100    pub fn wal(&self) -> &Arc<Wal> {
101        &self.wal
102    }
103
104    fn state_lock(&self) -> MutexGuard<'_, RecorderState> {
105        self.state
106            .lock()
107            .unwrap_or_else(|poisoned| poisoned.into_inner())
108    }
109
110    /// Mark the recorder as inside a query critical section. No WAL
111    /// I/O happens here — `Wal::begin` is deferred until the first
112    /// mutation event fires. A pure read query that never produces a
113    /// `MutationEvent` therefore costs the WAL nothing: no record
114    /// allocation, no buffer drain, no `fsync`.
115    ///
116    /// Errors with [`WalError::Poisoned`] if a prior failure has
117    /// poisoned the recorder, or if the host is double-arming
118    /// (`arm` already in effect).
119    pub fn arm(&self) -> Result<(), WalError> {
120        let mut state = self.state_lock();
121        if state.poisoned.is_some() {
122            return Err(WalError::Poisoned);
123        }
124        if state.armed {
125            state.poisoned = Some("WalRecorder::arm called while already armed".into());
126            return Err(WalError::Poisoned);
127        }
128        state.armed = true;
129        state.buffer.clear();
130        Ok(())
131    }
132
133    /// Drain the buffered events and commit them as one durable WAL
134    /// transaction.
135    ///
136    /// Routes through [`Wal::commit_tx`], which encodes
137    /// `TxBegin` + `MutationBatch` + `TxCommit` in a single critical
138    /// section and applies the configured flush policy. Under
139    /// `SyncMode::PerCommit`, durability is complete when this method returns
140    /// — the legacy "commit then flush" split is gone.
141    ///
142    /// Returns:
143    /// - [`WroteCommit::Yes`] when mutation events fired and the WAL
144    ///   wrote the begin/batch/commit triple.
145    /// - [`WroteCommit::No`] when no mutations fired during the query
146    ///   and no records were written.
147    pub fn commit(&self) -> Result<WroteCommit, WalError> {
148        let events = {
149            let mut state = self.state_lock();
150            if state.poisoned.is_some() {
151                return Err(WalError::Poisoned);
152            }
153            if !state.armed {
154                state.poisoned = Some("WalRecorder::commit called without an armed query".into());
155                return Err(WalError::Poisoned);
156            }
157            state.armed = false;
158            std::mem::take(&mut state.buffer)
159        };
160
161        if events.is_empty() {
162            return Ok(WroteCommit::No);
163        }
164
165        self.wal.commit_tx(events).inspect_err(|e| {
166            self.state_lock()
167                .poisoned
168                .get_or_insert_with(|| e.to_string());
169        })
170    }
171
172    /// Commit an explicit transaction's externally-buffered mutation
173    /// events as one durable WAL transaction.
174    ///
175    /// Used by `lora-database`'s [`Transaction`] flow, which keeps its
176    /// own `Vec<MutationEvent>` per transaction (statements may
177    /// rollback to a savepoint, which the recorder's flat buffer
178    /// cannot model). At commit time the host hands the accumulated
179    /// events here and we route them through [`Wal::commit_tx`] in one
180    /// call.
181    ///
182    /// [`Transaction`]: lora_database::Transaction
183    pub fn commit_events(
184        &self,
185        events: impl IntoIterator<Item = MutationEvent>,
186    ) -> Result<WroteCommit, WalBufferedCommitError> {
187        self.ensure_not_poisoned()
188            .map_err(|e| WalBufferedCommitError::Poisoned(e.reason().to_string()))?;
189
190        let events: Vec<MutationEvent> = events.into_iter().collect();
191        if events.is_empty() {
192            return Ok(WroteCommit::No);
193        }
194
195        self.wal.commit_tx(events).map_err(|e| {
196            self.state_lock()
197                .poisoned
198                .get_or_insert_with(|| e.to_string());
199            WalBufferedCommitError::Commit(super::errors::WalCommitError::Commit(e))
200        })
201    }
202
203    /// Discard any buffered events and disarm the recorder.
204    ///
205    /// Because [`Wal::commit_tx`] writes the entire begin/batch/commit
206    /// triple atomically, an aborted query never has any on-disk
207    /// presence — there is no half-written transaction to follow up
208    /// with a `TxAbort` marker. The returned bool indicates whether
209    /// the query observed any mutations (so the host can decide
210    /// whether to quarantine the live in-memory graph).
211    pub fn abort(&self) -> Result<bool, WalError> {
212        let mut state = self.state_lock();
213        if state.poisoned.is_some() {
214            return Err(WalError::Poisoned);
215        }
216        // Tolerate "abort without arm" — the host calls abort in
217        // unwind paths and we'd rather no-op than poison.
218        state.armed = false;
219        let had_buffered_events = !state.buffer.is_empty();
220        state.buffer.clear();
221        Ok(had_buffered_events)
222    }
223
224    /// Flush the WAL — write the pending buffer to the OS and
225    /// (under `SyncMode::PerCommit`) `fsync`.
226    pub fn flush(&self) -> Result<(), WalError> {
227        let mut state = self.state_lock();
228        if state.poisoned.is_some() {
229            return Err(WalError::Poisoned);
230        }
231        self.wal.flush().inspect_err(|e| {
232            state.poisoned = Some(e.to_string());
233        })?;
234        if let Some(mirror) = &self.mirror {
235            mirror.persist(self.wal.dir()).inspect_err(|e| {
236                state.poisoned = Some(e.to_string());
237            })?;
238        }
239        Ok(())
240    }
241
242    /// Force the underlying WAL to write, `fsync`, and advance its
243    /// durable fence regardless of the configured sync mode. Admin
244    /// paths use this when they need a durability point immediately.
245    pub fn force_fsync(&self) -> Result<(), WalError> {
246        let mut state = self.state_lock();
247        if state.poisoned.is_some() {
248            return Err(WalError::Poisoned);
249        }
250        self.wal.force_fsync().inspect_err(|e| {
251            state.poisoned = Some(e.to_string());
252        })?;
253        if let Some(mirror) = &self.mirror {
254            mirror.persist_force(self.wal.dir()).inspect_err(|e| {
255                state.poisoned = Some(e.to_string());
256            })?;
257        }
258        Ok(())
259    }
260
261    /// Append a `Checkpoint` marker. Used by the checkpoint admin
262    /// path after a successful snapshot rename — the marker doubles
263    /// as the log-side fence the next replay will trust.
264    pub fn checkpoint_marker(&self, snapshot_lsn: Lsn) -> Result<Lsn, WalError> {
265        let mut state = self.state_lock();
266        if state.poisoned.is_some() {
267            return Err(WalError::Poisoned);
268        }
269        self.wal.checkpoint_marker(snapshot_lsn).inspect_err(|e| {
270            state.poisoned = Some(e.to_string());
271        })
272    }
273
274    /// Drop sealed segments at or below `fence_lsn`. Forwards to
275    /// [`Wal::truncate_up_to`].
276    pub fn truncate_up_to(&self, fence_lsn: Lsn) -> Result<(), WalError> {
277        // Archive-backed databases must stay self-contained. Until snapshot
278        // checkpoint payloads are stored inside the archive too, preserving the
279        // full WAL history is the only safe way to let the archive recover by
280        // itself after a checkpoint marker.
281        if let Some(mirror) = &self.mirror {
282            mirror.persist_force(self.wal.dir())?;
283            return Ok(());
284        }
285        self.wal.truncate_up_to(fence_lsn)?;
286        Ok(())
287    }
288
289    /// True iff the recorder has already failed an append, **or** the WAL has
290    /// latched a durability failure. Cheap to poll under the store lock.
291    pub fn is_poisoned(&self) -> bool {
292        self.poisoned_reason().is_some()
293    }
294
295    pub fn poisoned_reason(&self) -> Option<String> {
296        let state = self.state_lock();
297        if let Some(msg) = state.poisoned.clone() {
298            return Some(msg);
299        }
300        self.wal.bg_failure()
301    }
302
303    pub fn ensure_not_poisoned(&self) -> Result<(), WalPoisonError> {
304        if let Some(reason) = self.poisoned_reason() {
305            return Err(WalPoisonError { reason });
306        }
307        Ok(())
308    }
309
310    /// Quarantine the recorder after the host detects that the live
311    /// in-memory graph may no longer match durable state. Once poisoned,
312    /// future query arms fail until the database is restarted from a
313    /// snapshot + WAL.
314    pub fn poison(&self, reason: impl Into<String>) {
315        let mut state = self.state_lock();
316        state.poisoned.get_or_insert_with(|| reason.into());
317        state.armed = false;
318        state.buffer.clear();
319    }
320
321    /// Test helper: clear the poisoned flag and disarm. Production
322    /// code should not call this — once the WAL is poisoned the right
323    /// move is to fail loudly and let the operator restart from the
324    /// last snapshot + WAL.
325    #[doc(hidden)]
326    pub fn clear_poisoned_for_tests(&self) {
327        let mut state = self.state_lock();
328        state.poisoned = None;
329        state.armed = false;
330        state.buffer.clear();
331    }
332}
333
334impl MutationRecorder for WalRecorder {
335    fn record(&self, event: MutationEvent) {
336        let mut state = self.state_lock();
337        if state.poisoned.is_some() {
338            return;
339        }
340        if !state.armed {
341            state.poisoned.get_or_insert_with(|| {
342                "MutationRecorder::record fired outside an armed query".into()
343            });
344            return;
345        }
346        state.buffer.push(event);
347    }
348
349    fn poisoned(&self) -> Option<String> {
350        // Surface a latched WAL failure too — the recorder is the host's
351        // single point of contact for "is the WAL still safe to commit
352        // through?".
353        self.poisoned_reason()
354    }
355}