use std::time::Instant;
use macrame::branch::BranchId;
use macrame::graph::{AttributeMode, EdgeAssertion, TraversalBuilder};
use macrame::temporal::{hydrate_attributes, AsOf};
use macrame::ConceptUpsert;
use macrame::Database;
const TS: &str = "2026-01-01T00:00:00.000000Z";
const FUTURE: &str = "2027-01-01T00:00:00.000000Z";
const RETIRED_AT: &str = "2026-06-01T00:00:00.000000Z";
const WRITES: usize = 400;
const WRITE_REPEATS: usize = 5;
const HOT_FOLD: &str = r#"
SELECT seq_id, table_name, entity_id, operation, payload, branch_id
FROM (
SELECT seq_id, table_name, entity_id, operation, payload, branch_id,
ROW_NUMBER() OVER (PARTITION BY table_name, entity_id, branch_id ORDER BY seq_id DESC) as rn
FROM transaction_log
WHERE recorded_at <= ?1
) WHERE rn = 1
"#;
const ANCHORED_HOT_FOLD: &str = r#"
SELECT seq_id, table_name, entity_id, operation, payload, branch_id
FROM (
SELECT seq_id, table_name, entity_id, operation, payload, branch_id,
ROW_NUMBER() OVER (PARTITION BY table_name, entity_id, branch_id ORDER BY seq_id DESC) as rn
FROM transaction_log
WHERE recorded_at <= ?1 AND seq_id > ?2
) WHERE rn = 1
"#;
const COLD_FOLD: &str = r#"
SELECT seq_id, table_name, entity_id, operation, payload, branch_id
FROM (
SELECT seq_id, table_name, entity_id, operation, payload, branch_id,
ROW_NUMBER() OVER (PARTITION BY table_name, entity_id, branch_id ORDER BY seq_id DESC) as rn
FROM (
SELECT seq_id, table_name, entity_id, operation, payload, recorded_at, branch_id FROM main.transaction_log
UNION ALL
SELECT seq_id, table_name, entity_id, operation, payload, recorded_at, branch_id FROM cold.transaction_log
) WHERE recorded_at <= ?1
) WHERE rn = 1
"#;
const OTHER_READERS: &[(&str, &str)] = &[
(
"the archive's log predicate (idx_txlog_time, idx_txlog_entity)",
"SELECT seq_id FROM transaction_log WHERE recorded_at < ?1 AND EXISTS ( \
SELECT 1 FROM transaction_log newer \
WHERE newer.entity_id = transaction_log.entity_id \
AND newer.branch_id = transaction_log.branch_id \
AND newer.seq_id > transaction_log.seq_id)",
),
(
"the hot log's newest stamp (idx_txlog_time)",
"SELECT MAX(recorded_at) FROM transaction_log",
),
(
"the reach guard's counts",
"SELECT COUNT(*), MIN(seq_id), MAX(seq_id), MIN(recorded_at) FROM transaction_log",
),
(
"the archive's branch arm",
"SELECT seq_id FROM transaction_log WHERE branch_id = ?1",
),
];
const WINNER: &str = "(table_name, entity_id, branch_id, seq_id DESC)";
const WALK_DEPTH: usize = 4;
const BOUNDS: &[usize] = &[25, 50, 75, 100];
const SHAPES: &[(&str, &str)] = &[
("C-4 as written", "(entity_id, branch_id)"),
(
"partition order",
"(table_name, entity_id, branch_id, seq_id)",
),
(
"partition order + recorded_at",
"(table_name, entity_id, branch_id, seq_id, recorded_at)",
),
(
"covering the fold",
"(table_name, entity_id, branch_id, seq_id, recorded_at, operation, payload)",
),
(
"recorded_at first",
"(recorded_at, table_name, entity_id, branch_id, seq_id)",
),
(
"partition order, seq_id DESC",
"(table_name, entity_id, branch_id, seq_id DESC)",
),
(
"covering, seq_id DESC",
"(table_name, entity_id, branch_id, seq_id DESC, recorded_at, operation, payload)",
),
];
struct Args {
entities: usize,
revisions: usize,
branches: usize,
iterations: usize,
arm: String,
}
fn args() -> Args {
let mut a = Args {
entities: 1_000,
revisions: 3,
branches: 3,
iterations: 9,
arm: "all".to_string(),
};
let argv: Vec<String> = std::env::args().collect();
let mut i = 1;
while i + 1 < argv.len() {
if argv[i] == "--arm" {
a.arm = argv[i + 1].clone();
i += 2;
continue;
}
let v = argv[i + 1]
.parse()
.unwrap_or_else(|_| panic!("bad {}", argv[i]));
match argv[i].as_str() {
"--entities" => a.entities = v,
"--revisions" => a.revisions = v,
"--branches" => a.branches = v,
"--iterations" => a.iterations = v,
other => panic!("unknown flag {other}"),
}
i += 2;
}
a
}
async fn populate(db: &Database, a: &Args) {
let mut lineages = vec![BranchId::main()];
for i in 1..a.branches {
let id = BranchId::new(format!("b{i}")).unwrap();
db.fork(id.clone(), BranchId::main()).await.unwrap();
lineages.push(id);
}
for rev in 0..a.revisions {
let mut concepts = Vec::with_capacity(a.entities * 2);
for e in 0..a.entities {
concepts
.push(ConceptUpsert::new(format!("n{e}"), format!("n rev {rev}")).valid_from(TS));
concepts
.push(ConceptUpsert::new(format!("m{e}"), format!("m rev {rev}")).valid_from(TS));
}
let written = db.write_concepts(concepts).await.unwrap();
assert_eq!(written, a.entities * 2);
}
let mut edges = Vec::with_capacity(a.entities);
for e in 0..a.entities {
edges.push(
EdgeAssertion::new(format!("n{e}"), format!("m{e}"), "LINKS")
.valid_from(TS)
.on_branch(lineages[e % lineages.len()].clone()),
);
}
let written = db.bulk_import(edges).await.unwrap();
assert_eq!(written, a.entities);
for e in (0..a.entities).step_by(2) {
let lineage = &lineages[e % lineages.len()];
db.retire_edge_on(
&format!("n{e}"),
&format!("m{e}"),
"LINKS",
TS,
RETIRED_AT,
lineage.clone(),
)
.await
.unwrap();
}
}
fn text(s: &str) -> libsql::Value {
libsql::Value::Text(s.to_string())
}
async fn used_pages(conn: &libsql::Connection) -> i64 {
scalar(conn, "PRAGMA page_count").await - scalar(conn, "PRAGMA freelist_count").await
}
async fn scalar(conn: &libsql::Connection, sql: &str) -> i64 {
let mut rows = conn.query(sql, ()).await.unwrap();
rows.next().await.unwrap().unwrap().get::<i64>(0).unwrap()
}
async fn plan(conn: &libsql::Connection, sql: &str, params: Vec<libsql::Value>) -> Vec<String> {
let mut rows = conn
.query(&format!("EXPLAIN QUERY PLAN {sql}"), params)
.await
.unwrap();
let mut out = Vec::new();
while let Some(row) = rows.next().await.unwrap() {
out.push(row.get::<String>(3).unwrap());
}
out
}
async fn time_sql(conn: &libsql::Connection, sql: &str, n: usize) -> (f64, f64) {
let mut best = f64::MAX;
let mut total = 0.0;
for _ in 0..n {
let t = Instant::now();
let mut rows = conn.query(sql, vec![text(FUTURE)]).await.unwrap();
let mut seen = 0usize;
while let Some(row) = rows.next().await.unwrap() {
let _: String = row.get(2).unwrap();
seen += 1;
}
let ms = t.elapsed().as_secs_f64() * 1e3;
assert!(seen > 0);
best = best.min(ms);
total += ms;
}
(best, total / n as f64)
}
async fn time_reconstruct(db: &Database, n: usize) -> (f64, f64) {
let mut best = f64::MAX;
let mut total = 0.0;
for _ in 0..n {
let t = Instant::now();
let state = db.reconstruct(FUTURE).await.unwrap();
let ms = t.elapsed().as_secs_f64() * 1e3;
assert!(!state.edges.is_empty());
best = best.min(ms);
total += ms;
}
(best, total / n as f64)
}
async fn time_writes(shape: Option<&str>, n: usize) -> f64 {
let dir = tempfile::tempdir().unwrap();
let db = Database::open_with_cadence(dir.path().join("w.db"), None)
.await
.unwrap();
if let Some(columns) = shape {
let conn = db.raw().connect().unwrap();
conn.execute(
&format!("CREATE INDEX idx_probe ON transaction_log {columns}"),
(),
)
.await
.unwrap();
}
let mut concepts = Vec::with_capacity(n * 2);
for i in 0..n {
concepts.push(ConceptUpsert::new(format!("w{i}"), "w").valid_from(TS));
concepts.push(ConceptUpsert::new(format!("x{i}"), "x").valid_from(TS));
}
db.write_concepts(concepts).await.unwrap();
let t = Instant::now();
for i in 0..n {
db.assert_edge(
EdgeAssertion::new(format!("w{i}"), format!("x{i}"), "LINKS").valid_from(TS),
)
.await
.unwrap();
}
let ms = t.elapsed().as_secs_f64() * 1e3;
db.close().await.unwrap();
ms
}
async fn best_writes(shape: Option<&str>, n: usize) -> f64 {
let mut best = f64::MAX;
for _ in 0..WRITE_REPEATS {
best = best.min(time_writes(shape, n).await);
}
best
}
async fn traversal_fixture(db: &Database, a: &Args) {
let chunk = (a.entities / a.revisions.max(1)).max(1);
for rev in 0..a.revisions {
let concepts: Vec<ConceptUpsert> = (0..a.entities)
.map(|e| ConceptUpsert::new(format!("n{e}"), format!("n rev {rev}")).valid_from(TS))
.collect();
db.write_concepts(concepts).await.unwrap();
let lo = rev * chunk;
let hi = ((rev + 1) * chunk).min(a.entities.saturating_sub(1));
let edges: Vec<EdgeAssertion> = (lo..hi)
.map(|e| {
EdgeAssertion::new(format!("n{e}"), format!("n{}", e + 1), "LINKS").valid_from(TS)
})
.collect();
if !edges.is_empty() {
db.bulk_import(edges).await.unwrap();
}
for e in lo..hi {
if e % 2 == 1 && e > WALK_DEPTH {
db.retire_edge_on(
&format!("n{e}"),
&format!("n{}", e + 1),
"LINKS",
TS,
RETIRED_AT,
BranchId::main(),
)
.await
.unwrap();
}
}
}
}
async fn bound_at(conn: &libsql::Connection, pct: usize) -> String {
let rows = scalar(conn, "SELECT COUNT(*) FROM transaction_log").await;
let offset = ((rows as usize * pct / 100).max(1) - 1).min(rows as usize - 1);
let mut r = conn
.query(
&format!(
"SELECT recorded_at FROM transaction_log ORDER BY seq_id LIMIT 1 OFFSET {offset}"
),
(),
)
.await
.unwrap();
r.next().await.unwrap().unwrap().get(0).unwrap()
}
async fn time_walk(conn: &libsql::Connection, at: &str, n: usize) -> (f64, f64) {
let walk = TraversalBuilder::new("n0")
.max_depth(WALK_DEPTH)
.as_of_recorded(at);
let mut best = f64::MAX;
let mut total = 0.0;
for _ in 0..n {
let t = Instant::now();
let ids = walk.execute_ids(conn, FUTURE).await.unwrap();
let ms = t.elapsed().as_secs_f64() * 1e3;
assert!(!ids.is_empty(), "the walk returned nothing at {at}");
best = best.min(ms);
total += ms;
}
(best, total / n as f64)
}
async fn time_hydrate(conn: &libsql::Connection, ids: &[String], at: &str, n: usize) -> (f64, f64) {
let as_of = AsOf::recorded_at(at);
let mut best = f64::MAX;
let mut total = 0.0;
for _ in 0..n {
let t = Instant::now();
let got = hydrate_attributes(conn, ids, &as_of, AttributeMode::AtTime)
.await
.unwrap();
let ms = t.elapsed().as_secs_f64() * 1e3;
assert!(!got.is_empty());
best = best.min(ms);
total += ms;
}
(best, total / n as f64)
}
async fn other_folds(a: &Args) {
let dir = tempfile::tempdir().unwrap();
let db = Database::open_with_cadence(dir.path().join("walk.db"), None)
.await
.unwrap();
traversal_fixture(&db, a).await;
db.analyze().await.unwrap();
let conn = db.raw().connect().unwrap();
let rows = scalar(&conn, "SELECT COUNT(*) FROM transaction_log").await;
let links = scalar(
&conn,
"SELECT COUNT(*) FROM transaction_log WHERE table_name = 'links'",
)
.await;
println!(
"\n== the other two folds: a chain of {} on one lineage ==",
a.entities
);
println!(" transaction_log: {rows} rows, {links} of them links\n");
let hydrated: Vec<String> = (0..=WALK_DEPTH).map(|e| format!("n{e}")).collect();
conn.execute("DROP INDEX idx_txlog_fold_partition", ())
.await
.unwrap();
for (state, index) in [
("without it (the v16 plan)", false),
("with it (v17)", true),
] {
if index {
conn.execute(
&format!("CREATE INDEX idx_txlog_fold_partition ON transaction_log {WINNER}"),
(),
)
.await
.unwrap();
}
conn.execute("ANALYZE", ()).await.unwrap();
println!(" {state}");
println!(
" {:<10} {:>9} {:>9} {:>9} {:>9}",
"bound", "walk best", "mean", "hydr best", "mean"
);
for pct in BOUNDS {
let at = bound_at(&conn, *pct).await;
let (wb, wm) = time_walk(&conn, &at, a.iterations).await;
let (hb, hm) = time_hydrate(&conn, &hydrated, &at, a.iterations).await;
println!(
" {:<10} {wb:9.3} {wm:9.3} {hb:9.3} {hm:9.3}",
format!("{pct}%")
);
}
let at = bound_at(&conn, 100).await;
let walk_sql = TraversalBuilder::new("n0")
.max_depth(WALK_DEPTH)
.as_of_recorded(&at)
.build_sql();
for step in plan(&conn, &walk_sql, Vec::new()).await {
if step.contains("transaction_log")
|| step.contains("links_at_tx")
|| step.contains("B-TREE")
{
println!(" walk {step}");
}
}
let hydrate_sql = "SELECT entity_id, seq_id, payload FROM ( \
SELECT entity_id, seq_id, payload, \
ROW_NUMBER() OVER (PARTITION BY entity_id ORDER BY seq_id DESC) as rn \
FROM transaction_log \
WHERE table_name = 'concepts' AND recorded_at <= ?1 \
AND entity_id IN ('n0','n1','n2','n3','n4')) WHERE rn = 1";
for step in plan(&conn, hydrate_sql, vec![text(&at)]).await {
println!(" hydrate {step}");
}
if index {
conn.execute("DROP INDEX idx_txlog_fold_partition", ())
.await
.unwrap();
}
}
db.close().await.unwrap();
}
#[tokio::main]
async fn main() {
let a = args();
if a.arm == "other-folds" {
other_folds(&a).await;
return;
}
let dir = tempfile::tempdir().unwrap();
let db = Database::open_with_cadence(dir.path().join("probe.db"), None)
.await
.unwrap();
println!(
"fixture: {} entities x {} revisions on {} lineages",
a.entities, a.revisions, a.branches
);
populate(&db, &a).await;
db.analyze().await.unwrap();
let conn = db.raw().connect().unwrap();
conn.execute("DROP INDEX IF EXISTS idx_txlog_fold_partition", ())
.await
.unwrap();
let rows = scalar(&conn, "SELECT COUNT(*) FROM transaction_log").await;
let parts = scalar(
&conn,
"SELECT COUNT(*) FROM (SELECT 1 FROM transaction_log \
GROUP BY table_name, entity_id, branch_id)",
)
.await;
println!(
" transaction_log: {rows} rows, {parts} partitions, {:.1} rows per partition\n",
rows as f64 / parts as f64
);
println!("== the plan today ==");
for (label, sql, params) in [
("hot fold", HOT_FOLD, vec![text(FUTURE)]),
(
"anchored hot fold",
ANCHORED_HOT_FOLD,
vec![text(FUTURE), libsql::Value::Integer(0)],
),
] {
println!(" {label}");
for step in plan(&conn, sql, params).await {
println!(" {step}");
}
}
println!(
"\n== ms over {} runs: the fold's SQL alone, then reconstruct() end to end ==",
a.iterations
);
println!(
" {:<32} {:>8} {:>8} {:>8} {:>8} {:>8}",
"", "sql best", "mean", "e2e best", "mean", "size"
);
let (sb, sm) = time_sql(&conn, HOT_FOLD, a.iterations).await;
let (rb, rm) = time_reconstruct(&db, a.iterations).await;
let base_pages = used_pages(&conn).await;
println!(
" {:<32} {sb:8.3} {sm:8.3} {rb:8.3} {rm:8.3} {base_pages:5} pages",
"no index (today)"
);
for (label, columns) in SHAPES {
conn.execute(
&format!("CREATE INDEX idx_probe ON transaction_log {columns}"),
(),
)
.await
.unwrap();
conn.execute("ANALYZE", ()).await.unwrap();
let (sb, sm) = time_sql(&conn, HOT_FOLD, a.iterations).await;
let (rb, rm) = time_reconstruct(&db, a.iterations).await;
let pages = used_pages(&conn).await;
println!(
" {label:<32} {sb:8.3} {sm:8.3} {rb:8.3} {rm:8.3} {:+5.1}%",
(pages - base_pages) as f64 / base_pages as f64 * 100.0
);
for step in plan(&conn, HOT_FOLD, vec![text(FUTURE)]).await {
println!(" {step}");
}
conn.execute("DROP INDEX idx_probe", ()).await.unwrap();
conn.execute("ANALYZE", ()).await.unwrap();
}
println!("\n== what else reads the log, before and after ==");
for (label, sql) in OTHER_READERS {
println!(" {label}");
for step in plan(&conn, sql, vec![text(FUTURE)]).await {
println!(" before {step}");
}
conn.execute(
&format!("CREATE INDEX idx_probe ON transaction_log {WINNER}"),
(),
)
.await
.unwrap();
conn.execute("ANALYZE", ()).await.unwrap();
for step in plan(&conn, sql, vec![text(FUTURE)]).await {
println!(" after {step}");
}
conn.execute("DROP INDEX idx_probe", ()).await.unwrap();
conn.execute("ANALYZE", ()).await.unwrap();
}
println!("\n== the cold fold, once the ledger has been archived ==");
let cold_path = dir.path().join("cold.db");
conn.execute(
&format!("ATTACH DATABASE '{}' AS cold", cold_path.display()),
(),
)
.await
.unwrap();
conn.execute(
"CREATE TABLE IF NOT EXISTS cold.transaction_log ( seq_id INTEGER PRIMARY KEY, table_name TEXT NOT NULL, entity_id TEXT NOT NULL, operation TEXT NOT NULL, payload TEXT NOT NULL, recorded_at TEXT NOT NULL, branch_id TEXT NOT NULL DEFAULT 'main')",
(),
)
.await
.unwrap();
conn.execute(
"INSERT INTO cold.transaction_log SELECT seq_id, table_name, entity_id, operation, payload, recorded_at, branch_id FROM main.transaction_log",
(),
)
.await
.unwrap();
for (label, hot, cold) in [
("neither side indexed", false, false),
("hot only (what the rung would ship)", true, false),
("both sides indexed", true, true),
] {
if hot {
conn.execute(
&format!("CREATE INDEX IF NOT EXISTS main.idx_probe ON transaction_log {WINNER}"),
(),
)
.await
.unwrap();
}
if cold {
conn.execute(
&format!(
"CREATE INDEX IF NOT EXISTS cold.idx_probe_cold ON transaction_log {WINNER}"
),
(),
)
.await
.unwrap();
}
conn.execute("ANALYZE", ()).await.unwrap();
println!(" {label}");
for step in plan(&conn, COLD_FOLD, vec![text(FUTURE)]).await {
println!(" {step}");
}
let (sb, sm) = time_sql(&conn, COLD_FOLD, a.iterations).await;
println!(" {sb:8.3} best {sm:8.3} mean");
conn.execute("DROP INDEX IF EXISTS idx_probe", ())
.await
.unwrap();
conn.execute("DROP INDEX IF EXISTS cold.idx_probe_cold", ())
.await
.unwrap();
}
conn.execute("DETACH DATABASE cold", ()).await.unwrap();
println!("\n== the write side: {WRITES} assertions on a fresh database, ms ==");
println!(" {:<32} {:>8} {:>8}", "", "no index", "with");
for (label, columns) in SHAPES {
let base = best_writes(None, WRITES).await;
let with_index = best_writes(Some(columns), WRITES).await;
println!(
" {label:<32} {base:8.1} {with_index:8.1} {:+.1}%",
(with_index - base) / base * 100.0
);
}
other_folds(&a).await;
db.close().await.unwrap();
}