reddb-io-server 1.42.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
//! Issue #2900 — native retention for `red.control_events`.
//!
//! The ledger appends one row per `emit()` and nothing removed them. This
//! module applies the declarative retention policy of issue #580/#584 to the
//! system collection instead of adding a dedicated deleter:
//!
//! - the policy lives on the collection contract (`retention_duration_ms`,
//!   anchored on the automatic `created_at` timestamp, which the ledger
//!   stamps at emit time);
//! - reads of `red.control_events` hide expired rows immediately
//!   (`red_schema::control_event_reads`);
//! - the background `retention_sweeper` deletes them in bounded batches
//!   through the regular `DELETE` path (WAL and replicas included);
//! - `red.retention` surfaces the policy and the sweeper counters.
//!
//! The window comes from `control_events.retention` (env
//! `REDDB_CONTROL_EVENTS_RETENTION`), e.g. `48h` or `7d`; `off` disables it.
//! It is applied at boot and again after `SET CONFIG control_events.retention`.
//! SQL DDL on `red.*` names stays refused.

use super::control_events::CONTROL_EVENTS_COLLECTION;
use super::RedDBRuntime;
use crate::{RedDBError, RedDBResult};

/// `red.config` key holding the retention window.
pub const CONFIG_KEY: &str = "control_events.retention";

/// Engine default when neither env nor `red.config` sets the key.
pub const DEFAULT_RETENTION: &str = "7d";

/// Parse a retention setting into milliseconds. `Ok(None)` disables the
/// policy. Accepts the duration forms of `SET RETENTION` (`48h`, `7d`,
/// `48 hours`, ...). A zero window is rejected because it would hide every
/// event.
pub(crate) fn parse_retention(raw: &str) -> Result<Option<u64>, String> {
    let value = raw.trim();
    if matches!(
        value.to_ascii_lowercase().as_str(),
        "off" | "none" | "disabled" | "false"
    ) {
        return Ok(None);
    }
    let invalid = || {
        format!("invalid {CONFIG_KEY} `{raw}`: expected a duration such as `48h` or `7d`, or `off`")
    };
    let nanos = reddb_types::duration::parse_duration_ns(value).ok_or_else(invalid)?;
    let millis = nanos / 1_000_000;
    if millis == 0 {
        return Err(invalid());
    }
    Ok(Some(millis))
}

/// Whether a ledger row falls outside the window. Mirrors the sweeper's
/// conservative reading of the second-resolution `created_at` (end of the
/// stored second), so reads never hide a row the sweeper would keep.
pub(crate) fn is_expired(entity: &crate::storage::UnifiedEntity, cutoff_ms: i64) -> bool {
    i64::try_from(entity.created_at)
        .ok()
        .and_then(|seconds| seconds.checked_mul(1_000))
        .and_then(|millis| millis.checked_add(999))
        .is_some_and(|millis| millis < cutoff_ms)
}

impl RedDBRuntime {
    /// Effective retention window for `red.control_events` in milliseconds
    /// (env > `red.config` > default). An invalid stored value falls back to
    /// the default so a bad setting can never disable retention silently.
    pub(crate) fn control_events_retention_ms(&self) -> Option<u64> {
        let raw = self.config_string(CONFIG_KEY, DEFAULT_RETENTION);
        match parse_retention(&raw) {
            Ok(window) => window,
            Err(err) => {
                tracing::warn!(
                    target: "reddb::control_events",
                    "{err}; using the default {DEFAULT_RETENTION}"
                );
                parse_retention(DEFAULT_RETENTION).expect("default retention parses")
            }
        }
    }

    /// Publish the configured window as the collection's retention policy.
    /// Idempotent; returns the applied window. Replicas keep the primary's
    /// contract and receive its sweeper deletes through the WAL.
    pub(crate) fn apply_control_events_retention(&self) -> RedDBResult<Option<u64>> {
        let window = self.control_events_retention_ms();
        let db = &self.inner.db;
        if db.is_replica_role()
            || db
                .store()
                .get_collection(CONTROL_EVENTS_COLLECTION)
                .is_none()
        {
            return Ok(window);
        }
        let mut contract = match db.collection_contract(CONTROL_EVENTS_COLLECTION) {
            Some(contract) => contract,
            None if window.is_none() => return Ok(window),
            None => super::impl_lifecycle::system_keyed_collection_contract(
                CONTROL_EVENTS_COLLECTION,
                crate::catalog::CollectionModel::Table,
            ),
        };
        if contract.timestamps_enabled && contract.retention_duration_ms == window {
            return Ok(window);
        }
        // The ledger never writes a timestamp column; `created_at` resolves to
        // the entity's insertion time, which is the event time.
        contract.timestamps_enabled = true;
        contract.retention_duration_ms = window;
        contract.updated_at_unix_ms = crate::utils::now_unix_millis() as u128;
        if db.options().read_only {
            db.cache_read_only_bootstrap_contract(contract);
            return Ok(window);
        }
        db.save_collection_contract(contract)
            .and_then(|_| db.persist_metadata())
            .map_err(|err| RedDBError::Internal(format!("{CONFIG_KEY}: {err}")))?;
        self.invalidate_result_cache();
        Ok(window)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::unified::{EntityData, EntityId, EntityKind, RowData};
    use crate::storage::UnifiedEntity;
    use reddb_types::Value;
    use std::sync::Arc;

    const DAY_MS: u64 = 86_400_000;

    #[test]
    fn parses_durations_and_off() {
        assert_eq!(parse_retention("7d"), Ok(Some(7 * DAY_MS)));
        assert_eq!(parse_retention("48h"), Ok(Some(2 * DAY_MS)));
        assert_eq!(parse_retention(" 48 hours "), Ok(Some(2 * DAY_MS)));
        assert_eq!(parse_retention("OFF"), Ok(None));
        assert!(parse_retention("0d").is_err());
        assert!(parse_retention("forever").is_err());
    }

    #[test]
    fn env_override_is_the_matrix_env_name() {
        assert_eq!(
            crate::runtime::config_overlay::env_name_for(CONFIG_KEY),
            "REDDB_CONTROL_EVENTS_RETENTION"
        );
        assert_eq!(
            crate::runtime::config_overlay::coerce_env_value(CONFIG_KEY, "48h"),
            Some(Value::text("48h"))
        );
    }

    fn insert_event(runtime: &RedDBRuntime, id: &str, age_secs: u64) {
        let mut named = std::collections::HashMap::new();
        named.insert("id".to_string(), Value::text(id.to_string()));
        named.insert("kind".to_string(), Value::text("test.retention"));
        let mut entity = UnifiedEntity::new(
            EntityId::new(0),
            EntityKind::TableRow {
                table: Arc::from(CONTROL_EVENTS_COLLECTION),
                row_id: 0,
            },
            EntityData::Row(RowData {
                columns: Vec::new(),
                named: Some(named),
                schema: None,
            }),
        );
        let now_secs = crate::utils::now_unix_millis() / 1_000;
        entity.created_at = now_secs - age_secs;
        entity.updated_at = entity.created_at;
        runtime
            .db()
            .store()
            .insert_auto(CONTROL_EVENTS_COLLECTION, entity)
            .expect("insert control event");
    }

    fn visible_ids(runtime: &RedDBRuntime) -> Vec<String> {
        let result = runtime
            .execute_query("SELECT id FROM red.control_events WHERE kind = 'test.retention'")
            .expect("read control events");
        let mut ids: Vec<String> = result
            .result
            .records
            .iter()
            .filter_map(|record| match record.get("id") {
                Some(Value::Text(id)) => Some(id.to_string()),
                _ => None,
            })
            .collect();
        ids.sort();
        ids
    }

    /// Live physical versions (a sweeper DELETE stamps `xmax`).
    fn physical_ids(runtime: &RedDBRuntime) -> usize {
        let manager = runtime
            .db()
            .store()
            .get_collection(CONTROL_EVENTS_COLLECTION)
            .expect("ledger collection");
        let mut count = 0;
        manager.for_each_entity(|entity| {
            if entity.xmax == 0
                && entity
                    .data
                    .as_row()
                    .and_then(|row| row.get_field("kind"))
                    .is_some_and(|kind| kind == &Value::text("test.retention"))
            {
                count += 1;
            }
            true
        });
        count
    }

    fn retention_row(runtime: &RedDBRuntime) -> Option<Value> {
        let result = runtime
            .execute_query(
                "SELECT retention_duration FROM red.retention WHERE name = 'red.control_events'",
            )
            .expect("red.retention");
        result
            .result
            .records
            .first()
            .and_then(|record| record.get("retention_duration").cloned())
    }

    fn runtime() -> RedDBRuntime {
        let mut runtime = RedDBRuntime::in_memory().expect("runtime");
        drop(runtime.background_tasks.take());
        runtime
    }

    #[test]
    fn default_window_is_seven_days_and_sweeper_removes_expired_events() {
        let runtime = runtime();
        assert_eq!(
            runtime
                .apply_control_events_retention()
                .expect("boot policy"),
            Some(7 * DAY_MS)
        );
        assert_eq!(
            retention_row(&runtime),
            Some(Value::UnsignedInteger(7 * DAY_MS))
        );

        insert_event(&runtime, "fresh", 3_600);
        insert_event(&runtime, "stale", 8 * 86_400);
        assert_eq!(visible_ids(&runtime), vec!["fresh".to_string()]);
        assert_eq!(physical_ids(&runtime), 2);

        for _ in 0..8 {
            runtime.sweep_retention_tick(1_000);
        }
        assert_eq!(physical_ids(&runtime), 1, "sweeper deletes the stale event");
        assert_eq!(visible_ids(&runtime), vec!["fresh".to_string()]);
        let swept = runtime
            .execute_query(
                "SELECT rows_swept_total FROM red.retention WHERE name = 'red.control_events'",
            )
            .expect("sweeper counters");
        assert_eq!(
            swept.result.records[0].get("rows_swept_total"),
            Some(&Value::UnsignedInteger(1))
        );
    }

    fn swept_total(runtime: &RedDBRuntime) -> Option<Value> {
        let swept = runtime
            .execute_query(
                "SELECT rows_swept_total FROM red.retention WHERE name = 'red.control_events'",
            )
            .expect("sweeper counters");
        swept.result.records[0].get("rows_swept_total").cloned()
    }

    /// A ledger written by `seed`, reopened with every row of it on disk.
    fn ledger_on_disk(
        name: &str,
        seed: impl FnOnce(&RedDBRuntime),
    ) -> (tempfile::TempDir, RedDBRuntime) {
        let directory = tempfile::tempdir().expect("ledger fixture");
        let options = crate::RedDBOptions::persistent(directory.path().join(name))
            .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
                .apply_control_events_retention()
                .expect("boot policy");
            seed(&runtime);
            runtime.flush().expect("persist the ledger");
        }
        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());
        (directory, runtime)
    }

    fn pass_in_progress(runtime: &RedDBRuntime) -> bool {
        runtime
            .inner
            .retention_sweeper
            .read()
            .pass_in_progress(CONTROL_EVENTS_COLLECTION)
    }

    /// The first pass after a start visits every position. The events here
    /// expire only once the window narrows, which leaves them to later passes.
    fn narrow_the_window_after_the_first_pass(runtime: &RedDBRuntime) {
        runtime.sweep_retention_tick(1_000);
        assert!(!pass_in_progress(runtime), "the first pass has ended");
        assert_eq!(swept_total(runtime), Some(Value::UnsignedInteger(0)));
        runtime
            .execute_query("SET CONFIG control_events.retention = '48h'")
            .expect("narrow the window");
    }

    #[test]
    fn a_pass_over_the_ledger_on_disk_ends_at_the_first_event_inside_the_window() {
        let (_directory, runtime) = ledger_on_disk("ledger.rdb", |runtime| {
            for n in 0..3 {
                insert_event(runtime, &format!("stale-{n}"), 3 * 86_400);
            }
            for n in 0..400 {
                insert_event(runtime, &format!("fresh-{n:03}"), 3_600);
            }
        });
        narrow_the_window_after_the_first_pass(&runtime);

        // Far fewer positions than the ledger holds.
        runtime.sweep_retention_tick(16);
        assert_eq!(swept_total(&runtime), Some(Value::UnsignedInteger(3)));
        assert!(
            !pass_in_progress(&runtime),
            "the first event inside the window ends the pass"
        );

        // The removals wait in the base for a checkpoint. They are not
        // candidates again, and the pass still ends at once.
        runtime.sweep_retention_tick(16);
        assert_eq!(swept_total(&runtime), Some(Value::UnsignedInteger(3)));
        assert!(!pass_in_progress(&runtime));
        assert_eq!(visible_ids(&runtime).len(), 400);
    }

    #[test]
    fn a_ledger_expired_on_disk_is_followed_into_memory() {
        let (_directory, runtime) = ledger_on_disk("ledger-expired.rdb", |runtime| {
            for n in 0..3 {
                insert_event(runtime, &format!("stale-{n}"), 3 * 86_400);
            }
        });
        narrow_the_window_after_the_first_pass(&runtime);
        insert_event(&runtime, "stale-resident", 3 * 86_400);
        insert_event(&runtime, "fresh-resident", 3_600);

        for _ in 0..4 {
            runtime.sweep_retention_tick(1_000);
        }
        assert_eq!(swept_total(&runtime), Some(Value::UnsignedInteger(4)));
        assert_eq!(visible_ids(&runtime), vec!["fresh-resident".to_string()]);
    }

    #[test]
    fn the_first_pass_after_a_start_reaches_an_expired_event_behind_a_newer_one() {
        let (_directory, runtime) = ledger_on_disk("ledger-unordered.rdb", |runtime| {
            insert_event(runtime, "fresh", 3_600);
            insert_event(runtime, "stale", 8 * 86_400);
        });

        runtime.sweep_retention_tick(1_000);
        assert_eq!(swept_total(&runtime), Some(Value::UnsignedInteger(1)));
        assert_eq!(visible_ids(&runtime), vec!["fresh".to_string()]);
    }

    fn ledger_entities(runtime: &RedDBRuntime) -> usize {
        runtime
            .db()
            .store()
            .get_collection(CONTROL_EVENTS_COLLECTION)
            .expect("ledger collection")
            .count()
    }

    #[test]
    fn an_event_already_removed_is_not_submitted_again() {
        let (_directory, runtime) = ledger_on_disk("ledger-resubmit.rdb", |runtime| {
            for n in 0..3 {
                insert_event(runtime, &format!("stale-{n}"), 3 * 86_400);
            }
            insert_event(runtime, "fresh", 3_600);
        });
        narrow_the_window_after_the_first_pass(&runtime);
        runtime.sweep_retention_tick(1_000);
        assert_eq!(swept_total(&runtime), Some(Value::UnsignedInteger(3)));

        // The three versions stay in the base until they are reclaimed. A pass
        // that submitted them again would remove nothing and be reported.
        for _ in 0..4 {
            runtime.sweep_retention_tick(1_000);
        }
        assert_eq!(swept_total(&runtime), Some(Value::UnsignedInteger(3)));
        assert!(!runtime
            .inner
            .retention_sweeper
            .read()
            .unremoved_reported(CONTROL_EVENTS_COLLECTION));
    }

    #[test]
    fn removed_events_are_reclaimed_although_a_vcs_commit_pins_history() {
        let (_directory, runtime) = ledger_on_disk("ledger-pinned.rdb", |runtime| {
            for n in 0..3 {
                insert_event(runtime, &format!("stale-{n}"), 8 * 86_400);
            }
            insert_event(runtime, "fresh", 3_600);
        });
        // A VCS commit pins the history of everything a commit can address.
        runtime
            .execute_query("CHECKPOINT 'pin history'")
            .expect("vcs commit");
        runtime.sweep_retention_tick(1_000);
        assert_eq!(swept_total(&runtime), Some(Value::UnsignedInteger(3)));
        let removed_logically = ledger_entities(&runtime);

        // Every collection takes its turn; the ledger's comes within these.
        for _ in 0..2_000 {
            runtime.try_reclaim_history_tick();
            if ledger_entities(&runtime) + 3 <= removed_logically {
                break;
            }
        }
        assert_eq!(
            ledger_entities(&runtime) + 3,
            removed_logically,
            "the removed events are still on disk"
        );
        assert_eq!(visible_ids(&runtime), vec!["fresh".to_string()]);
    }

    /// Marking an event removed changes it. A sweep over a large expired
    /// backlog changed more rows between two checkpoints than a delta takes.
    #[test]
    fn a_sweep_of_a_large_ledger_takes_a_share_of_each_checkpoint() {
        use crate::storage::unified::store::{
            MAINTENANCE_PACED_FROM_ROWS, MAINTENANCE_ROWS_PER_CHECKPOINT,
        };
        let share = MAINTENANCE_ROWS_PER_CHECKPOINT as u64;
        let (_directory, runtime) = ledger_on_disk("ledger-paced.rdb", |runtime| {
            for n in 0..MAINTENANCE_PACED_FROM_ROWS + 100 {
                insert_event(runtime, &format!("stale-{n}"), 8 * 86_400);
            }
            insert_event(runtime, "fresh", 3_600);
        });
        for _ in 0..40 {
            runtime.sweep_retention_tick(1_000);
        }
        assert_eq!(
            swept_total(&runtime),
            Some(Value::UnsignedInteger(share)),
            "the sweep did not stop at its share of the next checkpoint"
        );
        runtime.checkpoint().expect("checkpoint");
        for _ in 0..40 {
            runtime.sweep_retention_tick(1_000);
        }
        assert_eq!(
            swept_total(&runtime),
            Some(Value::UnsignedInteger(2 * share)),
            "the sweep did not go on after the checkpoint"
        );
    }

    #[test]
    fn set_config_override_narrows_the_window_at_runtime() {
        let runtime = runtime();
        runtime
            .apply_control_events_retention()
            .expect("boot policy");
        insert_event(&runtime, "fresh", 3_600);
        insert_event(&runtime, "three_days", 3 * 86_400);
        assert_eq!(visible_ids(&runtime).len(), 2);

        runtime
            .execute_query("SET CONFIG control_events.retention = '48h'")
            .expect("set retention");
        assert_eq!(
            retention_row(&runtime),
            Some(Value::UnsignedInteger(2 * DAY_MS))
        );
        assert_eq!(visible_ids(&runtime), vec!["fresh".to_string()]);

        let err = runtime
            .execute_query("SET CONFIG control_events.retention = 'forever'")
            .expect_err("invalid retention is rejected");
        assert!(err.to_string().contains(CONFIG_KEY), "{err}");
        assert_eq!(
            retention_row(&runtime),
            Some(Value::UnsignedInteger(2 * DAY_MS))
        );
    }

    #[test]
    fn off_keeps_every_event() {
        let runtime = runtime();
        runtime
            .execute_query("SET CONFIG control_events.retention = 'off'")
            .expect("disable retention");
        assert_eq!(
            runtime.apply_control_events_retention().expect("policy"),
            None
        );
        assert_eq!(retention_row(&runtime), Some(Value::Null));

        insert_event(&runtime, "fresh", 3_600);
        insert_event(&runtime, "ancient", 365 * 86_400);
        for _ in 0..8 {
            runtime.sweep_retention_tick(1_000);
        }
        assert_eq!(
            visible_ids(&runtime),
            vec!["ancient".to_string(), "fresh".to_string()]
        );
        assert_eq!(physical_ids(&runtime), 2);
    }
}