#[path = "common/harness.rs"]
mod harness;
use harness::TestHarness;
use libsql::Builder;
use macrame::schema::{ddl, migrations};
enum Justification {
Query {
label: &'static str,
sql: &'static str,
source: Option<(&'static str, &'static str)>,
},
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_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_annotations_label",
NoReader {
why: "nothing in the crate selects from analytics_annotations at all. \
The table is written by `write_analytics_annotations` and read \
only by callers, through their own connection.",
},
),
(
"idx_lc_tgt_active",
NoReader {
why: "no query in the crate seeks on target_id as a leading column. \
Every links_current predicate leads on source_id (the walk) or \
binds all three key columns (the guards); `Subgraph::in_adj` is \
built in Rust from the forward rows the walk already returned.",
},
),
];
async fn migrated(harness: &TestHarness) -> libsql::Connection {
let db = Builder::new_local(&harness.db_path).build().await.unwrap();
let conn = db.connect().unwrap();
migrations::run(&conn).await.unwrap();
conn
}
async fn plan_of(conn: &libsql::Connection, sql: &str) -> String {
let mut rows = conn
.query(&format!("EXPLAIN QUERY PLAN {sql}"), ())
.await
.unwrap();
let mut lines = Vec::new();
while let Some(r) = rows.next().await.unwrap() {
lines.push(r.get::<String>(3).unwrap());
}
lines.join(" | ")
}
#[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() {
let harness = TestHarness::new();
let conn = migrated(&harness).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}, planner chose: {plan}"
);
}
}
#[test]
fn the_unread_indices_are_the_two_already_known() {
let unread: Vec<&str> = REGISTRY
.iter()
.filter(|(_, j)| matches!(j, NoReader { .. }))
.map(|(n, _)| *n)
.collect();
let reasons = REGISTRY
.iter()
.filter_map(|(n, j)| match j {
NoReader { why } => Some(format!(" {n}: {why}")),
_ => None,
})
.collect::<Vec<_>>()
.join("\n");
assert_eq!(
unread,
vec!["idx_annotations_label", "idx_lc_tgt_active"],
"the set of indexes with no reader in the crate has changed. If one \
gained a reader, move it to a Query entry. If a new one lost its \
reader, that is an index write per insert buying nothing — see D-089.\
\nCurrently recorded as unread:\n{reasons}"
);
}
#[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"
);
}
}