reddb-io-server 1.43.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
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
//! Bounded physical table-history and aborted-queue reclamation.
use super::*;
use crate::storage::engine::BTreeCursor;
use crate::storage::transaction::SnapshotManager;
use crate::storage::unified::manager::PhysicalScanCursor;
use reddb_engine::storage::secondary_index_read::{SecondaryRangeCursor, SECONDARY_KEY_BYTES_MAX};

// These generation pins exist only within one fenced tick.
enum ColdInventory {
    Payloads(BTreeCursor),
    Visibility(SecondaryRangeCursor<Pager>),
}

pub(crate) struct MvccReclaimCursor {
    pub(crate) collection: String,
    manager: Arc<SegmentManager>,
    scan: PhysicalScanCursor,
    cold_after: Option<Vec<u8>>,
    cold_is_visibility: Option<bool>,
    cold_finished: bool,
    /// An ordered pass met a row still inside the window: nothing after it
    /// has expired.
    ordered_done: bool,
    /// The collection has used its share of the next checkpoint's delta.
    waits_for_checkpoint: bool,
    invalidated: bool,
}

impl MvccReclaimCursor {
    pub(crate) fn finished(&self) -> bool {
        self.invalidated
            || self.ordered_done
            || self.waits_for_checkpoint
            || (self.scan.finished() && self.cold_finished)
    }

    /// Whether the pass ended because nothing was left to visit.
    pub(crate) fn visited_every_position(&self) -> bool {
        !self.invalidated && self.scan.finished() && self.cold_finished
    }

    /// Whether an ordered tick will read the disk base: only then is every
    /// candidate it returns a row it read as expired.
    pub(crate) fn reads_the_base_in_order(&self) -> bool {
        !self.invalidated && !self.cold_finished && self.manager.has_backing()
    }

    /// Whether the pass went on to the resident rows, whose positions are all
    /// listed whatever their age.
    pub(crate) fn followed_into_resident_rows(&self) -> bool {
        self.cold_finished
    }

    /// Where an ordered pass ended: the last row of the base it read as
    /// expired or already removed.
    pub(crate) fn ordered_position(&self) -> Option<Vec<u8>> {
        self.ordered_done.then(|| self.cold_after.clone()).flatten()
    }

    /// Starts the pass after `key` instead of at the first row of the base.
    pub(crate) fn resume_after(&mut self, key: Vec<u8>) {
        self.cold_after = Some(key);
    }
}

/// How long a maintenance tick waits for the publication fence.
const MAINTENANCE_FENCE_WAIT: std::time::Duration = std::time::Duration::from_millis(50);

/// How long a maintenance removal waits for a walk of the collection's disk
/// base. It holds the publication fence meanwhile, and readers of the
/// collection queue behind it.
pub(super) const MAINTENANCE_WALK_WAIT: std::time::Duration = std::time::Duration::from_millis(5);

impl UnifiedStore {
    pub(crate) fn mvcc_reclaim_cursor(&self, collection: String) -> Option<MvccReclaimCursor> {
        let manager = self.get_collection(&collection)?;
        let scan = manager.physical_scan_cursor();
        Some(MvccReclaimCursor {
            collection,
            manager,
            scan,
            cold_after: None,
            cold_is_visibility: None,
            cold_finished: false,
            ordered_done: false,
            waits_for_checkpoint: false,
            invalidated: false,
        })
    }

    /// Inventory at most `budget` physical positions for retention. The caller
    /// must recheck the current row and retention predicate before deletion.
    /// The publication fence for one background maintenance tick.
    ///
    /// A tick that only tried the fence lost to foreground statements almost
    /// every time on a busy node: retention and version reclaim stopped while
    /// the load lasted and their backlog grew without bound. A short wait is
    /// enough to take a turn between statements; a checkpoint holding the
    /// fence for longer still makes the tick give up until the next one.
    fn maintenance_fence(&self) -> Option<parking_lot::ReentrantMutexGuard<'_, ()>> {
        self.vault_publication_lock
            .try_lock_for(MAINTENANCE_FENCE_WAIT)
    }

    /// [`Self::retention_scan_tick`] for a collection whose rows expire in the
    /// order of their ids: an insert-only ledger kept by its insertion time.
    ///
    /// The general inventory visits every position of the collection, pass
    /// after pass, because an expired row can be anywhere. A ledger of 800,000
    /// rows that loses 80 a minute was walked from end to end every few
    /// minutes for them, through a page cache far smaller than the ledger.
    /// Here the first row on disk still inside the window ends the pass: every
    /// later id, on disk or resident, was inserted later.
    ///
    /// A clock that stepped can leave an expired row behind a live one. Reads
    /// hide it at once; the caller's periodic pass over every position
    /// removes it.
    pub(crate) fn retention_scan_ordered_tick(
        &self,
        cursor: &mut MvccReclaimCursor,
        budget: usize,
        expired: &dyn Fn(&UnifiedEntity) -> bool,
    ) -> Result<(Vec<EntityId>, usize), StoreError> {
        let mut ids = Vec::new();
        let mut work_left = budget;
        {
            let Some(_publication) = self.maintenance_fence() else {
                return Ok((Vec::new(), 0));
            };
            let Some(manager) = self.get_collection(&cursor.collection) else {
                cursor.invalidated = true;
                return Ok((Vec::new(), 0));
            };
            if !Arc::ptr_eq(&manager, &cursor.manager) {
                cursor.invalidated = true;
                return Ok((Vec::new(), 0));
            }
            if !manager.has_backing() || cursor.cold_finished {
                // Nothing on disk to go by: every resident position is inspected.
                return self.retention_scan_tick(cursor, budget);
            }
            let tree = self
                .btree_indices
                .read()
                .get(&cursor.collection)
                .cloned()
                .ok_or_else(|| {
                    StoreError::Serialization("retention base has no published tree".into())
                })?;
            let start = match cursor.cold_after.as_deref() {
                Some(after) => {
                    let raw: [u8; 8] = after.try_into().map_err(|_| {
                        StoreError::Serialization("invalid retention cursor identity".into())
                    })?;
                    u64::from_be_bytes(raw).saturating_add(1).to_be_bytes()
                }
                None => 0_u64.to_be_bytes(),
            };
            let mut native = tree
                .cursor_seek(&start)
                .map_err(|e| StoreError::Io(std::io::Error::other(e.to_string())))?;
            while work_left > 0 {
                let Some(key) = native
                    .peek_key()
                    .map_err(|e| StoreError::Io(std::io::Error::other(e.to_string())))?
                else {
                    cursor.cold_finished = true;
                    break;
                };
                work_left -= 1;
                let raw: [u8; 8] = key.as_slice().try_into().map_err(|_| {
                    StoreError::Serialization("invalid retention physical identity".into())
                })?;
                let id = EntityId::new(u64::from_be_bytes(raw));
                // A removal stays in the base until the next checkpoint. Its
                // record is passed over without being read.
                if manager.backing_row_is_removed(id) {
                    native
                        .skip_next()
                        .map_err(|e| StoreError::Io(std::io::Error::other(e.to_string())))?;
                    cursor.cold_after = Some(key);
                    continue;
                }
                let Some((_, value)) = native
                    .next()
                    .map_err(|e| StoreError::Io(std::io::Error::other(e.to_string())))?
                else {
                    cursor.cold_finished = true;
                    break;
                };
                let (entity, _) = Self::deserialize_entity_record(&value, self.format_version())?;
                // An event already removed stays in the base until its
                // version is reclaimed. It is not a candidate again, and it
                // does not end the pass: it was written before any live one.
                if entity.xmax != 0 {
                    cursor.cold_after = Some(key);
                    continue;
                }
                if !expired(&entity) {
                    cursor.ordered_done = true;
                    break;
                }
                cursor.cold_after = Some(key);
                ids.push(id);
            }
            if cursor.ordered_done || !cursor.cold_finished {
                return Ok((ids, budget - work_left));
            }
        }
        // The whole base has expired, so resident rows may have too.
        let (resident, scanned) = self.retention_scan_tick(cursor, work_left)?;
        ids.extend(resident);
        ids.sort_unstable();
        ids.dedup();
        Ok((ids, budget - work_left + scanned))
    }

    pub(crate) fn retention_scan_tick(
        &self,
        cursor: &mut MvccReclaimCursor,
        budget: usize,
    ) -> Result<(Vec<EntityId>, usize), StoreError> {
        let Some(_publication) = self.maintenance_fence() else {
            return Ok((Vec::new(), 0));
        };
        let Some(manager) = self.get_collection(&cursor.collection) else {
            cursor.invalidated = true;
            return Ok((Vec::new(), 0));
        };
        if !Arc::ptr_eq(&manager, &cursor.manager) {
            cursor.invalidated = true;
            return Ok((Vec::new(), 0));
        }
        let mut work_left = budget;
        let mut ids = Vec::with_capacity(budget.min(128));
        while work_left > 0 && !cursor.scan.finished() {
            ids.extend(manager.physical_scan_batch(&mut cursor.scan, &mut work_left));
        }
        if !manager.has_backing() {
            cursor.cold_finished = true;
        }
        if work_left > 0 && !cursor.cold_finished {
            let tree = self
                .btree_indices
                .read()
                .get(&cursor.collection)
                .cloned()
                .ok_or_else(|| {
                    StoreError::Serialization("retention base has no published tree".into())
                })?;
            let start = match cursor.cold_after.as_deref() {
                Some(after) => {
                    let raw: [u8; 8] = after.try_into().map_err(|_| {
                        StoreError::Serialization("invalid retention cursor identity".into())
                    })?;
                    let Some(next) = u64::from_be_bytes(raw).checked_add(1) else {
                        cursor.cold_finished = true;
                        ids.sort_unstable();
                        ids.dedup();
                        return Ok((ids, budget - work_left));
                    };
                    next.to_be_bytes()
                }
                None => 0_u64.to_be_bytes(),
            };
            let mut native = tree
                .cursor_seek(&start)
                .map_err(|e| StoreError::Io(std::io::Error::other(e.to_string())))?;
            while work_left > 0 {
                let Some(key) = native
                    .peek_key()
                    .map_err(|e| StoreError::Io(std::io::Error::other(e.to_string())))?
                else {
                    cursor.cold_finished = true;
                    break;
                };
                let raw: [u8; 8] = key.as_slice().try_into().map_err(|_| {
                    StoreError::Serialization("invalid retention physical identity".into())
                })?;
                native
                    .skip_next()
                    .map_err(|e| StoreError::Io(std::io::Error::other(e.to_string())))?;
                cursor.cold_after = Some(key);
                ids.push(EntityId::new(u64::from_be_bytes(raw)));
                work_left -= 1;
            }
        }
        ids.sort_unstable();
        ids.dedup();
        Ok((ids, budget - work_left))
    }

    /// A busy checkpoint leaves the cursor untouched. Work is bounded by
    /// inspected positions, reclaimed versions and decoded bytes. Generation
    /// pins never survive the tick and force unrelated appends to copy history.
    pub(crate) fn reclaim_mvcc_tick(
        &self,
        cursor: &mut MvccReclaimCursor,
        snapshots: &SnapshotManager,
        cutoff: u64,
        scan_budget: usize,
        reclaim_budget: usize,
    ) -> Result<usize, StoreError> {
        self.reclaim_mvcc_tick_with(
            cursor,
            snapshots,
            |_| Ok(cutoff),
            scan_budget,
            reclaim_budget,
        )
    }

    /// Resolves the collection's cutoff inside the publication fence, so a
    /// retention decision cannot race a concurrent change of that policy.
    pub(crate) fn reclaim_mvcc_tick_with(
        &self,
        cursor: &mut MvccReclaimCursor,
        snapshots: &SnapshotManager,
        cutoff: impl FnOnce(&str) -> Result<u64, StoreError>,
        scan_budget: usize,
        reclaim_budget: usize,
    ) -> Result<usize, StoreError> {
        let Some(_publication) = self.maintenance_fence() else {
            return Ok(0);
        };
        let Some(manager) = self.get_collection(&cursor.collection) else {
            cursor.invalidated = true;
            return Ok(0);
        };
        if !Arc::ptr_eq(&manager, &cursor.manager) {
            cursor.invalidated = true;
            return Ok(0);
        }
        let reclaim_budget = reclaim_budget.min(self.maintenance_allowance(&cursor.collection));
        if reclaim_budget == 0 {
            // The pass ends here: the caller moves on to the next collection
            // and comes back to this one after the checkpoint.
            cursor.waits_for_checkpoint = true;
            return Ok(0);
        }
        let cutoff = cutoff(&cursor.collection)?;
        let mut scan_left = scan_budget;
        let mut reclaim = Vec::with_capacity(reclaim_budget);
        while scan_left > 0 && reclaim.len() < reclaim_budget && !cursor.scan.finished() {
            let work = scan_left.min(reclaim_budget - reclaim.len());
            let mut work_left = work;
            let ids = manager.physical_scan_batch(&mut cursor.scan, &mut work_left);
            scan_left -= work - work_left;
            manager.for_each_id(&ids, |_, entity| {
                if matches!(
                    entity.kind,
                    EntityKind::TableRow { .. } | EntityKind::QueueMessage { .. }
                ) && reclaimable(snapshots, cutoff, entity.xmin, entity.xmax)
                {
                    reclaim.push(entity.id);
                }
            });
        }
        if !manager.has_backing() {
            cursor.cold_finished = true;
        }
        if scan_left > 0 && reclaim.len() < reclaim_budget && !cursor.cold_finished {
            let previous_visibility = cursor.cold_is_visibility;
            let after = (previous_visibility == Some(true))
                .then_some(cursor.cold_after.as_deref())
                .flatten();
            let mut inventory = if let Some(index) =
                self.count_visibility_cursor(&cursor.collection, &manager, after)?
            {
                cursor.cold_is_visibility = Some(true);
                ColdInventory::Visibility(index)
            } else {
                let after = (previous_visibility == Some(false))
                    .then_some(cursor.cold_after.as_deref())
                    .flatten();
                let tree = self
                    .btree_indices
                    .read()
                    .get(&cursor.collection)
                    .cloned()
                    .ok_or_else(|| {
                        StoreError::Serialization("native GC base has no published tree".into())
                    })?;
                let mut native = tree
                    .cursor_seek(after.unwrap_or_default())
                    .map_err(|e| StoreError::Io(std::io::Error::other(e.to_string())))?;
                if let Some(after) = after {
                    if native
                        .peek_key()
                        .map_err(|e| StoreError::Io(std::io::Error::other(e.to_string())))?
                        .as_deref()
                        == Some(after)
                    {
                        native
                            .skip_next()
                            .map_err(|e| StoreError::Io(std::io::Error::other(e.to_string())))?;
                    }
                }
                cursor.cold_is_visibility = Some(false);
                ColdInventory::Payloads(native)
            };
            let read_limit = self.mvcc_reclaim_read_limit();
            let mut decoded_bytes = 0_usize;
            let mut projection = [0; SECONDARY_KEY_BYTES_MAX];
            while scan_left > 0 && reclaim.len() < reclaim_budget && decoded_bytes < read_limit {
                scan_left -= 1;
                let (id, candidate) = match &mut inventory {
                    ColdInventory::Payloads(native) => {
                        let Some(key) = native
                            .peek_key()
                            .map_err(|e| StoreError::Io(std::io::Error::other(e.to_string())))?
                        else {
                            cursor.cold_finished = true;
                            break;
                        };
                        let raw: [u8; 8] = key.as_slice().try_into().map_err(|_| {
                            StoreError::Serialization("invalid GC physical identity".into())
                        })?;
                        native
                            .skip_next()
                            .map_err(|e| StoreError::Io(std::io::Error::other(e.to_string())))?;
                        cursor.cold_after = Some(key);
                        (EntityId::new(u64::from_be_bytes(raw)), true)
                    }
                    ColdInventory::Visibility(index) => {
                        let Some((length, id)) = index.next_posting(&mut projection)? else {
                            cursor.cold_finished = true;
                            break;
                        };
                        if length != 17 || projection[16] > 1 {
                            return Err(StoreError::Serialization(
                                "invalid GC visibility projection".into(),
                            ));
                        }
                        let position = cursor
                            .cold_after
                            .get_or_insert_with(|| Vec::with_capacity(25));
                        position.clear();
                        position.extend_from_slice(&projection[..length]);
                        position.extend_from_slice(&id.raw().to_be_bytes());
                        let xmin = u64::from_be_bytes(
                            projection[..8].try_into().expect("eight-byte xmin"),
                        );
                        let xmax = u64::from_be_bytes(
                            projection[8..16].try_into().expect("eight-byte xmax"),
                        );
                        (id, reclaimable(snapshots, cutoff, xmin, xmax))
                    }
                };
                if !candidate {
                    continue;
                }
                // Positions inventory a possibly superseded generation. Only
                // the current base/overlay can authorize physical reclamation.
                if let Some(entity) = manager.try_get(id, read_limit)? {
                    decoded_bytes = decoded_bytes.saturating_add(
                        crate::storage::unified::memory_size::entity_bytes(&entity),
                    );
                    if matches!(
                        entity.kind,
                        EntityKind::TableRow { .. } | EntityKind::QueueMessage { .. }
                    ) && reclaimable(snapshots, cutoff, entity.xmin, entity.xmax)
                    {
                        reclaim.push(id);
                    }
                }
            }
        } // Release primary and visibility generation pins before publication.
        reclaim.sort_unstable();
        reclaim.dedup();
        let reclaimed = self
            .delete_batch_between_walks(&cursor.collection, &reclaim)?
            .len();
        self.charge_maintenance(&cursor.collection, reclaimed);
        Ok(reclaimed)
    }

    pub(crate) fn mvcc_reclaim_read_limit(&self) -> usize {
        usize::try_from(self.config.resident_memory_bytes_max.unwrap_or(0) / 8)
            .unwrap_or(usize::MAX)
            .clamp(16 * 1024, 16 * 1024 * 1024)
    }
}

fn reclaimable(snapshots: &SnapshotManager, cutoff: u64, xmin: u64, xmax: u64) -> bool {
    (xmin != 0 && snapshots.is_aborted(xmin))
        || (xmax != 0 && xmax < cutoff && !snapshots.is_aborted(xmax))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{RedDBOptions, RedDBRuntime};

    #[test]
    fn cold_gc_rechecks_overlays_and_preserves_active_creators() {
        for projected in [false, true] {
            let directory = tempfile::tempdir().unwrap();
            let path = directory.path().join("gc.rdb");
            let mut config = UnifiedStoreConfig::default().with_page_cache_slots(8);
            config.resident_memory_bytes_max = Some(4 * 1024 * 1024);
            let store = UnifiedStore::open_with_config(&path, config.clone()).unwrap();
            store.create_collection("rows").unwrap();
            if projected {
                store.register_count_index("rows").unwrap();
            }
            let snapshots = SnapshotManager::new();
            let active = snapshots.begin();
            let aborted = snapshots.begin();
            snapshots.rollback(aborted);
            for id in 1..=5 {
                let mut entity = UnifiedEntity::table_row(
                    EntityId::new(id),
                    "rows",
                    id,
                    vec![Value::Integer(id as i64)],
                );
                match id {
                    1 | 2 | 5 => entity.xmax = 5,
                    3 => entity.xmin = active,
                    4 => entity.xmin = aborted,
                    _ => unreachable!(),
                }
                store.insert("rows", entity).unwrap();
            }
            store.persist().unwrap();
            let manager = store.get_collection("rows").unwrap();
            assert!(manager.has_backing());
            let mut revived = manager
                .try_get(EntityId::new(2), usize::MAX)
                .unwrap()
                .unwrap();
            revived.xmax = 0;
            manager.update(revived).unwrap();
            let mut cursor = store.mvcc_reclaim_cursor("rows".into()).unwrap();
            let mut reclaimed = 0;
            for _ in 0..32 {
                let tick = store
                    .reclaim_mvcc_tick(&mut cursor, &snapshots, 10, 1, 1)
                    .unwrap();
                assert!(tick <= 1);
                reclaimed += tick;
                if cursor.finished() {
                    break;
                }
            }
            assert!(cursor.finished());
            assert_eq!(reclaimed, 3);
            assert!(manager
                .try_get(EntityId::new(1), usize::MAX)
                .unwrap()
                .is_none());
            assert!(manager
                .try_get(EntityId::new(4), usize::MAX)
                .unwrap()
                .is_none());
            assert!(
                manager
                    .try_get(EntityId::new(5), usize::MAX)
                    .unwrap()
                    .is_none(),
                "resume must preserve IDs sharing the same projected XIDs"
            );
            for id in [2, 3] {
                assert!(manager
                    .try_get(EntityId::new(id), usize::MAX)
                    .unwrap()
                    .is_some());
            }
            drop(cursor);
            store.persist().unwrap();
            drop(manager);
            drop(store);
            let reopened = UnifiedStore::open_with_config(&path, config).unwrap();
            assert_eq!(reopened.get_collection("rows").unwrap().count(), 2);
        }
    }

    fn fixture() -> RedDBRuntime {
        let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime opens");
        runtime
            .execute_query("SET CONFIG runtime.mvcc.autovacuum.enabled = false")
            .expect("disable automatic ticks");
        runtime
            .execute_query("CREATE TABLE reclaim_rows (id INTEGER, n INTEGER)")
            .expect("create table");
        runtime
    }

    #[test]
    fn maintenance_ticks_take_their_turn_on_a_busy_fence() {
        let runtime = fixture();
        runtime
            .execute_query("INSERT INTO reclaim_rows (id, n) VALUES (1, 0), (2, 0), (3, 0)")
            .expect("seed rows");
        let store = runtime.db().store();
        let stop = std::sync::atomic::AtomicBool::new(false);
        std::thread::scope(|scope| {
            // Foreground statements: the fence is free only between them.
            scope.spawn(|| {
                while !stop.load(Ordering::Acquire) {
                    let _fence = store.vault_publication_lock.lock();
                    std::thread::sleep(std::time::Duration::from_millis(2));
                }
            });
            std::thread::sleep(std::time::Duration::from_millis(20));
            let mut worked = 0;
            for _ in 0..20 {
                let mut cursor = store
                    .mvcc_reclaim_cursor("reclaim_rows".to_string())
                    .expect("open cursor");
                let (_, scanned) = store
                    .retention_scan_tick(&mut cursor, 8)
                    .expect("retention tick");
                worked += usize::from(scanned > 0);
            }
            stop.store(true, Ordering::Release);
            assert_eq!(worked, 20, "a tick must take its turn instead of skipping");
        });
    }

    #[test]
    fn collection_replacement_finishes_its_stale_cursor() {
        let runtime = fixture();
        runtime
            .execute_query("INSERT INTO reclaim_rows (id, n) VALUES (1, 0)")
            .expect("seed row");
        let store = runtime.db().store();
        let mut cursor = store
            .mvcc_reclaim_cursor("reclaim_rows".to_string())
            .expect("open cursor");
        runtime
            .execute_query("DROP TABLE reclaim_rows")
            .expect("drop source");
        runtime
            .execute_query("CREATE TABLE reclaim_rows (id INTEGER, n INTEGER)")
            .expect("replace source");
        runtime
            .execute_query("INSERT INTO reclaim_rows (id, n) VALUES (2, 1)")
            .expect("seed replacement");
        let reclaimed = store
            .reclaim_mvcc_tick(
                &mut cursor,
                &runtime.snapshot_manager(),
                runtime.mvcc_vacuum_cutoff_xid(),
                4096,
                256,
            )
            .expect("invalidate stale cursor");
        assert_eq!(reclaimed, 0);
        assert!(
            cursor.finished(),
            "collector would remain stuck on the replaced collection"
        );
        assert_eq!(
            runtime
                .execute_query("SELECT n FROM reclaim_rows WHERE id = 2")
                .expect("replacement survives")
                .result
                .records
                .len(),
            1
        );
    }

    #[test]
    fn reclamation_resumes_without_exceeding_its_delete_budget() {
        let runtime = fixture();
        let values = (0..128)
            .map(|id| format!("({id}, 0)"))
            .collect::<Vec<_>>()
            .join(",");
        runtime
            .execute_query(&format!("INSERT INTO reclaim_rows (id, n) VALUES {values}"))
            .expect("seed rows");
        runtime
            .execute_query("UPDATE reclaim_rows SET n = 1")
            .expect("create history");
        let store = runtime.db().store();
        let mut cursor = store
            .mvcc_reclaim_cursor("reclaim_rows".to_string())
            .expect("open cursor");
        let mut total = 0;
        for _ in 0..64 {
            let reclaimed = store
                .reclaim_mvcc_tick(
                    &mut cursor,
                    &runtime.snapshot_manager(),
                    runtime.mvcc_vacuum_cutoff_xid(),
                    32,
                    8,
                )
                .expect("bounded tick succeeds");
            assert!(reclaimed <= 8);
            total += reclaimed;
            if cursor.finished() {
                break;
            }
        }
        assert!(cursor.finished());
        assert_eq!(total, 128);
        assert_eq!(
            runtime
                .execute_query("SELECT COUNT(*) AS n FROM reclaim_rows WHERE n = 1")
                .expect("live rows survive")
                .result
                .records[0]
                .get("n")
                .expect("count exists")
                .to_string(),
            "128"
        );
    }

    #[test]
    fn aborted_event_messages_are_reclaimed_in_bounded_ticks_without_touching_readers() {
        use crate::runtime::mvcc::{clear_current_connection_id, set_current_connection_id};
        let runtime = fixture();
        runtime.execute_query("CREATE TABLE reclaim_event_source (id INT, payload TEXT) WITH EVENTS (DELETE) TO reclaim_events").expect("event source");
        let payload = "x".repeat(8192);
        runtime.execute_query(&format!("INSERT INTO reclaim_event_source (id, payload) VALUES (1, '{payload}'), (2, '{payload}'), (3, '{payload}')")).expect("source rows");
        runtime
            .enqueue_event_payload("reclaim_events", Value::text("committed"))
            .expect("committed message");
        set_current_connection_id(873);
        runtime.execute_query("BEGIN").expect("pending producer");
        runtime
            .enqueue_event_payload("reclaim_events", Value::text("pending"))
            .expect("pending message");
        clear_current_connection_id();
        let store = runtime.db().store();
        let queue = store.get_collection("reclaim_events").expect("outbox");
        let drain = || {
            let mut cursor = store
                .mvcc_reclaim_cursor("reclaim_events".into())
                .expect("queue cursor");
            let mut total = 0;
            for _ in 0..128 {
                let reclaimed = store
                    .reclaim_mvcc_tick(
                        &mut cursor,
                        &runtime.snapshot_manager(),
                        runtime.mvcc_vacuum_cutoff_xid(),
                        2,
                        1,
                    )
                    .expect("paced reclaim");
                assert!(reclaimed <= 1, "one tick exceeded its reclaim allowance");
                total += reclaimed;
                if cursor.finished() {
                    break;
                }
            }
            assert!(cursor.finished(), "bounded scan failed to finish");
            total
        };
        for cycle in 0..100 {
            store
                .test_fail_deferred_wal_append
                .store(true, Ordering::SeqCst);
            let error = runtime
                .execute_query("DELETE FROM reclaim_event_source")
                .expect_err("injected failed DELETE");
            assert!(error
                .to_string()
                .contains("injected deferred WAL append failure"));
            assert_eq!(drain(), 3, "aborted messages retained at cycle {cycle}");
            assert_eq!(
                queue.count(),
                2,
                "GC must keep committed and active creators"
            );
            queue.force_seal().expect("seal maintenance fixture");
            for _ in 0..16 {
                if !queue.pressure_consolidation_tick() {
                    break;
                }
            }
            assert!(
                queue.resident_bytes() < 64 * 1024,
                "failed outbox payloads accumulated at cycle {cycle}: {} bytes",
                queue.resident_bytes()
            );
            assert_eq!(
                runtime
                    .execute_query("QUEUE LEN reclaim_events")
                    .expect("visible message count")
                    .result
                    .records[0]
                    .get("len"),
                Some(&Value::UnsignedInteger(1))
            );
        }
        set_current_connection_id(873);
        runtime
            .execute_query("ROLLBACK")
            .expect("abort pending message");
        clear_current_connection_id();
        assert_eq!(
            drain(),
            1,
            "only the newly aborted producer becomes reclaimable"
        );
        assert_eq!(queue.count(), 1);
        assert_eq!(
            runtime
                .execute_query("DELETE FROM reclaim_event_source")
                .expect("successful source retry")
                .affected_rows,
            3
        );
        assert_eq!(drain(), 0, "committed event messages are not garbage");
        assert_eq!(
            runtime
                .execute_query("QUEUE LEN reclaim_events")
                .expect("committed event count")
                .result
                .records[0]
                .get("len"),
            Some(&Value::UnsignedInteger(4))
        );
    }

    #[test]
    fn queue_reclamation_preserves_old_readers_and_unfinished_deletions() {
        let runtime = fixture();
        runtime
            .execute_query("CREATE QUEUE retained_queue")
            .expect("queue");
        let store = runtime.db().store();
        let queue = store
            .get_collection("retained_queue")
            .expect("message store");
        let snapshots = runtime.snapshot_manager();
        let old_reader = snapshots.begin();
        let committed_delete = snapshots.begin();
        snapshots.commit(committed_delete);
        let pending_delete = snapshots.begin();
        let aborted_delete = snapshots.begin();
        snapshots.rollback(aborted_delete);
        for stamp in [0, committed_delete, pending_delete, aborted_delete] {
            let id = runtime
                .enqueue_event_payload("retained_queue", Value::text("retained"))
                .expect("message");
            let mut entity = queue.get(id).expect("message preimage");
            entity.set_xmax(stamp);
            queue.update(entity).expect("retirement stamp");
        }
        let reclaim = || {
            let mut cursor = store
                .mvcc_reclaim_cursor("retained_queue".into())
                .expect("cursor");
            let mut total = 0;
            for _ in 0..32 {
                let count = store
                    .reclaim_mvcc_tick(
                        &mut cursor,
                        &snapshots,
                        runtime.mvcc_vacuum_cutoff_xid(),
                        2,
                        1,
                    )
                    .expect("reclaim");
                assert!(count <= 1);
                total += count;
                if cursor.finished() {
                    break;
                }
            }
            assert!(cursor.finished());
            total
        };
        assert_eq!(
            reclaim(),
            0,
            "the old reader still needs the committed preimage"
        );
        assert_eq!(queue.count(), 4);
        snapshots.rollback(old_reader);
        assert_eq!(
            reclaim(),
            1,
            "only the committed, obsolete deletion is reclaimable"
        );
        assert_eq!(queue.count(), 3);
        snapshots.rollback(pending_delete);
        assert_eq!(
            reclaim(),
            0,
            "rolled-back deletions must preserve their messages"
        );
        assert_eq!(
            runtime
                .execute_query("QUEUE LEN retained_queue")
                .expect("retained messages")
                .result
                .records[0]
                .get("len"),
            Some(&Value::UnsignedInteger(3))
        );
    }
}