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 `GroupSync`,
139    /// bytes are written before this method returns; storage durability is
140    /// completed by the background flusher or an explicit sync boundary.
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.
225    pub fn flush(&self) -> Result<(), WalError> {
226        let mut state = self.state_lock();
227        if state.poisoned.is_some() {
228            return Err(WalError::Poisoned);
229        }
230        self.wal.flush().inspect_err(|e| {
231            state.poisoned = Some(e.to_string());
232        })?;
233        if let Some(mirror) = &self.mirror {
234            mirror.persist(self.wal.dir()).inspect_err(|e| {
235                state.poisoned = Some(e.to_string());
236            })?;
237        }
238        Ok(())
239    }
240
241    /// Force the underlying WAL to write, `fsync`, and advance its
242    /// durable fence regardless of the configured sync mode. Admin
243    /// paths use this when they need a durability point immediately.
244    pub fn force_fsync(&self) -> Result<(), WalError> {
245        let mut state = self.state_lock();
246        if state.poisoned.is_some() {
247            return Err(WalError::Poisoned);
248        }
249        self.wal.force_fsync().inspect_err(|e| {
250            state.poisoned = Some(e.to_string());
251        })?;
252        if let Some(mirror) = &self.mirror {
253            mirror.persist_force(self.wal.dir()).inspect_err(|e| {
254                state.poisoned = Some(e.to_string());
255            })?;
256        }
257        Ok(())
258    }
259
260    /// Append a `Checkpoint` marker. Used by the checkpoint admin
261    /// path after a successful snapshot rename — the marker doubles
262    /// as the log-side fence the next replay will trust.
263    pub fn checkpoint_marker(&self, snapshot_lsn: Lsn) -> Result<Lsn, WalError> {
264        let mut state = self.state_lock();
265        if state.poisoned.is_some() {
266            return Err(WalError::Poisoned);
267        }
268        self.wal.checkpoint_marker(snapshot_lsn).inspect_err(|e| {
269            state.poisoned = Some(e.to_string());
270        })
271    }
272
273    /// Drop sealed segments at or below `fence_lsn`. Forwards to
274    /// [`Wal::truncate_up_to`].
275    pub fn truncate_up_to(&self, fence_lsn: Lsn) -> Result<(), WalError> {
276        // Archive-backed databases must stay self-contained. Until snapshot
277        // checkpoint payloads are stored inside the archive too, preserving the
278        // full WAL history is the only safe way to let the archive recover by
279        // itself after a checkpoint marker.
280        if let Some(mirror) = &self.mirror {
281            mirror.persist_force(self.wal.dir())?;
282            return Ok(());
283        }
284        self.wal.truncate_up_to(fence_lsn)?;
285        Ok(())
286    }
287
288    /// True iff the recorder has already failed an append, **or** the WAL has
289    /// latched a durability failure. Cheap to poll under the store lock.
290    pub fn is_poisoned(&self) -> bool {
291        self.poisoned_reason().is_some()
292    }
293
294    pub fn poisoned_reason(&self) -> Option<String> {
295        let state = self.state_lock();
296        if let Some(msg) = state.poisoned.clone() {
297            return Some(msg);
298        }
299        self.wal.bg_failure()
300    }
301
302    pub fn ensure_not_poisoned(&self) -> Result<(), WalPoisonError> {
303        if let Some(reason) = self.poisoned_reason() {
304            return Err(WalPoisonError { reason });
305        }
306        Ok(())
307    }
308
309    /// Quarantine the recorder after the host detects that the live
310    /// in-memory graph may no longer match durable state. Once poisoned,
311    /// future query arms fail until the database is restarted from a
312    /// snapshot + WAL.
313    pub fn poison(&self, reason: impl Into<String>) {
314        let mut state = self.state_lock();
315        state.poisoned.get_or_insert_with(|| reason.into());
316        state.armed = false;
317        state.buffer.clear();
318    }
319
320    /// Test helper: clear the poisoned flag and disarm. Production
321    /// code should not call this — once the WAL is poisoned the right
322    /// move is to fail loudly and let the operator restart from the
323    /// last snapshot + WAL.
324    #[doc(hidden)]
325    pub fn clear_poisoned_for_tests(&self) {
326        let mut state = self.state_lock();
327        state.poisoned = None;
328        state.armed = false;
329        state.buffer.clear();
330    }
331}
332
333impl MutationRecorder for WalRecorder {
334    fn record(&self, event: MutationEvent) {
335        let mut state = self.state_lock();
336        if state.poisoned.is_some() {
337            return;
338        }
339        if !state.armed {
340            state.poisoned.get_or_insert_with(|| {
341                "MutationRecorder::record fired outside an armed query".into()
342            });
343            return;
344        }
345        state.buffer.push(event);
346    }
347
348    fn poisoned(&self) -> Option<String> {
349        // Surface a latched WAL failure too — the recorder is the host's
350        // single point of contact for "is the WAL still safe to commit
351        // through?".
352        self.poisoned_reason()
353    }
354}