reddb-io-server 1.41.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
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
//! Issue #584 — DeclarativeRetention slice 12.
//!
//! Background sweeper that physically removes rows whose timestamp column has fallen beyond the collection's
//! retention window. The
//! lazy-on-scan filter from slice 11 (`retention_filter`) hides
//! expired rows from reads the moment a policy is set; this slice
//! complements that filter with a low-priority background task that
//! reclaims storage in bounded batches.
//!
//! Mutable and append-only collection sweeps execute deletes through the standard
//! `RedDBRuntime::execute_query` chokepoint (`DELETE FROM <collection>
//! WHERE <timestamp> < <cutoff>`) so that WAL participation, snapshot guards and
//! event emission ride on the same single code path as user-issued
//! DELETEs — replicas replay sweeper deletes deterministically with
//! no special handling on the replication side. The scoped maintenance
//! context permits retention deletes on append-only collections while manual
//! DELETE remains prohibited. No external segment manifest is published.
//!
//! Per-collection runtime state (`last_sweep_at_ms`, `rows_swept_total`,
//! `segments_retired_total`, `last_pending_estimate`) lives on
//! `RuntimeInner::retention_sweeper` and is surfaced via the sweeper
//! columns on `red.retention`.
//! State is in-memory only — counters reset across restart, mirroring
//! the existing materialized-view scheduler state.

use std::cell::Cell;
use std::cell::RefCell;
use std::collections::HashMap;

thread_local! {
    static DELETE_LIMIT: Cell<Option<usize>> = const { Cell::new(None) };
    static TTL_EXPIRY_NOW_MS: Cell<Option<u64>> = const { Cell::new(None) };
    static TIMESTAMP_CONTEXT: RefCell<Option<(String, String)>> = const { RefCell::new(None) };
    static DELETE_CANDIDATES: RefCell<Option<Vec<crate::storage::EntityId>>> = const { RefCell::new(None) };
}

pub(crate) fn with_ttl_delete_candidates<T>(
    candidates: Vec<crate::storage::EntityId>,
    collection: &str,
    now_ms: u64,
    f: impl FnOnce() -> T,
) -> T {
    struct Restore(Option<u64>);
    impl Drop for Restore {
        fn drop(&mut self) {
            TTL_EXPIRY_NOW_MS.with(|slot| slot.set(self.0));
        }
    }
    let previous = TTL_EXPIRY_NOW_MS.with(|slot| slot.replace(Some(now_ms)));
    let _restore = Restore(previous);
    with_delete_candidates(candidates, collection, "rid", f)
}

pub(crate) fn ttl_expiry_now_ms() -> Option<u64> {
    TTL_EXPIRY_NOW_MS.with(Cell::get)
}

pub(crate) fn with_delete_candidates<T>(
    candidates: Vec<crate::storage::EntityId>,
    collection: &str,
    column: &str,
    f: impl FnOnce() -> T,
) -> T {
    struct Restore(Option<Vec<crate::storage::EntityId>>);
    impl Drop for Restore {
        fn drop(&mut self) {
            DELETE_CANDIDATES.with(|slot| *slot.borrow_mut() = self.0.take());
        }
    }
    let limit = candidates.len();
    let previous = DELETE_CANDIDATES.with(|slot| slot.replace(Some(candidates)));
    let _restore = Restore(previous);
    with_delete_limit(limit, collection, column, f)
}

/// Only the engine's scoped retention statement may delete append-only rows.
/// The collection identity prevents the exemption leaking into trigger writes.
pub(crate) fn is_retention_delete(collection: &str) -> bool {
    DELETE_CANDIDATES.with(|slot| slot.borrow().is_some())
        && TIMESTAMP_CONTEXT.with(|slot| {
            slot.borrow()
                .as_ref()
                .is_some_and(|(name, _)| name == collection)
        })
}

pub(crate) fn take_delete_candidates() -> Option<Vec<crate::storage::EntityId>> {
    DELETE_CANDIDATES.with(|slot| slot.borrow_mut().take())
}

/// Scope the limit to the synchronous maintenance statement and restore it on
/// every exit, including unwinding. The DELETE consumes it before publication.
pub(crate) fn with_delete_limit<T>(
    limit: usize,
    collection: &str,
    column: &str,
    f: impl FnOnce() -> T,
) -> T {
    struct Restore(Option<usize>, Option<(String, String)>);
    impl Drop for Restore {
        fn drop(&mut self) {
            DELETE_LIMIT.with(|slot| slot.set(self.0));
            TIMESTAMP_CONTEXT.with(|slot| *slot.borrow_mut() = self.1.take());
        }
    }
    let previous = DELETE_LIMIT.with(|slot| slot.replace(Some(limit)));
    let previous_context = TIMESTAMP_CONTEXT
        .with(|slot| slot.replace(Some((collection.to_owned(), column.to_owned()))));
    let _restore = Restore(previous, previous_context);
    f()
}

pub(crate) fn take_delete_limit() -> Option<usize> {
    DELETE_LIMIT.with(Cell::take)
}

pub(crate) fn cutoff_ms(now_ms: u64, retention_ms: u64) -> i64 {
    let cutoff = i128::from(now_ms) - i128::from(retention_ms);
    cutoff.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64
}

/// Resolve automatic timestamps in milliseconds only within the scoped
/// maintenance DELETE. Missing legacy values use the conservative end of the
/// stored second; malformed values do not qualify for deletion.
pub(crate) fn maintenance_timestamp(
    entity: &crate::storage::UnifiedEntity,
    field: &str,
) -> Option<reddb_types::Value> {
    let active = TIMESTAMP_CONTEXT.with(|slot| {
        slot.borrow().as_ref().is_some_and(|(collection, column)| {
            collection == entity.kind.collection()
                && column == field
                && matches!(field, "created_at" | "updated_at")
        })
    });
    if !active {
        return None;
    }
    let value = entity.data.as_row().and_then(|row| row.get_field(field));
    let millis = match value {
        Some(reddb_types::Value::TimestampMs(value))
        | Some(reddb_types::Value::BigInt(value))
        | Some(reddb_types::Value::Integer(value)) => Some(*value),
        Some(reddb_types::Value::Timestamp(value)) => value.checked_mul(1_000),
        Some(reddb_types::Value::UnsignedInteger(value)) => i64::try_from(*value).ok(),
        Some(_) => None,
        None => {
            let seconds = if field == "created_at" {
                entity.created_at
            } else {
                entity.updated_at
            };
            i64::try_from(seconds)
                .ok()
                .and_then(|seconds| seconds.checked_mul(1_000))
                .and_then(|millis| millis.checked_add(999))
        }
    };
    Some(
        millis
            .map(reddb_types::Value::Integer)
            .unwrap_or(reddb_types::Value::Null),
    )
}

/// Default per-tick batch size for the background sweeper. Acceptance
/// criterion: `default batch size red.retention.sweeper_batch (e.g.
/// 1000)`. Kept low enough that one tick is bounded work — the
/// sweeper never holds locks long enough to block the write path.
pub(crate) const DEFAULT_SWEEPER_BATCH: usize = 1_000;

/// A cold delete materializes each row before publishing its tombstone. Keep
/// one disk-resident tick small enough that foreground reads can run between
/// maintenance batches. The hot resident path retains the 1,000-row default.
/// Qualification bound: 32 cold rows x about 30 ms/row is about one second.
pub(crate) const DISK_RESIDENT_SWEEPER_BATCH: usize = 32;

/// Per-collection sweeper state surfaced on `red.retention`.
#[derive(Debug, Clone, Default)]
pub(crate) struct SweeperState {
    /// Wall-clock millis of the last sweep attempt — `0` until the
    /// sweeper first ticked the collection.
    pub last_sweep_at_ms: u64,
    /// Cumulative rows reclaimed since boot.
    pub rows_swept_total: u64,
    /// Cumulative append-only segments retired since boot.
    pub segments_retired_total: u64,
    /// Conservative signal that a full batch or an error may have left
    /// work for the next tick. This is not an exact backlog count.
    pub last_pending_estimate: u64,
    /// Cumulative individual-TTL rows reclaimed since boot.
    pub ttl_rows_swept_total: u64,
    /// Conservative remaining due rows after the latest bounded TTL tick.
    pub ttl_pending_estimate: u64,
    /// Duration of the latest individual-TTL tick for this collection.
    pub ttl_last_sweep_duration_ms: u64,
}

/// Per-runtime sweeper state map. Keyed by collection name.
/// What the sweeper did to one collection over a reporting interval.
#[derive(Debug, Clone)]
pub(crate) struct SweepActivity {
    since: std::time::Instant,
    pub(crate) ticks: u64,
    /// Positions inspected.
    pub(crate) positions: u64,
    /// Rows handed to the removing statement.
    pub(crate) candidates: u64,
    pub(crate) removed: u64,
    /// Ticks whose every candidate was read as expired.
    pub(crate) ordered_ticks: u64,
}

impl SweepActivity {
    fn starting(since: std::time::Instant) -> Self {
        Self {
            since,
            ticks: 0,
            positions: 0,
            candidates: 0,
            removed: 0,
            ordered_ticks: 0,
        }
    }
}

/// How often a retention sweep that removes nothing is reported.
const UNREMOVED_REPORT_INTERVAL: std::time::Duration = std::time::Duration::from_secs(600);

/// What stands between an expired row and its removal, for the log: whether
/// the row can be read by id, whether it is already deleted, what kind of
/// value its timestamp column holds, and its age. No row content.
pub(crate) fn describe_unremoved(
    store: &crate::storage::unified::store::UnifiedStore,
    collection: &str,
    column: &str,
    id: crate::storage::EntityId,
    now_ms: u64,
) -> String {
    let entity = match store.try_get(collection, id, usize::MAX) {
        Ok(Some(entity)) => entity,
        Ok(None) => return "row not found by id".to_string(),
        Err(err) => return format!("row unreadable by id: {err}"),
    };
    let field = match entity.data.as_row().and_then(|row| row.get_field(column)) {
        None => "absent",
        Some(reddb_types::Value::TimestampMs(_)) => "TimestampMs",
        Some(reddb_types::Value::Timestamp(_)) => "Timestamp",
        Some(reddb_types::Value::BigInt(_)) => "BigInt",
        Some(reddb_types::Value::Integer(_)) => "Integer",
        Some(reddb_types::Value::UnsignedInteger(_)) => "UnsignedInteger",
        Some(reddb_types::Value::Null) => "Null",
        Some(_) => "other",
    };
    let age_days = (now_ms / 1_000).saturating_sub(entity.created_at) / 86_400;
    format!(
        "stored_in={} deleted={} {column}_field={field} age_days={age_days}",
        entity.kind.collection(),
        entity.xmax != 0,
    )
}

/// How often the pass over a collection swept in id order visits every
/// position instead, as the first pass after a start does. An event stamped
/// ahead of time stops every ordered pass in front of it, and one stamped by
/// a clock that later stepped back sits behind newer ids; this pass reaches
/// the expired rows behind both.
const ORDERED_FULL_PASS_INTERVAL: std::time::Duration = std::time::Duration::from_secs(6 * 3600);

#[derive(Default)]
pub(crate) struct RetentionSweeperState {
    states: HashMap<String, SweeperState>,
    cursors: HashMap<String, crate::storage::unified::store::MvccReclaimCursor>,
    /// Collections swept in id order: when their last pass over every
    /// position ended, or `None` while one is under way.
    full_passes: HashMap<String, Option<std::time::Instant>>,
    /// When a sweep that removed nothing was last reported, per collection.
    reported: HashMap<String, std::time::Instant>,
    /// Where the last ordered pass over a collection ended. Everything before
    /// it was expired then, so the next ordered pass starts there.
    ordered_from: HashMap<String, Vec<u8>>,
    /// What the sweeper did to each collection since its last summary.
    activity: HashMap<String, SweepActivity>,
    ttl_projection_cursors: HashMap<String, crate::storage::unified::store::MvccReclaimCursor>,
    next_collection: Option<String>,
    next_ttl_collection: Option<String>,
}

impl RetentionSweeperState {
    pub(crate) fn new() -> Self {
        Self {
            states: HashMap::new(),
            cursors: HashMap::new(),
            full_passes: HashMap::new(),
            reported: HashMap::new(),
            ordered_from: HashMap::new(),
            activity: HashMap::new(),
            ttl_projection_cursors: HashMap::new(),
            next_collection: None,
            next_ttl_collection: None,
        }
    }

    /// `ordered` is the expiry test of a collection whose rows expire in the
    /// order of their ids; its pass ends at the first row inside the window.
    /// The last value says whether every candidate was read as expired, which
    /// only an ordered pass can say: the others list every position.
    pub(crate) fn scan_tick(
        &mut self,
        store: &crate::storage::unified::store::UnifiedStore,
        collection: &str,
        budget: usize,
        ordered: Option<&dyn Fn(&crate::storage::UnifiedEntity) -> bool>,
    ) -> Result<(Vec<crate::storage::EntityId>, usize, bool), crate::storage::StoreError> {
        if !self.cursors.contains_key(collection) {
            let Some(cursor) = store.mvcc_reclaim_cursor(collection.to_owned()) else {
                return Ok((Vec::new(), 0, false));
            };
            self.cursors.insert(collection.to_owned(), cursor);
            let due = ordered.is_some()
                && self
                    .full_passes
                    .get(collection)
                    .copied()
                    .flatten()
                    .is_none_or(|ended| ended.elapsed() >= ORDERED_FULL_PASS_INTERVAL);
            if due {
                self.full_passes.insert(collection.to_owned(), None);
            } else if ordered.is_some() {
                // Rows before this point were read as expired by an earlier
                // pass. Walking them again on every pass re-read every
                // removed event still waiting for its version to be reclaimed.
                if let Some(from) = self.ordered_from.get(collection) {
                    self.cursors
                        .get_mut(collection)
                        .expect("cursor was inserted")
                        .resume_after(from.clone());
                }
            }
        }
        let cursor = self
            .cursors
            .get_mut(collection)
            .expect("cursor was inserted");
        let full = self.full_passes.get(collection) == Some(&None);
        // An ordered tick on a collection with nothing on disk also lists
        // every resident position.
        let in_order = ordered.is_some() && !full && cursor.reads_the_base_in_order();
        let (ids, scanned) = match ordered {
            Some(expired) if !full => store.retention_scan_ordered_tick(cursor, budget, expired)?,
            _ => store.retention_scan_tick(cursor, budget)?,
        };
        let result = (
            ids,
            scanned,
            in_order && !cursor.followed_into_resident_rows(),
        );
        if let Some(position) = cursor.ordered_position() {
            self.ordered_from.insert(collection.to_owned(), position);
        }
        if cursor.finished() {
            if ordered.is_some() && full && cursor.visited_every_position() {
                self.full_passes
                    .insert(collection.to_owned(), Some(std::time::Instant::now()));
            }
            self.cursors.remove(collection);
        }
        Ok(result)
    }

    pub(crate) fn next_collection(&self) -> Option<&str> {
        self.next_collection.as_deref()
    }

    /// Adds one tick to the collection's running summary and returns the
    /// summary once [`UNREMOVED_REPORT_INTERVAL`] has passed, if the sweeper
    /// submitted anything in it. An idle sweeper stays silent.
    pub(crate) fn note_activity(
        &mut self,
        collection: &str,
        positions: usize,
        candidates: usize,
        removed: u64,
        in_order: bool,
    ) -> Option<SweepActivity> {
        let now = std::time::Instant::now();
        let activity = self
            .activity
            .entry(collection.to_owned())
            .or_insert_with(|| SweepActivity::starting(now));
        activity.ticks += 1;
        activity.positions += positions as u64;
        activity.candidates += candidates as u64;
        activity.removed += removed;
        activity.ordered_ticks += u64::from(in_order);
        if now.duration_since(activity.since) < UNREMOVED_REPORT_INTERVAL {
            return None;
        }
        let summary = std::mem::replace(activity, SweepActivity::starting(now));
        (summary.candidates != 0).then_some(summary)
    }

    /// Whether a sweep of `collection` that removed nothing is due a log line.
    /// The sweeper ticks twice a second; a standing fault says so once every
    /// [`UNREMOVED_REPORT_INTERVAL`].
    pub(crate) fn report_unremoved(&mut self, collection: &str) -> bool {
        let now = std::time::Instant::now();
        match self.reported.get(collection) {
            Some(last) if now.duration_since(*last) < UNREMOVED_REPORT_INTERVAL => false,
            _ => {
                self.reported.insert(collection.to_owned(), now);
                true
            }
        }
    }

    /// Whether a pass over the collection is under way.
    #[cfg(test)]
    pub(crate) fn pass_in_progress(&self, collection: &str) -> bool {
        self.cursors.contains_key(collection)
    }

    /// Whether a sweep of the collection was ever reported as removing none
    /// of the rows it read as expired.
    #[cfg(test)]
    pub(crate) fn unremoved_reported(&self, collection: &str) -> bool {
        self.reported.contains_key(collection)
    }

    pub(crate) fn rebuild_ttl_projection_tick(
        &mut self,
        store: &crate::storage::unified::store::UnifiedStore,
        collection: &str,
        budget: usize,
    ) -> Result<(usize, bool), crate::storage::StoreError> {
        if !self.ttl_projection_cursors.contains_key(collection) {
            let Some(cursor) = store.mvcc_reclaim_cursor(collection.to_owned()) else {
                return Ok((0, true));
            };
            self.ttl_projection_cursors
                .insert(collection.to_owned(), cursor);
        }
        let cursor = self
            .ttl_projection_cursors
            .get_mut(collection)
            .expect("TTL projection cursor was inserted");
        let (ids, scanned) = store.retention_scan_tick(cursor, budget)?;
        let manager = store
            .get_collection(collection)
            .ok_or_else(|| crate::storage::StoreError::CollectionNotFound(collection.into()))?;
        for id in ids {
            manager.rebuild_metadata_expiry(id)?;
        }
        let complete = cursor.finished();
        if complete {
            self.ttl_projection_cursors.remove(collection);
            manager.mark_metadata_expiry_projection_ready();
        }
        Ok((scanned, complete))
    }

    pub(crate) fn resume_at(&mut self, collection: String) {
        self.next_collection = Some(collection);
    }

    pub(crate) fn next_ttl_collection(&self) -> Option<&str> {
        self.next_ttl_collection.as_deref()
    }

    pub(crate) fn resume_ttl_at(&mut self, collection: String) {
        self.next_ttl_collection = Some(collection);
    }

    /// Snapshot of every tracked collection's sweeper state.
    pub(crate) fn snapshot(&self) -> Vec<(String, SweeperState)> {
        self.states
            .iter()
            .map(|(name, state)| (name.clone(), state.clone()))
            .collect()
    }

    /// Lookup the sweeper state for `collection`. Returns a fresh
    /// `SweeperState::default()` when the collection has never been
    /// ticked — keeps the call-site free of `Option` plumbing.
    pub(crate) fn get(&self, collection: &str) -> SweeperState {
        self.states.get(collection).cloned().unwrap_or_default()
    }

    /// Record the outcome of a sweeper tick.
    pub(crate) fn record_tick(
        &mut self,
        collection: &str,
        rows_swept: u64,
        pending_estimate: u64,
        at_unix_ms: u64,
    ) {
        let entry = self.states.entry(collection.to_string()).or_default();
        entry.last_sweep_at_ms = at_unix_ms;
        entry.rows_swept_total = entry.rows_swept_total.saturating_add(rows_swept);
        entry.last_pending_estimate = pending_estimate;
    }

    pub(crate) fn record_ttl_tick(
        &mut self,
        collection: &str,
        rows_swept: u64,
        pending_estimate: u64,
        duration_ms: u64,
        at_unix_ms: u64,
    ) {
        let entry = self.states.entry(collection.to_string()).or_default();
        entry.last_sweep_at_ms = at_unix_ms;
        entry.ttl_rows_swept_total = entry.ttl_rows_swept_total.saturating_add(rows_swept);
        entry.ttl_pending_estimate = pending_estimate;
        entry.ttl_last_sweep_duration_ms = duration_ms;
    }

    #[cfg(test)]
    pub(crate) fn record_segments_retired(
        &mut self,
        collection: &str,
        segments_retired: u64,
        at_unix_ms: u64,
    ) {
        let entry = self.states.entry(collection.to_string()).or_default();
        entry.last_sweep_at_ms = at_unix_ms;
        entry.segments_retired_total = entry
            .segments_retired_total
            .saturating_add(segments_retired);
    }

    /// Drop bookkeeping for a collection (DROP TABLE / DROP COLLECTION).
    pub(crate) fn forget(&mut self, collection: &str) {
        self.states.remove(collection);
        self.cursors.remove(collection);
    }
}

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

    fn row_count(runtime: &RedDBRuntime, table: &str) -> u64 {
        let result = runtime
            .execute_query(&format!("SELECT COUNT(*) AS n FROM {table}"))
            .expect("count TTL rows");
        match result.result.records[0].get("n").expect("count") {
            Value::UnsignedInteger(value) => *value,
            Value::Integer(value) => u64::try_from(*value).expect("non-negative count"),
            value => panic!("unexpected count {value:?}"),
        }
    }

    #[test]
    fn maintenance_delete_limit_is_consumed_and_restored_on_unwind() {
        assert_eq!(take_delete_limit(), None);
        with_delete_limit(2, "events", "created_at", || {
            assert_eq!(take_delete_limit(), Some(2));
            assert_eq!(take_delete_limit(), None);
            let _ = std::panic::catch_unwind(|| {
                with_delete_limit(3, "events", "created_at", || panic!("test unwind"))
            });
            assert_eq!(take_delete_limit(), None);
        });
        assert_eq!(take_delete_limit(), None);
    }

    #[test]
    fn retention_cutoff_never_wraps_long_durations() {
        assert_eq!(cutoff_ms(10, 3), 7);
        assert_eq!(cutoff_ms(10, u64::MAX), i64::MIN);
        assert_eq!(cutoff_ms(u64::MAX, 0), i64::MAX);
    }

    #[test]
    fn individual_ttl_sweep_is_bounded_without_policy_call() {
        let mut runtime = RedDBRuntime::in_memory().expect("runtime");
        drop(runtime.background_tasks.take());
        runtime
            .execute_query("CREATE TABLE ttl_rows (id INTEGER)")
            .expect("table");
        for id in 0..5 {
            runtime
                .execute_query(&format!(
                    "INSERT INTO ttl_rows (id) VALUES ({id}) WITH EXPIRES AT 1"
                ))
                .expect("expired row");
        }
        runtime
            .execute_query("INSERT INTO ttl_rows (id) VALUES (99) WITH EXPIRES AT 9999999999999")
            .expect("future row");
        let manager = runtime
            .db()
            .store()
            .get_collection("ttl_rows")
            .expect("TTL manager");
        assert_eq!(manager.scheduled_metadata_expiry_count(), 6);
        assert_eq!(manager.expired_metadata_ids(2, 10).len(), 5);

        assert_eq!(runtime.sweep_individual_ttl_tick_at(2, 2), 2);
        assert_eq!(manager.scheduled_metadata_expiry_count(), 4);
        assert_eq!(runtime.sweep_individual_ttl_tick_at(2, 2), 2);
        assert_eq!(manager.scheduled_metadata_expiry_count(), 2);
        assert_eq!(runtime.sweep_individual_ttl_tick_at(2, 2), 1);
        assert_eq!(manager.scheduled_metadata_expiry_count(), 1);

        let metrics = runtime
            .execute_query(
                "SELECT ttl_rows_swept_total, ttl_pending_sweep_estimate, \
                 ttl_last_sweep_duration_ms FROM red.retention WHERE name = 'ttl_rows'",
            )
            .expect("TTL retention metrics");
        let row = &metrics.result.records[0];
        assert_eq!(
            row.get("ttl_rows_swept_total"),
            Some(&Value::UnsignedInteger(5))
        );
        assert_eq!(
            row.get("ttl_pending_sweep_estimate"),
            Some(&Value::UnsignedInteger(0))
        );
        assert!(matches!(
            row.get("ttl_last_sweep_duration_ms"),
            Some(Value::UnsignedInteger(_))
        ));
    }

    #[test]
    fn background_sweeper_expires_individual_ttl_without_policy_call() {
        let runtime = RedDBRuntime::in_memory().expect("runtime");
        runtime
            .execute_query("CREATE TABLE ttl_background (id INTEGER)")
            .expect("table");
        runtime
            .execute_query("INSERT INTO ttl_background (id) VALUES (1) WITH EXPIRES AT 1")
            .expect("expired row");
        let manager = runtime
            .db()
            .store()
            .get_collection("ttl_background")
            .expect("TTL manager");

        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
        while manager.scheduled_metadata_expiry_count() != 0 && std::time::Instant::now() < deadline
        {
            std::thread::sleep(std::time::Duration::from_millis(20));
        }

        assert_eq!(manager.scheduled_metadata_expiry_count(), 0);
        assert_eq!(row_count(&runtime, "ttl_background"), 0);
    }

    #[test]
    fn expired_rows_are_invisible_on_the_primary_before_the_sweeper_deletes_them() {
        let mut runtime = RedDBRuntime::in_memory().expect("runtime");
        drop(runtime.background_tasks.take());
        runtime
            .execute_query("CREATE TABLE ttl_primary_visibility (id INTEGER)")
            .expect("table");
        runtime
            .execute_query("INSERT INTO ttl_primary_visibility (id) VALUES (1) WITH EXPIRES AT 1")
            .expect("expired row");

        let result = runtime
            .execute_query("SELECT id FROM ttl_primary_visibility")
            .expect("select expired row");

        assert!(
            result.result.records.is_empty(),
            "primary reads must not expose logically expired rows before bounded physical cleanup"
        );
    }

    #[test]
    fn grouped_aggregates_exclude_expired_rows_before_the_sweeper_deletes_them() {
        let mut runtime = RedDBRuntime::in_memory().expect("runtime");
        drop(runtime.background_tasks.take());
        runtime
            .execute_query("CREATE TABLE ttl_grouped_visibility (bucket TEXT, id INTEGER)")
            .expect("table");
        runtime
            .execute_query("INSERT INTO ttl_grouped_visibility (bucket, id) VALUES ('live', 1)")
            .expect("live row");
        runtime
            .execute_query(
                "INSERT INTO ttl_grouped_visibility (bucket, id) VALUES ('expired', 2) \
                 WITH EXPIRES AT 1",
            )
            .expect("expired row");

        let result = runtime
            .execute_query(
                "SELECT bucket, COUNT(*) AS n FROM ttl_grouped_visibility GROUP BY bucket",
            )
            .expect("grouped count");

        assert_eq!(result.result.records.len(), 1);
        assert_eq!(
            result.result.records[0].get("bucket"),
            Some(&Value::text("live"))
        );
    }

    #[test]
    fn bounded_ttl_sweeps_allow_concurrent_reads_and_writes() {
        let mut runtime = RedDBRuntime::in_memory().expect("runtime");
        drop(runtime.background_tasks.take());
        runtime
            .execute_query("CREATE TABLE ttl_concurrent (id INTEGER)")
            .expect("table");
        for id in 0..16 {
            runtime
                .execute_query(&format!(
                    "INSERT INTO ttl_concurrent (id) VALUES ({id}) WITH EXPIRES AT 1"
                ))
                .expect("expired row");
        }

        let reader_runtime = runtime.clone();
        let reader = std::thread::spawn(move || {
            for _ in 0..32 {
                let result = reader_runtime
                    .execute_query("SELECT 1")
                    .expect("scalar read");
                assert_eq!(result.result.records.len(), 1);
            }
        });
        let writer_runtime = runtime.clone();
        let writer = std::thread::spawn(move || {
            for id in 100..116 {
                writer_runtime
                    .execute_query(&format!(
                        "INSERT INTO ttl_concurrent (id) VALUES ({id}) \
                         WITH EXPIRES AT 9999999999999"
                    ))
                    .expect("concurrent future row");
            }
        });

        let mut swept = 0;
        while swept < 16 {
            let batch = runtime.sweep_individual_ttl_tick_at(4, 2);
            assert!(batch <= 4);
            swept += batch;
        }
        reader.join().expect("reader thread");
        writer.join().expect("writer thread");
        assert_eq!(swept, 16);
        assert_eq!(row_count(&runtime, "ttl_concurrent"), 16);
    }

    #[test]
    fn ttl_reclamation_returns_pages_for_reuse() {
        let directory = tempfile::tempdir().expect("TTL reuse fixture");
        let path = directory.path().join("ttl-reuse.rdb");
        let mut runtime = RedDBRuntime::with_options(
            RedDBOptions::persistent(&path)
                .with_memory_budget(32 * 1024 * 1024)
                .with_bounded_disk_residency(true),
        )
        .expect("runtime");
        drop(runtime.background_tasks.take());
        runtime
            .execute_query("CREATE TABLE ttl_reuse (id INTEGER, payload TEXT)")
            .expect("table");
        let payload = "x".repeat(64 * 1024);
        for id in 0..8 {
            runtime
                .execute_query_with_params(
                    "INSERT INTO ttl_reuse (id, payload) VALUES ($1, $2) WITH EXPIRES AT 1",
                    &[Value::Integer(id), Value::text(payload.clone())],
                )
                .expect("TTL payload");
        }
        runtime.checkpoint().expect("initial checkpoint");
        let initial_page_count = runtime
            .db()
            .store()
            .pager()
            .expect("pager")
            .page_count()
            .expect("initial page count");
        let mut swept = 0;
        while swept < 8 {
            swept += runtime.sweep_individual_ttl_tick_at(2, 2);
        }
        runtime.checkpoint().expect("tombstone checkpoint");

        let store = runtime.db().store();
        let mut cursor = store
            .mvcc_reclaim_cursor("ttl_reuse".into())
            .expect("TTL GC cursor");
        let mut reclaimed = 0;
        for _ in 0..64 {
            reclaimed += store
                .reclaim_mvcc_tick(
                    &mut cursor,
                    &runtime.snapshot_manager(),
                    runtime.mvcc_vacuum_cutoff_xid(),
                    32,
                    8,
                )
                .expect("TTL MVCC reclaim");
            if cursor.finished() {
                break;
            }
        }
        assert!(cursor.finished());
        assert_eq!(reclaimed, 8);
        drop(cursor);
        for _ in 0..3 {
            runtime.checkpoint().expect("publish free pages");
        }
        let pager = store.pager().expect("pager");
        let total_before_reuse = pager.page_count().expect("page count");
        let free_before_reuse = pager.free_page_count().expect("free pages");

        for id in 100..108 {
            runtime
                .execute_query_with_params(
                    "INSERT INTO ttl_reuse (id, payload) VALUES ($1, $2) \
                     WITH EXPIRES AT 9999999999999",
                    &[Value::Integer(id), Value::text(payload.clone())],
                )
                .expect("replacement payload");
        }
        runtime.checkpoint().expect("reuse checkpoint");
        let total_after_reuse = pager.page_count().expect("page count after reuse");
        assert!(
            total_after_reuse <= initial_page_count.saturating_add(16),
            "replacement TTL payloads failed to reuse the initial allocation: initial={initial_page_count}, before reuse={total_before_reuse}, free before reuse={free_before_reuse}, after reuse={total_after_reuse}"
        );
    }

    #[test]
    fn persisted_ttl_deadlines_rebuild_without_materializing_the_collection() {
        let directory = tempfile::tempdir().expect("TTL fixture");
        let options = RedDBOptions::persistent(directory.path().join("ttl.rdb"))
            .with_memory_budget(64 * 1024 * 1024)
            .with_storage_profile(
                crate::storage::profile::StorageDeployPreset::PrimaryReplicaDev.selection(),
            )
            .expect("profile");
        let deadline = 9_000_000_000_000u64;
        let mut runtime = RedDBRuntime::with_options(options.clone()).expect("seed runtime");
        drop(runtime.background_tasks.take());
        runtime
            .execute_query("CREATE TABLE ttl_restart (id INTEGER)")
            .expect("table");
        for id in 0..3 {
            runtime
                .execute_query(&format!(
                    "INSERT INTO ttl_restart (id) VALUES ({id}) WITH EXPIRES AT {deadline}"
                ))
                .expect("future row");
        }
        assert_eq!(runtime.sweep_individual_ttl_tick_at(2, deadline), 2);
        assert_eq!(row_count(&runtime, "ttl_restart"), 1);
        assert_eq!(
            runtime
                .db()
                .store()
                .get_collection("ttl_restart")
                .expect("TTL collection before checkpoint")
                .scheduled_metadata_expiry_count(),
            1
        );
        runtime
            .flush()
            .expect("checkpoint during bounded sweep backlog");
        drop(runtime);

        let mut runtime = crate::storage::RedDB::with_disk_residency_for_qualification(|| {
            RedDBRuntime::with_options(options)
        })
        .expect("reopen disk-resident runtime");
        drop(runtime.background_tasks.take());
        let manager = runtime
            .db()
            .store()
            .get_collection("ttl_restart")
            .expect("TTL collection");
        assert_eq!(manager.scheduled_metadata_expiry_count(), 1);
        assert_eq!(runtime.sweep_individual_ttl_tick_at(2, deadline), 1);
        assert_eq!(row_count(&runtime, "ttl_restart"), 0);
        drop(manager);
        drop(runtime);
    }

    #[test]
    fn disk_resident_ttl_tick_caps_cold_delete_work() {
        let directory = tempfile::tempdir().expect("TTL cold-delete fixture");
        let options = RedDBOptions::persistent(directory.path().join("ttl-cold.rdb"))
            .with_memory_budget(64 * 1024 * 1024)
            .with_bounded_disk_residency(true);
        {
            let mut runtime = RedDBRuntime::with_options(options.clone()).expect("seed runtime");
            drop(runtime.background_tasks.take());
            runtime
                .execute_query("CREATE TABLE ttl_cold (id INTEGER)")
                .expect("table");
            let values = (0..64)
                .map(|id| format!("({id})"))
                .collect::<Vec<_>>()
                .join(",");
            runtime
                .execute_query(&format!(
                    "INSERT INTO ttl_cold (id) VALUES {values} WITH EXPIRES AT 1"
                ))
                .expect("expired rows");
            runtime.flush().expect("persist cold TTL fixture");
        }

        let mut runtime = crate::storage::RedDB::with_disk_residency_for_qualification(|| {
            RedDBRuntime::with_options(options)
        })
        .expect("reopen disk-resident runtime");
        drop(runtime.background_tasks.take());

        let swept = runtime.sweep_individual_ttl_tick_at(DEFAULT_SWEEPER_BATCH, 2);
        assert_eq!(
            swept, 32,
            "one disk-resident maintenance tick must cap cold row materialization"
        );
        assert_eq!(
            runtime
                .db()
                .store()
                .get_collection("ttl_cold")
                .expect("cold TTL collection")
                .scheduled_metadata_expiry_count(),
            32,
            "logical expiry must remain queued for later physical ticks"
        );
        assert_eq!(row_count(&runtime, "ttl_cold"), 0);
    }

    #[test]
    fn legacy_timestamp_fallback_is_conservative_and_scoped() {
        use crate::storage::{EntityId, UnifiedEntity};
        let mut entity = UnifiedEntity::table_row(EntityId::new(1), "events", 1, vec![]);
        entity.created_at = 10;
        assert_eq!(maintenance_timestamp(&entity, "created_at"), None);
        with_delete_limit(1, "events", "created_at", || {
            assert_eq!(
                maintenance_timestamp(&entity, "created_at"),
                Some(reddb_types::Value::Integer(10_999))
            );
            assert_eq!(maintenance_timestamp(&entity, "updated_at"), None);
        });
        assert_eq!(maintenance_timestamp(&entity, "created_at"), None);
    }

    #[test]
    fn record_tick_accumulates_rows_swept_total() {
        let mut state = RetentionSweeperState::new();
        state.record_tick("events", 100, 50, 1_000);
        state.record_tick("events", 50, 0, 2_000);
        let s = state.get("events");
        assert_eq!(s.rows_swept_total, 150);
        assert_eq!(s.segments_retired_total, 0);
        assert_eq!(s.last_pending_estimate, 0);
        assert_eq!(s.last_sweep_at_ms, 2_000);
    }

    #[test]
    fn record_segments_retired_accumulates_without_rows() {
        let mut state = RetentionSweeperState::new();
        state.record_segments_retired("events", 1, 1_000);
        state.record_segments_retired("events", 2, 2_000);
        let s = state.get("events");
        assert_eq!(s.rows_swept_total, 0);
        assert_eq!(s.segments_retired_total, 3);
        assert_eq!(s.last_sweep_at_ms, 2_000);
    }

    #[test]
    fn get_unknown_collection_returns_zeroed_state() {
        let state = RetentionSweeperState::new();
        let s = state.get("missing");
        assert_eq!(s.last_sweep_at_ms, 0);
        assert_eq!(s.rows_swept_total, 0);
        assert_eq!(s.last_pending_estimate, 0);
    }

    #[test]
    fn forget_removes_bookkeeping() {
        let mut state = RetentionSweeperState::new();
        state.record_tick("events", 10, 0, 1);
        state.forget("events");
        assert_eq!(state.get("events").rows_swept_total, 0);
    }
}