#[path = "common/harness.rs"]
mod harness;
#[path = "common/plan_fixture.rs"]
mod plan_fixture;
use harness::TestHarness;
use macrame::schema::ddl;
use plan_fixture::{assert_has_statistics, migrated, plan_of, populated_and_analysed};
enum Justification {
Query {
label: &'static str,
sql: &'static str,
source: Option<(&'static str, &'static str)>,
},
#[allow(dead_code)]
NoReader { why: &'static str },
}
use Justification::{NoReader, Query};
const REGISTRY: &[(&str, Justification)] = &[
(
"idx_lc_traversal_cover",
Query {
label: "the traversal CTE's recursive step",
sql: "SELECT l.target_id FROM links_current l WHERE l.source_id = ?1 \
AND l.valid_from <= ?3 AND ?3 < l.valid_to AND l.weight >= ?4",
source: None,
},
),
(
"idx_lc_open_interval",
Query {
label: "the overlap guard and the single-open probe",
sql: "SELECT valid_from, valid_to FROM links_current \
WHERE source_id = ?1 AND target_id = ?2 AND edge_type = ?3 \
AND valid_from <> ?4",
source: None,
},
),
(
"idx_lc_lineage_cut",
Query {
label: "the lineage read's two base scans over the projection",
sql: "SELECT source_id, target_id, edge_type, valid_from, valid_to, weight \
FROM links_current WHERE branch_id = ?1 AND recorded_at > ?2",
source: Some((
include_str!("../src/graph/lineage.rs"),
"WHERE g.cutoff IS NOT NULL AND lc.recorded_at > g.cutoff",
)),
},
),
(
"idx_txlog_time",
Query {
label: "the fold's recorded_at window",
sql: "SELECT seq_id, table_name, entity_id, operation, payload \
FROM transaction_log WHERE recorded_at <= ?1",
source: Some((
include_str!("../src/temporal/replay.rs"),
"FROM transaction_log\n WHERE recorded_at <= ?1",
)),
},
),
(
"idx_txlog_entity",
Query {
label: "the archive's supersession test",
sql: "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.seq_id > transaction_log.seq_id)",
source: Some((
include_str!("../src/temporal/archive.rs"),
"newer.entity_id = transaction_log.entity_id",
)),
},
),
(
"idx_links_recorded_at",
Query {
label: "the archive cutoff on the links ledger",
sql: "SELECT source_id, target_id FROM links WHERE recorded_at < ?1 AND ( \
EXISTS ( \
SELECT 1 FROM links newer \
WHERE newer.source_id = links.source_id \
AND newer.target_id = links.target_id \
AND newer.edge_type = links.edge_type \
AND newer.valid_from = links.valid_from \
AND newer.recorded_at > links.recorded_at) \
OR (valid_to <> '9999-12-31T23:59:59.999999Z' AND valid_to <= ?1))",
source: Some((
include_str!("../src/temporal/archive.rs"),
"recorded_at < :cutoff AND (",
)),
},
),
(
"idx_links_target",
Query {
label: "the concept-archival reverse-reachability arm",
sql: "SELECT id FROM concepts WHERE retired = 1 AND recorded_at < ?1 \
AND valid_to < ?1 AND NOT EXISTS ( \
SELECT 1 FROM links WHERE links.source_id = concepts.id \
OR links.target_id = concepts.id)",
source: Some((
include_str!("../src/temporal/archive.rs"),
"OR links.target_id = concepts.id",
)),
},
),
];
#[test]
fn every_index_is_justified() {
let declared: Vec<String> = ddl::CREATE_INDICES
.iter()
.map(|sql| {
let after = sql.split("IF NOT EXISTS ").nth(1).expect("index DDL shape");
after.split_whitespace().next().unwrap().to_string()
})
.collect();
for name in &declared {
assert!(
REGISTRY.iter().any(|(n, _)| n == name),
"{name} is declared in ddl::CREATE_INDICES and has no registry entry. \
State the query that seeks on it, or record it as NoReader — see D-089."
);
}
for (name, _) in REGISTRY {
assert!(
declared.iter().any(|d| d == name),
"{name} is in the registry and no longer declared; drop the entry"
);
}
assert_eq!(declared.len(), REGISTRY.len());
}
#[tokio::test]
async fn every_justified_index_is_the_one_the_planner_picks_with_statistics() {
let harness = TestHarness::new();
let conn = populated_and_analysed(&harness.db_path).await;
assert_has_statistics(&conn).await;
for (name, j) in REGISTRY {
let Query { label, sql, .. } = j else {
continue;
};
let plan = plan_of(&conn, sql).await;
assert!(
plan.contains(name),
"{label}: expected {name} on a populated, analysed database — \
planner chose: {plan}"
);
}
}
const QUERY_REGISTRY: &[(&str, &str, Expect)] = &[
(
"the concept-archival predicate's link check",
"SELECT id FROM concepts WHERE retired = 1 AND recorded_at < ?1 AND valid_to < ?1 AND NOT EXISTS ( SELECT 1 FROM links WHERE links.source_id = concepts.id OR links.target_id = concepts.id)",
Expect {
fragment: "MULTI-INDEX OR",
note: "Review §2.2, closed in 0.12.6 by `idx_links_target`. If this reverts to a bare `SCAN links` inside the subquery, concept archival is O(concepts × links) again.",
},
),
(
"the link-archival supersession probe",
"SELECT rowid FROM links WHERE recorded_at < ?1 AND EXISTS ( SELECT 1 FROM links newer WHERE newer.source_id = links.source_id AND newer.target_id = links.target_id AND newer.edge_type = links.edge_type AND newer.valid_from = links.valid_from AND newer.recorded_at > links.recorded_at)",
Expect {
fragment: "SEARCH links USING INDEX idx_links_recorded_at",
note: "Review §2.1, closed in 0.12.6 by `idx_links_recorded_at`. The outer `recorded_at <` filter used to scan every row of `links`; it now seeks. The inner probe was always served by the primary key and was never the problem.",
},
),
(
"the clock floor read on every open()",
"SELECT MAX(recorded_at) FROM ( SELECT MAX(recorded_at) AS recorded_at FROM concepts UNION ALL SELECT MAX(recorded_at) AS recorded_at FROM links)",
Expect {
fragment: "SEARCH links USING COVERING INDEX",
note: "Served from a covering index before and after W3.1 — no traversal of the table either way. Contradicts review §2.1's claim that this is a full scan closed by `idx_links_recorded_at`; that index is justified on the archive path alone (D-150, D-151).",
},
),
];
struct Expect {
fragment: &'static str,
note: &'static str,
}
#[tokio::test]
async fn every_registered_query_gets_the_plan_it_is_recorded_as_getting() {
let harness = TestHarness::new();
let conn = populated_and_analysed(&harness.db_path).await;
for (label, sql, expect) in QUERY_REGISTRY {
let plan = plan_of(&conn, sql).await;
assert!(
plan.contains(expect.fragment),
"{label}: expected the plan to contain {:?}
note: {}
planner chose: {plan}
If an index you just added changed this, that is the point of this test — update the entry and say what the new plan is.",
expect.fragment,
expect.note
);
}
}
#[tokio::test]
async fn every_justified_index_is_the_one_the_planner_picks_when_empty() {
let harness = TestHarness::new();
let conn = migrated(&harness.db_path).await;
for (name, j) in REGISTRY {
let Query { label, sql, .. } = j else {
continue;
};
let plan = plan_of(&conn, sql).await;
assert!(
plan.contains(name),
"{label}: expected {name} on an empty database — planner chose: {plan}"
);
}
}
#[test]
fn the_unread_index_set_is_empty() {
let unread: Vec<String> = REGISTRY
.iter()
.filter_map(|(n, j)| match j {
NoReader { why } => Some(format!(" {n}: {why}")),
_ => None,
})
.collect();
assert!(
unread.is_empty(),
"an index in `ddl::CREATE_INDICES` has no reader in the crate. That is \
an index write on every insert into its table, forever, buying nothing \
— and one of the two v8 removed was on the hottest write path (D-089). \
Either name the query that seeks on it, or drop it in a rung.\
\nUnread:\n{}",
unread.join("\n")
);
assert!(
REGISTRY.len() >= 4,
"the registry has shrunk to {} entries; an empty unread set means \
nothing if there is nothing to be unread",
REGISTRY.len()
);
}
#[test]
fn every_reproduced_query_still_exists_in_its_source() {
for (name, j) in REGISTRY {
let Query {
source: Some((text, fragment)),
..
} = j
else {
continue;
};
let flat = |s: &str| s.split_whitespace().collect::<Vec<_>>().join(" ");
assert!(
flat(text).contains(&flat(fragment)),
"{name}: the source no longer contains {fragment:?}, so the query \
this file explains is a query nobody runs"
);
}
}