reddb-io-server 1.40.5

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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
//! Bounded checkpoint projection of rows whose exact image is already in the WAL.
use super::commit::StoreWalAction;
use super::*;

enum SparseCheckpointValue {
    Cached,
    Wal(super::checkpoint_wal::WalRowReference),
    Projected(Vec<u8>),
}

thread_local! {
    /// Why the incremental checkpoint of the collection at hand gave up.
    static DECLINED: std::cell::Cell<Option<&'static str>> = const { std::cell::Cell::new(None) };
}

/// The incremental checkpoint gives up in many places and the collection is
/// then republished in full, which is what makes a checkpoint long. Keep the
/// first reason so the publication can say which bound a workload outgrew.
pub(super) fn declined<T>(reason: &'static str) -> Result<Option<T>, StoreError> {
    refused(reason);
    Ok(None)
}

pub(super) fn refused(reason: &'static str) -> bool {
    DECLINED.with(|slot| slot.set(slot.get().or(Some(reason))));
    false
}

pub(super) fn take_declined() -> Option<&'static str> {
    DECLINED.with(std::cell::Cell::take)
}

/// Index entries one incremental checkpoint may change across a collection.
pub(super) const POSTING_CHANGES_MAX: usize =
    8 * crate::storage::unified::segment::CHECKPOINT_MUTATIONS_MAX;

/// Whether a delta of `changed` rows is one the incremental checkpoint takes:
/// within the mutation journal and within the index entries it may change.
/// Staging a replacement tree asks the same question, so it copies a
/// collection only when the delta would have been declined.
pub(super) fn delta_fits(changed: usize, indexes: usize) -> bool {
    changed <= crate::storage::unified::segment::CHECKPOINT_MUTATIONS_MAX
        && changed.saturating_mul(indexes) <= POSTING_CHANGES_MAX
}

#[derive(Default)]
pub(super) struct DurableRows {
    rows: HashMap<(String, EntityId), Vec<u8>>,
    bytes: usize,
    collection_rows: HashMap<String, usize>,
    references: super::checkpoint_wal::WalRowReferences,
}

impl DurableRows {
    pub(super) fn memory_bytes(&self) -> usize {
        self.bytes + self.references.memory_bytes()
    }

    fn bytes_after_insert(&self, key: &(String, EntityId), capacity: usize) -> usize {
        let previous = self.rows.get(key);
        self.bytes
            .saturating_sub(previous.map_or(0, Vec::capacity))
            .saturating_add(capacity)
            .saturating_add(if previous.is_none() {
                key.0.len() + 128
            } else {
                0
            })
            .saturating_add(if self.collection_rows.contains_key(&key.0) {
                0
            } else {
                key.0.len() + 128
            })
    }

    fn forget_collection(&mut self, collection: &str) {
        if self.collection_rows.remove(collection).is_none() {
            return;
        }
        let mut reclaimed = collection.len() + 128;
        self.rows.retain(|(name, _), record| {
            if name != collection {
                return true;
            }
            reclaimed += record.capacity() + name.len() + 128;
            false
        });
        self.rows.shrink_to_fit();
        self.collection_rows.shrink_to_fit();
        self.bytes = self.bytes.saturating_sub(reclaimed);
    }

    fn remember(&mut self, collection: &str, record: Vec<u8>, limit: usize) {
        let frame = match reddb_file::decode_native_entity_record_frame(&record) {
            Ok(frame) => frame,
            Err(_) => return,
        };
        let entity = frame.map_or(record.as_slice(), |frame| frame.entity);
        let mut position = 0;
        let Ok(id) = read_varu64(entity, &mut position) else {
            return;
        };
        // The existing entity codec's table-row discriminator follows its ID.
        // Other models keep their existing inline/checkpoint paths.
        if entity.get(position) != Some(&0) {
            return;
        }
        let key = (collection.to_owned(), EntityId::new(id));
        let standalone_bytes = record
            .capacity()
            .saturating_add(2 * (collection.len() + 128));
        if standalone_bytes > limit {
            return;
        }
        if !self.rows.contains_key(&key)
            && self.collection_rows.get(collection).copied().unwrap_or(0) == 1024
        {
            self.forget_collection(collection);
        }
        let mut bytes = self.bytes_after_insert(&key, record.capacity());
        if bytes > limit {
            // Pressure in one collection must not evict another collection's
            // exact WAL proof while the shared byte budget can retain it.
            self.forget_collection(collection);
            bytes = self.bytes_after_insert(&key, record.capacity());
            if bytes > limit {
                let references = std::mem::take(&mut self.references);
                *self = Self {
                    references,
                    ..Self::default()
                };
                bytes = standalone_bytes;
            }
        }
        if self.rows.insert(key, record).is_none() {
            *self
                .collection_rows
                .entry(collection.to_owned())
                .or_default() += 1;
        }
        self.bytes = bytes;
    }
}

impl UnifiedStore {
    /// Whether the incremental checkpoint is certain to have what it needs to
    /// apply these changes in place: a published tree to apply them to, a
    /// delta within its bounds, and a retained WAL image for every changed row
    /// that still exists. It can still decline for other reasons, and then
    /// publishes the collection again inside the checkpoint.
    pub(super) fn delta_is_ready(
        &self,
        collection: &str,
        manager: &SegmentManager,
        changed: &[EntityId],
    ) -> bool {
        let indexes = self
            .key_indices
            .read()
            .get(collection)
            .map_or(0, |keys| keys.secondary.len());
        if !delta_fits(changed.len(), indexes)
            || !self
                .btree_indices
                .read()
                .get(collection)
                .is_some_and(|tree| tree.has_page_proofs() && tree.root_page_id() != 0)
        {
            return false;
        }
        let retained = self.checkpoint_durable_rows.read();
        let mut key = (collection.to_owned(), EntityId::new(0));
        changed.iter().all(|&id| {
            key.1 = id;
            manager.get_with(id, |_| ()).is_none()
                || retained.rows.contains_key(&key)
                || retained.references.get(collection, id).is_some()
        })
    }

    /// Called only after the WAL append succeeds. The ordinary inline KV path
    /// does not retain records here. The checkpoint's existing force_sync is
    /// the durability fence before any sparse projection changes pager pages.
    pub(super) fn remember_checkpoint_rows(
        &self,
        actions: Vec<StoreWalAction>,
        references: super::checkpoint_wal::CheckpointWalBatch,
    ) {
        if self.pager.is_none() || self.commit.is_none() {
            return;
        }
        // A store that does not size its page cache runs the pager's default
        // one. Budgeting this as if it had none kept a few hundred rows, and
        // every checkpoint of more than that republished its collection.
        let slots = self
            .config
            .page_cache_slots
            .unwrap_or_else(|| crate::storage::engine::PagerConfig::default().cache_size);
        let limit = (slots.saturating_mul(crate::storage::engine::PAGE_SIZE) / 32)
            .clamp(16 * 1024, 8 * 1024 * 1024);
        let mut retained = self.checkpoint_durable_rows.write();
        retained.references.remember(references, limit / 2);
        let limit = limit / 2;
        for action in actions {
            match action {
                StoreWalAction::UpsertEntityRecord { collection, record } => {
                    retained.remember(&collection, record, limit)
                }
                StoreWalAction::BulkUpsertEntityRecords {
                    collection,
                    records,
                } => {
                    for record in records {
                        retained.remember(&collection, record, limit);
                    }
                }
                _ => {}
            }
        }
    }

    /// Every changed ID must be accounted for by the bounded segment journal.
    /// An unchanged tree image needs no write; a different image requires an
    /// exact retained WAL record. Deferred MVCC rows are revisited when their
    /// transaction outcome changes, without inspecting unchanged payloads.
    /// Unknown edits, reader pins and exhausted journals retain the full path.
    pub(super) fn sparse_checkpoint_tree(
        &self,
        collection: &str,
        manager: &Arc<SegmentManager>,
        tree: &Arc<BTree>,
        previous: &CheckpointVersion,
        current: &mut CheckpointVersion,
    ) -> Result<Option<Arc<BTree>>, StoreError> {
        if manager.has_backing() {
            return self.sparse_cold_row_tree(collection, manager, tree, previous, current);
        }
        if Arc::strong_count(tree) != 1 || tree.has_retirement_readers() {
            return declined("a reader holds the data tree");
        }
        self.apply_sparse_checkpoint_tree(
            collection,
            manager,
            tree,
            previous,
            current,
            &Default::default(),
        )
    }

    pub(super) fn apply_sparse_checkpoint_tree(
        &self,
        collection: &str,
        manager: &Arc<SegmentManager>,
        tree: &Arc<BTree>,
        previous: &CheckpointVersion,
        current: &mut CheckpointVersion,
        logged_removals: &std::collections::HashSet<EntityId>,
    ) -> Result<Option<Arc<BTree>>, StoreError> {
        if previous.untracked_visibility_revision != current.untracked_visibility_revision {
            return declined("untracked visibility changed");
        }
        let Some(deferred) = previous.deferred_rows.as_ref() else {
            return declined("the previous checkpoint recorded no deferred rows");
        };
        let Some(ids) = manager.checkpoint_mutations_since(&previous.segments) else {
            return declined("the mutation journal no longer reaches the previous checkpoint");
        };
        let mut ids: std::collections::BTreeSet<_> = ids.into_iter().collect();
        ids.extend(deferred.iter().copied());
        ids.extend(
            previous
                .pending_vault
                .symmetric_difference(&current.pending_vault)
                .copied(),
        );
        if ids.len() > crate::storage::unified::segment::CHECKPOINT_MUTATIONS_MAX {
            return declined("more than 8192 changed rows");
        }
        let retained = self.checkpoint_durable_rows.read();
        let mut upserts = Vec::new();
        let mut projected_bytes = 0_usize;
        let mut deferred = Vec::new();
        for id in ids {
            // The cold path validates and applies these physical deletes with their postings.
            if logged_removals.contains(&id) {
                continue;
            }
            let key = id.raw().to_be_bytes().to_vec();
            let existing = tree
                .get(&key)
                .map_err(|error| StoreError::Io(std::io::Error::other(error.to_string())))?;
            let metadata = manager.get_metadata(id);
            let mut defer = false;
            let row = manager.get_with(id, |entity| {
                if current.pending_vault.contains(&id)
                    || current.excluded_xids.contains(&entity.xmin)
                {
                    defer = true;
                    return None;
                }
                let raw =
                    Self::serialize_entity_record(entity, metadata.as_ref(), self.format_version());
                let normalize_branch = entity.branch_version().is_some_and(|branch| {
                    branch
                        .deletions
                        .iter()
                        .any(|(_, xid)| current.excluded_xids.contains(xid))
                });
                let normalize_xmax = current.excluded_xids.contains(&entity.xmax);
                let projected = if normalize_xmax || normalize_branch {
                    defer = true;
                    let mut normalized = entity.clone();
                    if normalize_xmax {
                        normalized.xmax = 0;
                    }
                    normalized.retain_branch_deletions(|xid| !current.excluded_xids.contains(&xid));
                    Some(Self::serialize_entity_record(
                        &normalized,
                        metadata.as_ref(),
                        self.format_version(),
                    ))
                } else {
                    None
                };
                Some((raw, projected))
            });
            if defer {
                deferred.push(id);
            }
            let Some(row) = row else {
                if existing.is_some() {
                    return declined("a removed row is still published");
                }
                continue;
            };
            let Some((raw, projected)) = row else {
                if existing.is_some() {
                    return declined("a removed row is still published");
                }
                continue;
            };
            if existing.as_ref() == Some(projected.as_ref().unwrap_or(&raw)) {
                continue;
            }
            let source = if retained.rows.get(&(collection.to_owned(), id)) == Some(&raw) {
                SparseCheckpointValue::Cached
            } else if let (Some(commit), Some(reference)) =
                (&self.commit, retained.references.get(collection, id))
            {
                if !commit
                    .checkpoint_row_matches(reference, &raw)
                    .map_err(StoreError::Io)?
                {
                    return declined("a changed row differs from its WAL record");
                }
                SparseCheckpointValue::Wal(reference)
            } else {
                return declined("a changed row has no retained WAL record");
            };
            let source = if let Some(projected) = projected {
                projected_bytes = projected_bytes.saturating_add(projected.capacity());
                if projected_bytes > 8 * 1024 * 1024 {
                    return declined("normalized rows exceed 8 MiB");
                }
                SparseCheckpointValue::Projected(projected)
            } else {
                source
            };
            upserts.push((id, source));
        }
        if manager.checkpoint_revisions() != current.segments {
            return declined("rows changed while the checkpoint read them");
        }
        current.has_unprojected_rows = !deferred.is_empty();
        current.deferred_rows = Some(Arc::new(deferred));
        // Validate every source before changing the published tree. Afterwards
        // materialize only bounded batches from those exact durable images;
        // do not reread potentially changed manager payloads in a second pass.
        #[cfg(debug_assertions)]
        let root_before = tree.root_page_id();
        let protected = self.ownership_active_epoch.load(Ordering::Acquire) != 0;
        let tree = Arc::clone(tree);
        let apply = |items: &[(Vec<u8>, Vec<u8>)]| -> Result<(), StoreError> {
            if protected
                && tree
                    .try_upsert_inline_without_splits(items)
                    .map_err(|error| StoreError::Io(std::io::Error::other(error.to_string())))?
            {
                #[cfg(test)]
                if std::env::var_os("REDDB_TEST_EXIT_AFTER_INLINE_SPARSE_WRITE").is_some() {
                    self.pager
                        .as_ref()
                        .expect("paged checkpoint")
                        .sync()
                        .map_err(|error| {
                            StoreError::Io(std::io::Error::other(error.to_string()))
                        })?;
                    std::process::exit(190);
                }
            } else {
                // The ownership epoch records each old page before its first
                // overwrite. Recovery restores those images before reading
                // roots, then releases new pages and replays committed rows.
                tree.upsert_batch_sorted(items)
                    .map_err(|error| StoreError::Io(std::io::Error::other(error.to_string())))?;
            }
            #[cfg(debug_assertions)]
            if std::env::var_os("REDDB_TEST_EXIT_AFTER_SPARSE_BATCH").is_some() {
                self.pager
                    .as_ref()
                    .expect("paged checkpoint")
                    .sync()
                    .map_err(|error| StoreError::Io(std::io::Error::other(error.to_string())))?;
                std::process::exit(193);
            }
            Ok(())
        };
        let mut batch = Vec::new();
        let mut batch_bytes = 0_usize;
        for (id, source) in upserts {
            let value = match source {
                SparseCheckpointValue::Cached => retained
                    .rows
                    .get(&(collection.to_owned(), id))
                    .expect("validated retained image")
                    .clone(),
                SparseCheckpointValue::Wal(reference) => self
                    .commit
                    .as_ref()
                    .expect("validated durable WAL")
                    .checkpoint_row_bytes(reference)
                    .map_err(StoreError::Io)?,
                SparseCheckpointValue::Projected(value) => value,
            };
            let key = id.raw().to_be_bytes().to_vec();
            let bytes = key.len() + value.len();
            if !batch.is_empty()
                && (batch_bytes.saturating_add(bytes) > 1024 * 1024 || batch.len() >= 512)
            {
                apply(&batch)?;
                batch.clear();
                batch_bytes = 0;
            }
            batch_bytes += bytes;
            batch.push((key, value));
        }
        if !batch.is_empty() {
            apply(&batch)?;
        }
        drop(retained);
        #[cfg(debug_assertions)]
        if tree.root_page_id() != root_before
            && std::env::var_os("REDDB_TEST_CHECKPOINT_EXIT_AFTER_SPARSE_ROOT_CHANGE").is_some()
        {
            self.pager
                .as_ref()
                .expect("paged projection")
                .sync()
                .map_err(|error| StoreError::Io(std::io::Error::other(error.to_string())))?;
            std::process::exit(176);
        }
        Ok(Some(tree))
    }
}

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

    fn record(id: u64, payload_bytes: usize) -> Vec<u8> {
        let mut entity = UnifiedEntity::table_row(
            EntityId::new(id),
            "rows",
            id,
            vec![Value::text("p".repeat(payload_bytes))],
        );
        entity.created_at = 0;
        entity.updated_at = 0;
        UnifiedStore::serialize_entity_record(&entity, None, STORE_VERSION_V11)
    }

    #[test]
    fn row_capacity_eviction_keeps_accepting_exact_wal_images() {
        let mut retained = DurableRows::default();
        let limit = 8 * 1024 * 1024;
        for id in 1..=1025 {
            retained.remember("rows", record(id, 16), limit);
            assert!(retained.rows.len() <= 1024);
            assert!(retained.memory_bytes() <= limit);
        }
        assert!(!retained
            .rows
            .contains_key(&("rows".into(), EntityId::new(1))));
        assert_eq!(
            retained.rows.get(&("rows".into(), EntityId::new(1025))),
            Some(&record(1025, 16))
        );
    }

    #[test]
    fn byte_capacity_and_oversized_images_do_not_disable_later_retention() {
        let mut retained = DurableRows::default();
        let limit = 16 * 1024;
        for id in 1..=200 {
            retained.remember("rows", record(id, 256), limit);
            assert!(retained.memory_bytes() <= limit);
        }
        assert!(retained.rows.len() < 200, "byte pressure must evict images");
        assert_eq!(
            retained.rows.get(&("rows".into(), EntityId::new(200))),
            Some(&record(200, 256))
        );
        let mut oversized = record(201, limit);
        // The entity codec compresses repeated payloads. The retention budget
        // accounts for allocated capacity, so explicitly exceed that allowance.
        oversized.reserve_exact(limit + 1);
        assert!(oversized.capacity() > limit);
        retained.remember("rows", oversized, limit);
        assert!(retained.memory_bytes() <= limit);
        assert!(!retained
            .rows
            .contains_key(&("rows".into(), EntityId::new(201))));
        retained.remember("rows", record(202, 16), limit);
        assert_eq!(
            retained.rows.get(&("rows".into(), EntityId::new(202))),
            Some(&record(202, 16))
        );
    }

    #[test]
    fn unrelated_row_pressure_preserves_earlier_exact_images() {
        let mut retained = DurableRows::default();
        let limit = 8 * 1024 * 1024;
        let expected = record(1, 4096);
        retained.remember("payload", expected.clone(), limit);
        for id in 1..=1100 {
            retained.remember("noise", record(id, 16), limit);
            assert_eq!(
                retained.rows.get(&("payload".into(), EntityId::new(1))),
                Some(&expected),
                "unrelated row pressure discarded the earlier WAL proof"
            );
            assert!(retained.memory_bytes() <= limit);
        }
    }

    #[test]
    fn unrelated_byte_pressure_and_oversized_images_preserve_earlier_proofs() {
        let mut retained = DurableRows::default();
        let limit = 16 * 1024;
        let expected = record(1, 16);
        retained.remember("payload", expected.clone(), limit);
        for id in 1..=200 {
            retained.remember("noise", record(id, 256), limit);
            assert_eq!(
                retained.rows.get(&("payload".into(), EntityId::new(1))),
                Some(&expected)
            );
            assert!(retained.memory_bytes() <= limit);
        }
        let mut oversized = record(201, 16);
        oversized.reserve_exact(limit + 1);
        retained.remember("noise", oversized, limit);
        assert_eq!(
            retained.rows.get(&("payload".into(), EntityId::new(1))),
            Some(&expected)
        );
        assert!(retained.memory_bytes() <= limit);
    }
}