reddb-io-server 1.10.0

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` crate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
//! Stale-term fencing for a returning ex-primary (issue #835, PRD #819, ADR 0030).
//!
//! After a failover the cluster serves a *new term*. A former primary that
//! rejoins on its old, **stale** term must not be able to corrupt the new
//! timeline — its term-stamped writes and its stream handshakes have to be
//! refused until it re-syncs and adopts the new term. This module is the
//! reusable term-comparison primitive both fencing boundaries share:
//!
//! * **Apply boundary** — a replica rejects a WAL/logical record whose term
//!   is behind its current term. The live replica apply path enforces this
//!   directly in [`super::logical::LogicalChangeApplier::apply`] (it already
//!   tracks the last-applied term); [`TermFence::admit_record`] is the same
//!   rule expressed over a durable term so it survives a restart.
//! * **Handshake boundary** — when a node opens a replication stream it
//!   declares the term it is streaming under. [`TermFence::admit_handshake`]
//!   refuses a handshake whose declared term is behind the current term, so a
//!   stale ex-primary cannot even establish the stream.
//!
//! The decision is deliberately the data-path twin of the election-side
//! [`super::RefusalReason::StaleTerm`]:
//!
//! * `incoming == current` → **admit** at the live term;
//! * `incoming  > current` → a newer timeline supersedes ours, so **adopt**
//!   the new term (persisted durably) and then admit. This is how a replica
//!   moves forward when the legitimate new primary streams to it;
//! * `incoming  < current` → **fenced**: a superseded primary, refused.
//!
//! The current term is held behind a [`TermStore`] so adoption is durable —
//! a replica that crashes after adopting term *N* comes back fencing stale
//! term *N-1* records rather than briefly accepting them. Production wires the
//! file-backed store alongside the node's other durable replication state;
//! tests use the in-memory store.

use crate::serde_json::{self, Value as JsonValue};

/// The boundary at which a term-stamped message is being admitted. Only
/// affects diagnostics — the term rule is identical at both.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FenceBoundary {
    /// A WAL/logical record being applied on a replica.
    Apply,
    /// A replication stream handshake declaring the streamer's term.
    Handshake,
}

impl FenceBoundary {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Apply => "apply",
            Self::Handshake => "handshake",
        }
    }
}

/// Why the term fence refused a message: the incoming term is behind the
/// current term, so the sender is a deposed primary on a superseded timeline.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StaleTermFenced {
    pub boundary: FenceBoundary,
    pub incoming_term: u64,
    pub current_term: u64,
}

impl std::fmt::Display for StaleTermFenced {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "fenced stale-term {} message: incoming term {} is behind current term {}",
            self.boundary.as_str(),
            self.incoming_term,
            self.current_term
        )
    }
}

impl std::error::Error for StaleTermFenced {}

/// The verdict of the term fence for one incoming term-stamped message.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FenceVerdict {
    /// `incoming == current`: admit at the live term.
    Admit { term: u64 },
    /// `incoming > current`: a newer timeline. The fence adopted `new_term`
    /// (persisting it) and the message is admitted under it.
    Adopt { new_term: u64 },
    /// `incoming < current`: stale — refused.
    Fenced(StaleTermFenced),
}

impl FenceVerdict {
    /// Was the message let through (either at the live term or after adopting
    /// a newer one)?
    pub fn is_admitted(&self) -> bool {
        matches!(self, Self::Admit { .. } | Self::Adopt { .. })
    }

    /// Was the message fenced as stale?
    pub fn is_fenced(&self) -> bool {
        matches!(self, Self::Fenced(_))
    }
}

/// Error reading or persisting the durable current term.
#[derive(Debug)]
pub enum TermStoreError {
    Io(std::io::Error),
    InvalidFormat(String),
}

impl std::fmt::Display for TermStoreError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io(err) => write!(f, "term store io error: {err}"),
            Self::InvalidFormat(msg) => write!(f, "invalid term store format: {msg}"),
        }
    }
}

impl std::error::Error for TermStoreError {}

/// Durable store for a node's current replication term. The default (when
/// nothing was ever written) is
/// [`DEFAULT_REPLICATION_TERM`](crate::replication::DEFAULT_REPLICATION_TERM),
/// matching the term records carry before any failover.
pub trait TermStore {
    fn load(&self) -> Result<u64, TermStoreError>;
    fn persist(&self, term: u64) -> Result<(), TermStoreError>;
}

/// In-memory term store for tests and ephemeral nodes.
#[derive(Debug)]
pub struct MemoryTermStore {
    inner: std::sync::Mutex<u64>,
}

impl Default for MemoryTermStore {
    fn default() -> Self {
        Self::new()
    }
}

impl MemoryTermStore {
    pub fn new() -> Self {
        Self {
            inner: std::sync::Mutex::new(crate::replication::DEFAULT_REPLICATION_TERM),
        }
    }

    /// Seed an initial term — used by tests to simulate a node that already
    /// adopted a term before a restart.
    pub fn seeded(term: u64) -> Self {
        Self {
            inner: std::sync::Mutex::new(term),
        }
    }
}

impl TermStore for MemoryTermStore {
    fn load(&self) -> Result<u64, TermStoreError> {
        Ok(*self.inner.lock().expect("term store mutex"))
    }

    fn persist(&self, term: u64) -> Result<(), TermStoreError> {
        *self.inner.lock().expect("term store mutex") = term;
        Ok(())
    }
}

/// File-backed term store. Persisted with the atomic temp-file + rename +
/// parent-dir fsync discipline used for the durable last-vote
/// ([`super::FileLastVoteStore`]) so a crash mid-write never yields a torn
/// record and an adopted term cannot be silently lost.
pub struct FileTermStore {
    path: std::path::PathBuf,
}

impl FileTermStore {
    pub fn new(path: impl Into<std::path::PathBuf>) -> Self {
        Self { path: path.into() }
    }
}

impl TermStore for FileTermStore {
    fn load(&self) -> Result<u64, TermStoreError> {
        match std::fs::read(&self.path) {
            Ok(bytes) => {
                let json: JsonValue = serde_json::from_slice(&bytes)
                    .map_err(|err| TermStoreError::InvalidFormat(format!("parse: {err}")))?;
                json.get("term")
                    .and_then(JsonValue::as_u64)
                    .ok_or_else(|| TermStoreError::InvalidFormat("missing term".into()))
            }
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                Ok(crate::replication::DEFAULT_REPLICATION_TERM)
            }
            Err(err) => Err(TermStoreError::Io(err)),
        }
    }

    fn persist(&self, term: u64) -> Result<(), TermStoreError> {
        let mut obj = serde_json::Map::new();
        obj.insert("term".to_string(), JsonValue::Number(term as f64));
        let bytes = serde_json::to_vec(&JsonValue::Object(obj))
            .map_err(|err| TermStoreError::InvalidFormat(format!("serialize: {err}")))?;
        if let Some(parent) = self.path.parent() {
            std::fs::create_dir_all(parent).map_err(TermStoreError::Io)?;
        }
        let tmp = self.path.with_extension("term.tmp");
        std::fs::write(&tmp, &bytes).map_err(TermStoreError::Io)?;
        if let Ok(f) = std::fs::File::open(&tmp) {
            let _ = f.sync_all();
        }
        std::fs::rename(&tmp, &self.path).map_err(TermStoreError::Io)?;
        // fsync the parent dir so the rename itself is durable — otherwise a
        // crash could leave the directory entry pointing at the old term and
        // let the node briefly accept records it had already fenced.
        if let Some(parent) = self.path.parent() {
            if let Ok(dir) = std::fs::File::open(parent) {
                let _ = dir.sync_all();
            }
        }
        Ok(())
    }
}

/// The stale-term fence. Wraps a durable [`TermStore`] and applies the term
/// rule at the apply and handshake boundaries.
pub struct TermFence<S: TermStore> {
    store: S,
}

impl<S: TermStore> TermFence<S> {
    pub fn new(store: S) -> Self {
        Self { store }
    }

    /// The node's current (highest adopted) term.
    pub fn current_term(&self) -> Result<u64, TermStoreError> {
        self.store.load()
    }

    /// Classify `incoming_term` against the current term **without** mutating
    /// anything. Pure read — useful for probing a decision before committing
    /// to the adoption side-effect.
    pub fn classify(
        &self,
        boundary: FenceBoundary,
        incoming_term: u64,
    ) -> Result<FenceVerdict, TermStoreError> {
        let current = self.store.load()?;
        Ok(if incoming_term < current {
            FenceVerdict::Fenced(StaleTermFenced {
                boundary,
                incoming_term,
                current_term: current,
            })
        } else if incoming_term > current {
            FenceVerdict::Adopt {
                new_term: incoming_term,
            }
        } else {
            FenceVerdict::Admit { term: current }
        })
    }

    /// Admit (or fence) a term-stamped **record** at the apply boundary. On a
    /// newer term the fence adopts it durably before returning `Adopt`.
    pub fn admit_record(&self, incoming_term: u64) -> Result<FenceVerdict, TermStoreError> {
        self.admit(FenceBoundary::Apply, incoming_term)
    }

    /// Admit (or fence) a stream **handshake** declaring `incoming_term`. On a
    /// newer term the fence adopts it durably before returning `Adopt`.
    pub fn admit_handshake(&self, incoming_term: u64) -> Result<FenceVerdict, TermStoreError> {
        self.admit(FenceBoundary::Handshake, incoming_term)
    }

    fn admit(
        &self,
        boundary: FenceBoundary,
        incoming_term: u64,
    ) -> Result<FenceVerdict, TermStoreError> {
        let verdict = self.classify(boundary, incoming_term)?;
        if let FenceVerdict::Adopt { new_term } = verdict {
            // Persist the adopted term before admitting so the advance is
            // durable: a crash right after this cannot un-adopt the new term.
            self.store.persist(new_term)?;
        }
        Ok(verdict)
    }

    /// Force the current term to `new_term`, persisting it. Used after a node
    /// re-syncs under a known term (e.g. a deposed primary rejoining as a
    /// replica) so it stops fencing the timeline it has now adopted. Never
    /// moves the term backwards.
    pub fn adopt(&self, new_term: u64) -> Result<(), TermStoreError> {
        let current = self.store.load()?;
        if new_term > current {
            self.store.persist(new_term)?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn fence(term: u64) -> TermFence<MemoryTermStore> {
        TermFence::new(MemoryTermStore::seeded(term))
    }

    // ---- Apply boundary ----

    #[test]
    fn apply_boundary_fences_stale_term() {
        let f = fence(5);
        let verdict = f.admit_record(4).unwrap();
        assert_eq!(
            verdict,
            FenceVerdict::Fenced(StaleTermFenced {
                boundary: FenceBoundary::Apply,
                incoming_term: 4,
                current_term: 5,
            })
        );
        assert!(verdict.is_fenced());
        // A fenced record must not move the current term.
        assert_eq!(f.current_term().unwrap(), 5);
    }

    #[test]
    fn apply_boundary_admits_current_term() {
        let f = fence(5);
        assert_eq!(f.admit_record(5).unwrap(), FenceVerdict::Admit { term: 5 });
        assert_eq!(f.current_term().unwrap(), 5);
    }

    #[test]
    fn apply_boundary_adopts_higher_term_durably() {
        let f = fence(5);
        assert_eq!(
            f.admit_record(8).unwrap(),
            FenceVerdict::Adopt { new_term: 8 }
        );
        // Adoption persisted: the old term is now fenced.
        assert_eq!(f.current_term().unwrap(), 8);
        assert!(f.admit_record(5).unwrap().is_fenced());
    }

    // ---- Handshake boundary ----

    #[test]
    fn handshake_boundary_fences_stale_term() {
        let f = fence(7);
        let verdict = f.admit_handshake(6).unwrap();
        assert_eq!(
            verdict,
            FenceVerdict::Fenced(StaleTermFenced {
                boundary: FenceBoundary::Handshake,
                incoming_term: 6,
                current_term: 7,
            })
        );
        assert!(verdict.is_fenced());
    }

    #[test]
    fn handshake_boundary_admits_current_and_adopts_higher() {
        let f = fence(7);
        assert_eq!(
            f.admit_handshake(7).unwrap(),
            FenceVerdict::Admit { term: 7 }
        );
        assert_eq!(
            f.admit_handshake(9).unwrap(),
            FenceVerdict::Adopt { new_term: 9 }
        );
        assert_eq!(f.current_term().unwrap(), 9);
    }

    // ---- End-to-end: returning ex-primary on a stale term ----

    #[test]
    fn returning_ex_primary_is_fenced_until_it_adopts_new_term() {
        // The replica adopted the new term 6 (handshake from the new primary).
        let f = fence(5);
        assert!(matches!(
            f.admit_handshake(6).unwrap(),
            FenceVerdict::Adopt { new_term: 6 }
        ));

        // The ex-primary returns on its stale term 5: both its handshake and
        // its records are fenced.
        assert!(f.admit_handshake(5).unwrap().is_fenced());
        assert!(f.admit_record(5).unwrap().is_fenced());

        // Only after it re-syncs and adopts the new term can it participate —
        // here it rejoins as a replica that has caught up to term 6.
        f.adopt(6).unwrap();
        assert!(f.admit_record(6).unwrap().is_admitted());
    }

    #[test]
    fn classify_is_pure_and_does_not_adopt() {
        let f = fence(3);
        // Classifying a higher term reports Adopt but must NOT persist it.
        assert_eq!(
            f.classify(FenceBoundary::Apply, 9).unwrap(),
            FenceVerdict::Adopt { new_term: 9 }
        );
        assert_eq!(f.current_term().unwrap(), 3, "classify must not mutate");
    }

    #[test]
    fn adopt_never_moves_term_backwards() {
        let f = fence(10);
        f.adopt(4).unwrap();
        assert_eq!(f.current_term().unwrap(), 10);
        f.adopt(12).unwrap();
        assert_eq!(f.current_term().unwrap(), 12);
    }

    // ---- File-backed durability ----

    #[test]
    fn file_term_store_round_trips_and_defaults() {
        let path = std::env::temp_dir().join(format!(
            "reddb-term-fence-{}-{}.json",
            std::process::id(),
            crate::utils::now_unix_nanos()
        ));
        let _ = std::fs::remove_file(&path);

        // Missing file → default base term.
        let store = FileTermStore::new(&path);
        assert_eq!(
            store.load().unwrap(),
            crate::replication::DEFAULT_REPLICATION_TERM
        );

        // Adopt across a "restart": a fresh store at the same path still
        // fences the old term.
        {
            let fence = TermFence::new(FileTermStore::new(&path));
            assert!(matches!(
                fence.admit_handshake(6).unwrap(),
                FenceVerdict::Adopt { new_term: 6 }
            ));
        }
        let reopened = TermFence::new(FileTermStore::new(&path));
        assert_eq!(reopened.current_term().unwrap(), 6);
        assert!(reopened.admit_record(5).unwrap().is_fenced());

        let _ = std::fs::remove_file(&path);
    }
}