reddb-io-server 1.46.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
//! Local half of the serverless WAL archive.
//!
//! The commit WAL's LSN is a byte offset that restarts whenever a checkpoint
//! truncates or rewrites the file. The archive needs a position that survives
//! those rewrites, so the tap numbers every captured logical frame with a
//! monotonic *stream LSN*. The commit coordinator feeds it from two places:
//!
//! * the archiver's periodic capture (frames up to the durable LSN), and
//! * the checkpoint path, under the coordinator's exclusive epoch lock,
//!   immediately before frames are discarded from the local WAL.
//!
//! Commits never wait on the tap. Captured frames are batched in memory and
//! sealed into encoded segment files that the runtime uploads off the commit
//! path.

use std::collections::VecDeque;
use std::io::{self, Read, Seek, SeekFrom};
use std::path::Path;
use std::time::Instant;

use crate::storage::wal::WalRecord;

/// A sealed, encoded segment waiting for upload.
pub(crate) struct SealedWalSegment {
    pub epoch: u64,
    pub first_lsn: u64,
    pub last_lsn: u64,
    pub sha256: [u8; 32],
    pub bytes: u64,
    /// When the oldest frame in the segment was captured.
    pub oldest_captured_at: Instant,
    pub file: reddb_file::ServerlessWriterLeaseTempFile,
}

#[derive(Default)]
struct PendingBatch {
    payload: Vec<u8>,
    first_lsn: u64,
    frames: u64,
    oldest_captured_at: Option<Instant>,
}

struct TapState {
    max_segment_bytes: u64,
    wal_generation: u64,
    wal_offset: u64,
    wal_format_version: u8,
    epoch: u64,
    next_lsn: u64,
    pending: PendingBatch,
    sealed: VecDeque<SealedWalSegment>,
    last_sealed_sha: Option<[u8; 32]>,
    /// Set when the local WAL changed under the tap without a capture (for
    /// example a rewrite the tap was not told about). The stream then has an
    /// unknown gap and only a new generation can restart it.
    discontinuity: Option<String>,
    /// Segment popped for upload: (oldest capture time, bytes).
    in_flight: Option<(Instant, u64)>,
    captured_frames_total: u64,
    captured_bytes_total: u64,
}

/// Point-in-time view used by metrics and the archiver.
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct WalArchiveTapStatus {
    pub epoch: u64,
    pub next_lsn: u64,
    pub pending_frames: u64,
    pub pending_bytes: u64,
    pub sealed_segments: u64,
    pub sealed_bytes: u64,
    pub oldest_unarchived_at: Option<Instant>,
    pub captured_frames_total: u64,
    pub captured_bytes_total: u64,
}

/// Result of cutting a generation: the stream LSN its files include and the
/// digest of the segment that ends at that LSN (if any frame was archived).
#[derive(Debug, Clone, Copy)]
pub(crate) struct WalArchiveCut {
    pub wal_lsn: u64,
    pub prev_sha256: Option<[u8; 32]>,
}

pub(crate) struct WalArchiveTap {
    state: parking_lot::Mutex<TapState>,
}

impl WalArchiveTap {
    /// `next_lsn` is the first stream LSN this writer will assign; `prev_sha`
    /// links the first segment it seals to the last segment of the stream it
    /// continues (the restored tail, or `None` for a new stream).
    pub(crate) fn new(
        epoch: u64,
        next_lsn: u64,
        prev_sha: Option<[u8; 32]>,
        max_segment_bytes: u64,
    ) -> Self {
        Self {
            state: parking_lot::Mutex::new(TapState {
                max_segment_bytes: max_segment_bytes.max(1),
                wal_generation: 0,
                wal_offset: 0,
                wal_format_version: 0,
                epoch,
                next_lsn: next_lsn.max(1),
                pending: PendingBatch::default(),
                sealed: VecDeque::new(),
                last_sealed_sha: prev_sha,
                discontinuity: None,
                in_flight: None,
                captured_frames_total: 0,
                captured_bytes_total: 0,
            }),
        }
    }

    pub(crate) fn reset_cursor(&self, wal_generation: u64, wal_offset: u64, format_version: u8) {
        let mut state = self.state.lock();
        state.wal_generation = wal_generation;
        state.wal_offset = wal_offset;
        state.wal_format_version = format_version;
    }

    /// Capture logical frames in `[cursor, end)` of the local WAL. The caller
    /// holds the coordinator's epoch lock so the file cannot be rewritten and
    /// `end` is a durable frame boundary.
    pub(crate) fn capture(&self, wal_path: &Path, wal_generation: u64, end: u64) -> io::Result<()> {
        let mut state = self.state.lock();
        Self::capture_locked(&mut state, wal_path, wal_generation, end)
    }

    fn capture_locked(
        state: &mut TapState,
        wal_path: &Path,
        wal_generation: u64,
        end: u64,
    ) -> io::Result<()> {
        if let Some(reason) = &state.discontinuity {
            return Err(io::Error::other(format!(
                "WAL archive stream is discontinuous: {reason}"
            )));
        }
        if state.wal_generation != wal_generation {
            let reason = format!(
                "local WAL generation moved from {} to {wal_generation} without archive capture",
                state.wal_generation
            );
            state.discontinuity = Some(reason.clone());
            return Err(io::Error::other(reason));
        }
        if end <= state.wal_offset {
            return Ok(());
        }
        let start = state.wal_offset;
        let length = usize::try_from(end - start)
            .map_err(|_| io::Error::other("WAL archive capture range overflows memory"))?;
        let mut buffer = vec![0u8; length];
        let mut file = std::fs::File::open(wal_path)?;
        file.seek(SeekFrom::Start(start))?;
        file.read_exact(&mut buffer)?;
        let format_version = state.wal_format_version;
        let now = Instant::now();
        let mut cursor = io::Cursor::new(buffer.as_slice());
        let mut complete = 0usize;
        while complete < buffer.len() {
            let frame_start = complete;
            cursor.set_position(frame_start as u64);
            let record = match WalRecord::read_with_format_version(&mut cursor, format_version) {
                Ok(Some((_, record))) => record,
                Ok(None) => break,
                // A frame still being written past a sync boundary; the next
                // capture picks it up once it is complete.
                Err(err) if err.kind() == io::ErrorKind::UnexpectedEof => break,
                Err(err) => {
                    let reason = format!(
                        "local WAL frame at offset {} is unreadable: {err}",
                        start + frame_start as u64
                    );
                    state.discontinuity = Some(reason.clone());
                    return Err(io::Error::other(reason));
                }
            };
            let frame_end = cursor.position() as usize;
            complete = frame_end;
            if !archived_record(&record) {
                continue;
            }
            let frame = &buffer[frame_start..frame_end];
            let lsn = state.next_lsn;
            state.next_lsn += 1;
            let pending = &mut state.pending;
            if pending.frames == 0 {
                pending.first_lsn = lsn;
                pending.oldest_captured_at = Some(now);
            }
            reddb_file::push_serverless_wal_segment_frame(&mut pending.payload, frame);
            pending.frames += 1;
            state.captured_frames_total += 1;
            state.captured_bytes_total += frame.len() as u64;
            // Bound segment size (and memory) even when one capture spans a
            // large WAL range, such as a checkpoint after a bulk load.
            if state.pending.payload.len() as u64 >= state.max_segment_bytes {
                Self::seal_locked(state)?;
            }
        }
        state.wal_offset = start + complete as u64;
        Ok(())
    }

    /// Seal the pending batch when it is old enough (`max_age`) or large
    /// enough (`max_bytes`), or unconditionally when `force` is set. Returns
    /// whether a segment was sealed.
    pub(crate) fn seal_if_due(
        &self,
        now: Instant,
        max_age: std::time::Duration,
        max_bytes: u64,
        force: bool,
    ) -> io::Result<bool> {
        let mut state = self.state.lock();
        let due = match state.pending.oldest_captured_at {
            None => false,
            Some(oldest) => {
                force
                    || now.saturating_duration_since(oldest) >= max_age
                    || state.pending.payload.len() as u64 >= max_bytes
            }
        };
        if !due {
            return Ok(false);
        }
        Self::seal_locked(&mut state)?;
        Ok(true)
    }

    fn seal_locked(state: &mut TapState) -> io::Result<()> {
        if state.pending.frames == 0 {
            return Ok(());
        }
        let pending = std::mem::take(&mut state.pending);
        let header = reddb_file::ServerlessWalSegmentHeader {
            wal_format_version: state.wal_format_version,
            epoch: state.epoch,
            first_lsn: pending.first_lsn,
            last_lsn: pending.first_lsn + pending.frames - 1,
            prev_sha256: state.last_sealed_sha,
        };
        let (bytes, sha256) =
            reddb_file::encode_serverless_wal_segment(&header, pending.frames, &pending.payload)
                .map_err(|err| io::Error::other(err.to_string()))?;
        let file = reddb_file::ServerlessWriterLeaseTempFile::new("wal-segment");
        file.write_bytes(&bytes)
            .map_err(|err| io::Error::other(err.to_string()))?;
        state.last_sealed_sha = Some(sha256);
        state.sealed.push_back(SealedWalSegment {
            epoch: header.epoch,
            first_lsn: header.first_lsn,
            last_lsn: header.last_lsn,
            sha256,
            bytes: bytes.len() as u64,
            oldest_captured_at: pending.oldest_captured_at.unwrap_or_else(Instant::now),
            file,
        });
        Ok(())
    }

    /// Capture through `end`, let `copy` persist the local WAL prefix that
    /// ends at the captured offset, then seal and report the cut position.
    /// All three happen under one tap lock so a concurrent capture cannot
    /// move the stream between the copy and the reported LSN. Called with
    /// the coordinator's epoch lease held.
    pub(crate) fn cut(
        &self,
        wal_path: &Path,
        wal_generation: u64,
        end: u64,
        copy: impl FnOnce(u64) -> io::Result<()>,
    ) -> io::Result<WalArchiveCut> {
        let mut state = self.state.lock();
        Self::capture_locked(&mut state, wal_path, wal_generation, end)?;
        copy(state.wal_offset)?;
        Self::seal_locked(&mut state)?;
        Ok(WalArchiveCut {
            wal_lsn: state.next_lsn - 1,
            prev_sha256: state.last_sealed_sha,
        })
    }

    /// Run `upload` on the oldest sealed segment if it ends below
    /// `limit_lsn`; drop it on success. Returns `Ok(None)` when nothing is
    /// sealed or the oldest segment must wait.
    pub(crate) fn upload_front_below<E>(
        &self,
        limit_lsn: u64,
        upload: impl FnOnce(&SealedWalSegment) -> Result<(), E>,
    ) -> Result<Option<(u64, u64, u64)>, E> {
        // Uploads run without the state lock so capture (and therefore the
        // checkpoint path that captures under the epoch lock) never waits on
        // object storage. Only the archiver pops, so the front is stable.
        let front = {
            let mut state = self.state.lock();
            if state
                .sealed
                .front()
                .is_some_and(|segment| segment.last_lsn >= limit_lsn)
            {
                return Ok(None);
            }
            match state.sealed.pop_front() {
                Some(segment) => {
                    state.in_flight = Some((segment.oldest_captured_at, segment.bytes));
                    segment
                }
                None => return Ok(None),
            }
        };
        let result = upload(&front);
        let mut state = self.state.lock();
        state.in_flight = None;
        match result {
            Ok(()) => Ok(Some((front.first_lsn, front.last_lsn, front.bytes))),
            Err(err) => {
                state.sealed.push_front(front);
                Err(err)
            }
        }
    }

    pub(crate) fn status(&self) -> WalArchiveTapStatus {
        let state = self.state.lock();
        let oldest_sealed = state
            .in_flight
            .map(|(oldest, _)| oldest)
            .or_else(|| state.sealed.front().map(|s| s.oldest_captured_at));
        WalArchiveTapStatus {
            epoch: state.epoch,
            next_lsn: state.next_lsn,
            pending_frames: state.pending.frames,
            pending_bytes: state.pending.payload.len() as u64,
            sealed_segments: state.sealed.len() as u64 + u64::from(state.in_flight.is_some()),
            sealed_bytes: state.sealed.iter().map(|s| s.bytes).sum::<u64>()
                + state.in_flight.map(|(_, bytes)| bytes).unwrap_or(0),
            oldest_unarchived_at: oldest_sealed.or(state.pending.oldest_captured_at),
            captured_frames_total: state.captured_frames_total,
            captured_bytes_total: state.captured_bytes_total,
        }
    }

    pub(crate) fn discontinuity(&self) -> Option<String> {
        self.state.lock().discontinuity.clone()
    }

    /// Restart capture at `wal_offset` after a discontinuity. Frames between
    /// the last capture and `wal_offset` were never archived, so one stream
    /// LSN is skipped on purpose: a restore that would replay across the hole
    /// sees a gap and fails closed. Only a generation cut after this call can
    /// be followed by the frames captured from here on.
    pub(crate) fn restart_after_discontinuity(
        &self,
        wal_generation: u64,
        wal_offset: u64,
        format_version: u8,
    ) -> io::Result<()> {
        let mut state = self.state.lock();
        if state.discontinuity.is_none() {
            return Ok(());
        }
        Self::seal_locked(&mut state)?;
        state.next_lsn += 1;
        state.wal_generation = wal_generation;
        state.wal_offset = wal_offset;
        state.wal_format_version = format_version;
        state.discontinuity = None;
        Ok(())
    }
}

impl super::UnifiedStore {
    fn archive_commit(&self) -> io::Result<&std::sync::Arc<super::commit::StoreCommitCoordinator>> {
        self.commit
            .as_ref()
            .ok_or_else(|| io::Error::other("store has no commit WAL to archive"))
    }

    pub(crate) fn attach_wal_archive_tap(
        &self,
        tap: std::sync::Arc<WalArchiveTap>,
    ) -> io::Result<()> {
        self.archive_commit()?.attach_archive_tap(tap)
    }

    pub(crate) fn wal_archive_tap(&self) -> Option<std::sync::Arc<WalArchiveTap>> {
        self.commit.as_ref().and_then(|commit| commit.archive_tap())
    }

    pub(crate) fn capture_wal_archive_frames(&self) -> io::Result<()> {
        self.archive_commit()?.capture_archive_frames()
    }

    pub(crate) fn cut_wal_archive_generation(
        &self,
        destination: &Path,
    ) -> io::Result<WalArchiveCut> {
        self.archive_commit()?.cut_archive_generation(destination)
    }

    pub(crate) fn restart_wal_archive_after_discontinuity(&self) -> io::Result<()> {
        self.archive_commit()?.restart_archive_after_discontinuity()
    }

    pub(crate) fn commit_wal_path(&self) -> Option<std::path::PathBuf> {
        self.commit
            .as_ref()
            .map(|commit| commit.wal_path().to_path_buf())
    }
}

/// Logical frames replay on any physical layout; page ownership, page images,
/// and checkpoint markers describe this node's file and stay local.
pub(crate) fn archived_record(record: &WalRecord) -> bool {
    !matches!(
        record,
        WalRecord::PageOwnership { .. }
            | WalRecord::FullPageImage { .. }
            | WalRecord::Checkpoint { .. }
    )
}