reddb-io-server 1.45.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
//! File-backed commit diagnostic. Run in release with `persistent_commit_matrix -- --ignored --nocapture`.

use crate::api::DurabilityMode;
use crate::runtime::mvcc::{clear_current_connection_id, set_current_connection_id};
use crate::{RedDBOptions, RedDBRuntime};
use reddb_types::Value;
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Barrier, OnceLock};
use std::time::Instant;

const CRASH_EXIT: i32 = 72;
const CASE_PATH: &str = "REDDB_COMMIT_BENCH_CASE_PATH";
const OPERATIONS: &str = "REDDB_COMMIT_BENCH_OPERATIONS";
const CASE_FILTER: &str = "REDDB_COMMIT_BENCH_CASE";
const REPORT: &str = "REDDB_COMMIT_BENCH_REPORT";
const LEGACY_UPDATES_ENV: &str = "REDDB_COMMIT_BENCH_LEGACY_UPDATES";
const SERIAL_POINT_UPDATES_ENV: &str = "REDDB_COMMIT_BENCH_SERIAL_POINT_UPDATES";
const SEED_ROWS: usize = 64;
const TEST_NAME: &str = "storage::unified::store::commit_bench::persistent_commit_matrix";

#[derive(Default, Serialize)]
pub(super) struct Probe {
    pub wal_syncs: AtomicU64,
    pub wal_sync_ns: AtomicU64,
    pub wal_waiters: AtomicU64,
    pub wal_wait_ns: AtomicU64,
    pub wal_wakes: AtomicU64,
    pub wal_empty_wakes: AtomicU64,
    pub row_requests: AtomicU64,
    pub row_groups: AtomicU64,
    pub row_queue_ns: AtomicU64,
    pub row_wakes: AtomicU64,
    pub row_empty_wakes: AtomicU64,
}

static PROBE: OnceLock<Probe> = OnceLock::new();
static LEGACY_UPDATES: AtomicBool = AtomicBool::new(false);
pub(super) static SERIAL_POINT_UPDATES: AtomicBool = AtomicBool::new(false);

pub(super) fn legacy_updates() -> bool {
    LEGACY_UPDATES.load(Ordering::Relaxed)
}

pub(super) fn probe() -> Option<&'static Probe> {
    PROBE.get()
}

pub(super) fn add_elapsed(counter: &AtomicU64, start: Instant) {
    let elapsed = u64::try_from(start.elapsed().as_nanos()).expect("diagnostic duration fits u64");
    counter.fetch_add(elapsed, Ordering::Relaxed);
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
struct Case {
    writers: usize,
    shared_key: bool,
    independent_tables: bool,
    operations: usize,
}

impl Case {
    fn label(self) -> String {
        let keys = if self.independent_tables {
            "tables"
        } else if self.shared_key {
            "shared"
        } else {
            "separate"
        };
        format!("{}-{keys}", self.writers)
    }

    fn table_count(self) -> usize {
        if self.independent_tables {
            self.writers
        } else {
            1
        }
    }

    fn table_name(self, key: usize) -> String {
        if self.independent_tables {
            format!("counters_{}", key % self.writers)
        } else {
            "counters".to_string()
        }
    }
}

#[derive(Deserialize, Serialize)]
struct Measurement {
    case: Case,
    legacy_updates: bool,
    serial_point_updates: bool,
    window_us: u64,
    acknowledged_per_key: Vec<usize>,
    elapsed_ns: u64,
    operation_ns: Vec<u64>,
    wal_syncs_total: u64,
    wal_bytes_before_exit: u64,
    probe: serde_json::Value,
}

fn open(path: &Path) -> RedDBRuntime {
    let runtime = RedDBRuntime::with_options(
        RedDBOptions::persistent(path)
            .with_durability_mode(DurabilityMode::WalDurableGrouped)
            .with_auto_checkpoint(0)
            .with_bounded_disk_residency(true)
            .with_memory_budget(1 << 30),
    )
    .expect("open file-backed runtime");
    assert!(runtime.stats().paged_mode);
    runtime
}

fn child(case_path: &Path) -> ! {
    LEGACY_UPDATES.store(
        std::env::var(LEGACY_UPDATES_ENV).is_ok_and(|value| value == "1"),
        Ordering::Relaxed,
    );
    SERIAL_POINT_UPDATES.store(
        std::env::var(SERIAL_POINT_UPDATES_ENV).is_ok_and(|value| value == "1"),
        Ordering::Relaxed,
    );
    let case: Case = serde_json::from_slice(
        &std::fs::read(case_path.join("case.json")).expect("read case configuration"),
    )
    .expect("parse case configuration");
    let path = case_path.join("data.rdb");
    let runtime = open(&path);
    for table in 0..case.table_count() {
        let name = case.table_name(table);
        runtime
            .execute_query(&format!(
                "CREATE TABLE {name} (id INTEGER PRIMARY KEY, n INTEGER)"
            ))
            .expect("create counters");
        let rows = (table..SEED_ROWS)
            .step_by(case.table_count())
            .map(|id| format!("({id}, 0)"))
            .collect::<Vec<_>>();
        runtime
            .execute_query(&format!(
                "INSERT INTO {name} (id, n) VALUES {}",
                rows.join(",")
            ))
            .expect("seed counters");
    }
    runtime.checkpoint().expect("checkpoint fixture");
    let store = runtime.db().store();
    let coordinator = store.commit.as_ref().expect("active main WAL coordinator");
    let initial_syncs = coordinator.fsync_count();
    let probe = PROBE.get_or_init(Probe::default);
    let ready = Barrier::new(case.writers + 1);
    let mut acknowledged_per_key = vec![0; SEED_ROWS];
    let mut operation_ns = Vec::with_capacity(case.operations);
    let elapsed_ns = std::thread::scope(|scope| {
        let threads = (0..case.writers)
            .map(|writer| {
                let runtime = &runtime;
                let ready = &ready;
                scope.spawn(move || {
                    set_current_connection_id(20_000 + writer as u64);
                    let id = if case.shared_key { 0 } else { writer };
                    let name = case.table_name(id);
                    let sql = format!("UPDATE {name} SET n = n + 1 WHERE id = {id}");
                    let mut samples = Vec::with_capacity(case.operations.div_ceil(case.writers));
                    ready.wait();
                    for _ in (writer..case.operations).step_by(case.writers) {
                        let start = Instant::now();
                        let reply = runtime.execute_query(&sql).expect("update counter");
                        assert_eq!(reply.affected_rows, 1);
                        samples.push(
                            u64::try_from(start.elapsed().as_nanos()).expect("sample fits u64"),
                        );
                    }
                    clear_current_connection_id();
                    (id, samples)
                })
            })
            .collect::<Vec<_>>();
        let start = Instant::now();
        ready.wait();
        for thread in threads {
            let (id, mut samples) = thread.join().expect("workload writer");
            acknowledged_per_key[id] += samples.len();
            operation_ns.append(&mut samples);
        }
        u64::try_from(start.elapsed().as_nanos()).expect("workload duration fits u64")
    });
    assert_eq!(operation_ns.len(), case.operations);
    let measurement = Measurement {
        case,
        legacy_updates: legacy_updates(),
        serial_point_updates: SERIAL_POINT_UPDATES.load(Ordering::Relaxed),
        window_us: u64::try_from(
            super::commit::StoreCommitCoordinator::resolve_window(&store.config.group_commit)
                .as_micros(),
        )
        .expect("diagnostic window fits u64"),
        acknowledged_per_key,
        elapsed_ns,
        operation_ns,
        wal_syncs_total: coordinator.fsync_count() - initial_syncs,
        wal_bytes_before_exit: std::fs::metadata(reddb_file::layout::unified_wal_path(&path))
            .expect("locate persisted WAL")
            .len(),
        probe: serde_json::to_value(probe).expect("encode probe counters"),
    };
    std::fs::write(
        case_path.join("measurement.json"),
        serde_json::to_vec(&measurement).expect("encode measurement"),
    )
    .expect("save acknowledged operations and metrics");
    // Simulate abrupt process exit without database destructors or a closing checkpoint.
    std::process::exit(CRASH_EXIT);
}

fn verify(runtime: &RedDBRuntime, case: Case, expected: &[usize]) {
    for table in 0..case.table_count() {
        let name = case.table_name(table);
        let result = runtime
            .execute_query(&format!("SELECT id, n FROM {name} ORDER BY id"))
            .expect("read recovered counters");
        let expected = expected
            .iter()
            .enumerate()
            .skip(table)
            .step_by(case.table_count());
        let rows = &result.result.records;
        assert_eq!(rows.len(), expected.len());
        for (record, (id, n)) in rows.iter().zip(expected) {
            let integer = |name| match record.get(name) {
                Some(Value::UnsignedInteger(n)) => usize::try_from(*n).expect("counter fits usize"),
                Some(Value::Integer(n)) => usize::try_from(*n).expect("counter is nonnegative"),
                other => panic!("expected integer {name}, got {other:?}"),
            };
            assert_eq!((integer("id"), integer("n")), (id, *n));
        }
    }
}

#[test]
#[ignore = "release diagnostic with 46,000 durable commits per workload"]
fn persistent_commit_matrix() {
    if let Some(case_path) = std::env::var_os(CASE_PATH) {
        child(Path::new(&case_path));
    }
    let operations = std::env::var(OPERATIONS)
        .map(|value| value.parse().expect("positive diagnostic operation count"))
        .unwrap_or(46_000);
    assert!(operations > 0);
    let filter = std::env::var(CASE_FILTER).ok();
    let report = std::env::var_os(REPORT);
    let mut measurements = Vec::new();
    let directory = tempfile::tempdir().expect("commit benchmark workspace");
    for writers in [1, 8, 32, 64] {
        for (shared_key, independent_tables) in [(false, false), (true, false), (false, true)] {
            // With one writer, one key and one table are enough.
            if writers == 1 && (shared_key || independent_tables) {
                continue;
            }
            let case = Case {
                writers,
                shared_key,
                independent_tables,
                operations,
            };
            let label = case.label();
            if filter.as_ref().is_some_and(|selected| selected != &label) {
                continue;
            }
            println!("commit diagnostic starting {label}");
            let folder = directory.path().join(&label);
            std::fs::create_dir(&folder).expect("create case directory");
            std::fs::write(
                folder.join("case.json"),
                serde_json::to_vec(&case).expect("encode case"),
            )
            .expect("save case configuration");
            let status =
                std::process::Command::new(std::env::current_exe().expect("test executable"))
                    .args(["--exact", TEST_NAME, "--ignored", "--nocapture"])
                    .env(CASE_PATH, &folder)
                    .env("REDDB_RUNTIME_RESULT_CACHE_ENABLED", "false")
                    .status()
                    .expect("run durable workload child");
            assert_eq!(
                status.code(),
                Some(CRASH_EXIT),
                "{label} child did not reach abrupt exit"
            );
            let sample: Measurement = serde_json::from_slice(
                &std::fs::read(folder.join("measurement.json")).expect("read measurement"),
            )
            .expect("parse measurement");
            assert_eq!(
                sample.acknowledged_per_key.iter().sum::<usize>(),
                operations
            );
            assert!(sample.wal_syncs_total > 0 && sample.wal_bytes_before_exit > 8);
            let path = folder.join("data.rdb");
            let recovered = open(&path);
            verify(&recovered, case, &sample.acknowledged_per_key);
            recovered
                .checkpoint()
                .expect("checkpoint restored counters");
            drop(recovered);
            verify(&open(&path), case, &sample.acknowledged_per_key);
            println!("commit diagnostic verified {label} after exit and reopen");
            measurements.push(sample);
            if let Some(report) = &report {
                std::fs::write(
                    report,
                    serde_json::to_vec(&measurements).expect("encode report"),
                )
                .expect("save recovered cases");
            }
        }
    }
    assert!(!measurements.is_empty(), "select an existing case");
}