use super::super::index_store::IndexStore;
use super::*;
use crate::storage::unified::hash_index::HashCandidates;
thread_local! {
pub(crate) static EXPRESSION_RESIDUAL_READS: std::cell::Cell<u64> =
const { std::cell::Cell::new(0) };
}
const PURE_SCALAR_FUNCTIONS: &[&str] = &[
"ABS",
"CEIL",
"CHARACTER_LENGTH",
"CHAR_LENGTH",
"COALESCE",
"CONCAT",
"FLOOR",
"LEFT",
"LENGTH",
"LOWER",
"LTRIM",
"OCTET_LENGTH",
"RIGHT",
"ROUND",
"RTRIM",
"SUBSTR",
"SUBSTRING",
"TRIM",
"UPPER",
];
pub(super) fn pure_scalar_expr(expr: &Expr) -> bool {
match expr {
Expr::Literal { .. } | Expr::Column { .. } | Expr::Parameter { .. } => true,
Expr::BinaryOp { lhs, rhs, .. } => pure_scalar_expr(lhs) && pure_scalar_expr(rhs),
Expr::UnaryOp { operand, .. }
| Expr::IsNull { operand, .. }
| Expr::Cast { inner: operand, .. } => pure_scalar_expr(operand),
Expr::InList { target, values, .. } => {
pure_scalar_expr(target) && values.iter().all(pure_scalar_expr)
}
Expr::Between {
target, low, high, ..
} => pure_scalar_expr(target) && pure_scalar_expr(low) && pure_scalar_expr(high),
Expr::Case {
branches, else_, ..
} => {
branches
.iter()
.all(|(condition, value)| pure_scalar_expr(condition) && pure_scalar_expr(value))
&& else_.as_deref().is_none_or(pure_scalar_expr)
}
Expr::FunctionCall { name, args, .. } => {
PURE_SCALAR_FUNCTIONS
.iter()
.any(|pure| name.eq_ignore_ascii_case(pure))
&& args.iter().all(pure_scalar_expr)
}
Expr::Subquery { .. } | Expr::WindowFunctionCall { .. } => false,
}
}
fn conjuncts(filter: &Filter) -> Vec<&Filter> {
let mut pending = vec![filter];
let mut leaves = Vec::new();
while let Some(filter) = pending.pop() {
match filter {
Filter::And(left, right) => {
pending.push(right);
pending.push(left);
}
other => leaves.push(other),
}
}
leaves
}
fn names_indexed_column(filter: &Filter, indexed: &std::collections::HashSet<String>) -> bool {
match filter {
Filter::Compare { field, .. }
| Filter::IsNull(field)
| Filter::IsNotNull(field)
| Filter::In { field, .. }
| Filter::Between { field, .. }
| Filter::Like { field, .. }
| Filter::StartsWith { field, .. }
| Filter::EndsWith { field, .. }
| Filter::Contains { field, .. } => {
matches!(field, FieldRef::TableColumn { column, .. } if indexed.contains(column))
}
_ => false,
}
}
pub(super) fn lookup_filter(filter: &Filter, table: &str, store: &IndexStore) -> Option<Filter> {
let mut plain = Vec::new();
let mut expressions = false;
for conjunct in conjuncts(filter) {
match conjunct {
Filter::CompareExpr { lhs, rhs, .. } => {
if !pure_scalar_expr(lhs) || !pure_scalar_expr(rhs) {
return None;
}
expressions = true;
}
_ if expressions || super::table::runtime_filter_contains_compare_expr(conjunct) => {
return None;
}
_ => plain.push(conjunct),
}
}
if !expressions {
return None;
}
let indexed = store.indexed_columns_set(table);
if !plain
.iter()
.any(|conjunct| names_indexed_column(conjunct, &indexed))
{
return None;
}
plain
.into_iter()
.cloned()
.reduce(|left, right| Filter::And(Box::new(left), Box::new(right)))
}
pub(super) fn candidates(
lookup: &Filter,
table: &str,
store: &IndexStore,
) -> RedDBResult<Option<HashCandidates>> {
let mut ids = store.paged_btree_lookup_for_query(table, lookup, &[])?.0;
if ids.is_none() {
ids = super::indexed_scan::try_sorted_index_lookup(lookup, table, store, None)?;
}
if ids.is_none() {
if let Some((column, key)) = super::helpers::extract_index_candidate(lookup) {
if let Some(index) = store.find_hash_index_for_column(table, &column) {
let found = store
.hash_lookup(table, index.hash_lookup_name().as_ref(), &key)
.map_err(|error| {
RedDBError::Internal(format!("hash index lookup failed: {error}"))
})?;
ids = (!found.is_empty()).then_some(found);
}
}
}
if std::env::var("REDDB_INDEX_TRACE").as_deref() == Ok("1") {
eprintln!(
"expression_residual_lookup table={table} filter={lookup:?} candidates={:?}",
ids.as_ref().map(|ids| ids.len())
);
}
if ids.is_some() {
EXPRESSION_RESIDUAL_READS.with(|reads| reads.set(reads.get() + 1));
}
Ok(ids)
}
#[cfg(test)]
mod tests {
use super::EXPRESSION_RESIDUAL_READS;
use crate::{RedDBOptions, RedDBRuntime};
use reddb_types::Value;
const BASE: &str = "environment = 'stg' AND park_id = 'p1' \
AND completed_at IS NULL AND streamed_at IS NOT NULL";
#[derive(Clone, Copy, Debug, PartialEq)]
enum Path {
Indexed,
Old,
Any,
}
struct Case {
sql: String,
params: Vec<Value>,
path: Path,
}
fn case(sql: &str, path: Path) -> Case {
Case {
sql: sql.replace("{base}", BASE),
params: Vec::new(),
path,
}
}
fn cases() -> Vec<Case> {
use Path::{Any, Indexed, Old};
let mut cases = vec![
case("SELECT * FROM {t} WHERE {base}", Any),
case(
"SELECT * FROM {t} WHERE {base} AND reconcile_after IS NULL",
Any,
),
case(
"SELECT * FROM {t} WHERE {base} \
AND COALESCE(reconcile_after, '') <= '2026-11-15T00:00:00Z'",
Indexed,
),
case(
"SELECT * FROM {t} WHERE {base} AND COALESCE(reconcile_after, '') = ''",
Indexed,
),
case(
"SELECT * FROM {t} WHERE {base} \
AND COALESCE(reconcile_after, '9999') > '2026-11-15T00:00:00Z'",
Indexed,
),
case(
"SELECT * FROM {t} WHERE {base} AND UPPER(environment) = 'STG'",
Indexed,
),
case(
"SELECT id, note FROM {t} WHERE {base} AND UPPER(note) = 'HELLO'",
Indexed,
),
case(
"SELECT id FROM {t} WHERE {base} AND LENGTH(note) > 4",
Indexed,
),
case(
"SELECT id, attempts FROM {t} WHERE {base} AND CAST(attempts AS TEXT) = '2'",
Indexed,
),
case(
"SELECT id FROM {t} WHERE {base} AND attempts * 2 >= 4",
Indexed,
),
case(
"SELECT id FROM {t} WHERE {base} AND COALESCE(note, 'none') = 'none'",
Indexed,
),
case(
"SELECT id FROM {t} WHERE {base} AND COALESCE(attempts, -1) < 0",
Indexed,
),
case(
"SELECT id FROM {t} WHERE {base} AND UPPER(note) NOT IN ('HELLO', 'OTHER')",
Any,
),
case(
"SELECT id FROM {t} WHERE {base} \
AND CASE WHEN attempts IS NULL THEN 0 ELSE attempts END >= 1",
Indexed,
),
case(
"SELECT id FROM {t} WHERE {base} AND attempts >= 1 AND UPPER(note) = 'HELLO'",
Indexed,
),
case(
"SELECT id FROM {t} WHERE {base} AND UPPER(note) = 'HELLO' \
AND COALESCE(reconcile_after, '') <> ''",
Indexed,
),
case(
"SELECT id, window_start FROM {t} WHERE {base} \
AND COALESCE(reconcile_after, '') <= '2026-11-15T00:00:00Z' \
ORDER BY window_start DESC, id LIMIT 3",
Indexed,
),
case(
"SELECT id, reconcile_after FROM {t} WHERE {base} \
AND COALESCE(reconcile_after, '') <= '2026-12-31T00:00:00Z' \
ORDER BY reconcile_after, id LIMIT 4 OFFSET 1",
Indexed,
),
case(
"SELECT id FROM {t} WHERE environment = 'stg' AND park_id = 'p2' \
AND completed_at IS NULL AND streamed_at IS NOT NULL \
AND window_start >= '2026-11-10' \
AND COALESCE(reconcile_after, '') <= '2026-11-15T00:00:00Z'",
Indexed,
),
case(
"SELECT id FROM {t} WHERE {base} AND 1 / (attempts - attempts) > 0",
Indexed,
),
case(
"SELECT id FROM {t} WHERE environment = 'nowhere' AND park_id = 'p1' \
AND 1 / (attempts - attempts) > 0",
Any,
),
case(
"SELECT id FROM {t} WHERE {base} AND (UPPER(note) = 'HELLO' OR attempts = 3)",
Old,
),
case(
"SELECT id FROM {t} WHERE UPPER(note) = 'HELLO' OR park_id = 'p1'",
Old,
),
case(
"SELECT id FROM {t} WHERE {base} AND NOT (UPPER(note) = 'HELLO')",
Old,
),
case(
"SELECT id FROM {t} WHERE UPPER(environment) = 'STG' AND park_id = 'p1' \
AND completed_at IS NULL",
Old,
),
case(
"SELECT id FROM {t} WHERE attempts >= 0 AND UPPER(note) = 'HELLO'",
Old,
),
case(
"SELECT id FROM {t} WHERE {base} AND REVERSE(note) = 'olleh'",
Old,
),
];
let params = |values: [&str; 3]| values.map(Value::text).to_vec();
cases.push(Case {
sql: "SELECT id, reconcile_after FROM {t} WHERE environment = $1 AND park_id = $2 \
AND completed_at IS NULL AND streamed_at IS NOT NULL \
AND COALESCE(reconcile_after, '') <= $3"
.into(),
params: params(["stg", "p1", "2026-11-15T00:00:00Z"]),
path: Indexed,
});
cases.push(Case {
sql: "SELECT id, note FROM {t} WHERE environment = $1 AND park_id = $2 \
AND completed_at IS NULL AND streamed_at IS NOT NULL \
AND UPPER(note) = UPPER($3)"
.into(),
params: params(["stg", "p2", "hello"]),
path: Indexed,
});
cases
}
fn reads() -> u64 {
EXPRESSION_RESIDUAL_READS.with(|reads| reads.get())
}
fn operators(node: &crate::storage::query::planner::CanonicalLogicalNode) -> Vec<String> {
let mut operators = Vec::new();
let mut node = Some(node);
while let Some(current) = node {
operators.push(match current.operator.as_str() {
"table_scan" | "index_seek" => "scan".to_string(),
other => other.to_string(),
});
node = current.children.first();
}
operators
}
fn assert_plans_match(runtime: &RedDBRuntime, cases: &[Case]) {
use crate::storage::query::planner::CanonicalPlanner;
use reddb_rql::ast::QueryExpr;
let db = runtime.db();
let planner = CanonicalPlanner::new(&db);
for case in cases {
let sql = case.sql.replace("{t}", "jobs");
let QueryExpr::Table(query) = reddb_rql::parser::parse(&sql).expect("parse").query
else {
panic!("table query: {sql}")
};
let scan = planner.build(&QueryExpr::Table(query.clone()));
let candidates = planner.build_over_candidates(&query, 1);
assert_eq!(operators(&candidates.root), operators(&scan.root), "{sql}");
}
}
fn exec(runtime: &RedDBRuntime, sql: &str) {
runtime
.execute_query(sql)
.unwrap_or_else(|error| panic!("{sql}: {error:?}"));
}
fn observe(
runtime: &RedDBRuntime,
sql: &str,
params: &[Value],
) -> Result<(Vec<String>, Vec<String>), String> {
runtime.invalidate_result_cache();
let result = runtime
.execute_query_with_params(sql, params)
.map_err(|error| error.to_string())?
.result;
let mut rows = result
.records
.iter()
.map(|record| {
let mut values = record
.iter_fields()
.map(|(name, value)| format!("{name}={value:?}"))
.collect::<Vec<_>>();
values.sort();
values.join(", ")
})
.collect::<Vec<_>>();
let ordered = sql.contains("ORDER BY");
if !ordered {
rows.sort();
}
let columns = if ordered || !sql.starts_with("SELECT * ") {
result.columns
} else {
Vec::new()
};
Ok((columns, rows))
}
fn observe_indexed(
runtime: &RedDBRuntime,
case: &Case,
) -> Result<(Vec<String>, Vec<String>), String> {
let sql = case.sql.replace("{t}", "jobs");
let before = reads();
let observed = observe(runtime, &sql, &case.params);
let indexed = reads() > before;
match case.path {
Path::Indexed => assert!(indexed, "expected index candidates: {sql}"),
Path::Old => assert!(!indexed, "expected the previous read: {sql}"),
Path::Any => {}
}
observed
}
fn rows() -> Vec<String> {
(0..400)
.map(|i| {
let text = |value: Option<String>| {
value.map_or_else(|| "NULL".to_string(), |value| format!("'{value}'"))
};
let environment = if i % 7 == 0 { "prd" } else { "stg" };
let completed_at =
(i % 3 != 0).then(|| format!("2026-11-{:02}T00:00:00Z", 1 + i % 28));
let streamed_at =
(i % 4 != 1).then(|| format!("2026-11-{:02}T01:00:00Z", 1 + i % 27));
let window_start = format!("2026-11-{:02}T{:02}:00:00Z", 1 + i % 28, i % 24);
let reconcile_after = match (i / 5) % 5 {
0 => None,
1 => Some(String::new()),
2 => Some("2026-10-01T00:00:00Z".to_string()),
3 => Some("2026-12-31T00:00:00Z".to_string()),
_ => Some("2026-11-15T00:00:00Z".to_string()),
};
let attempts = if i % 6 == 0 {
"NULL".to_string()
} else {
(i % 4).to_string()
};
let note = match (i / 25) % 4 {
0 => None,
1 => Some("hello"),
2 => Some("HeLLo"),
_ => Some("other"),
};
format!(
"('job-{i:04}', '{environment}', 'p{}', {}, {}, '{window_start}', {}, {attempts}, {})",
i % 5,
text(completed_at),
text(streamed_at),
text(reconcile_after),
text(note.map(str::to_string)),
)
})
.collect()
}
fn create_and_fill(runtime: &RedDBRuntime, table: &str) {
exec(
runtime,
&format!(
"CREATE TABLE {table} (id TEXT PRIMARY KEY, environment TEXT, park_id TEXT, \
completed_at TEXT, streamed_at TEXT, window_start TEXT, reconcile_after TEXT, \
attempts INTEGER, note TEXT)"
),
);
for batch in rows().chunks(100) {
exec(
runtime,
&format!(
"INSERT INTO {table} (id, environment, park_id, completed_at, streamed_at, \
window_start, reconcile_after, attempts, note) VALUES {}",
batch.join(", ")
),
);
}
}
fn differential(runtime: &RedDBRuntime, indexes: &[&str], checkpoint: bool) {
create_and_fill(runtime, "jobs");
if checkpoint {
runtime.checkpoint().expect("rows on disk");
}
let cases = cases();
let scanned = cases
.iter()
.map(|case| {
let before = reads();
let observed = observe(runtime, &case.sql.replace("{t}", "jobs"), &case.params);
assert_eq!(reads(), before, "no index yet: {}", case.sql);
observed
})
.collect::<Vec<_>>();
assert!(
scanned
.iter()
.filter_map(|observed| observed.as_ref().ok())
.any(|(_, rows)| rows.len() > 1),
"the fixture must select rows"
);
assert!(
scanned.iter().any(Result::is_err),
"the fixture must make an expression fail"
);
for index in indexes {
exec(runtime, index);
}
if checkpoint {
runtime.checkpoint().expect("indexes on disk");
}
assert_plans_match(runtime, &cases);
for (case, expected) in cases.iter().zip(&scanned) {
let actual = observe_indexed(runtime, case);
assert_eq!(&actual, expected, "{}", case.sql);
}
for statement in [
"INSERT INTO {t} (id, environment, park_id, completed_at, streamed_at, window_start, \
reconcile_after, attempts, note) VALUES ('job-late', 'stg', 'p1', NULL, \
'2026-11-02T00:00:00Z', '2026-11-30T00:00:00Z', NULL, 2, 'Hello')",
"UPDATE {t} SET reconcile_after = '2026-12-31T00:00:00Z' WHERE id = 'job-0006'",
"UPDATE {t} SET completed_at = '2026-11-20T00:00:00Z' WHERE id = 'job-0066'",
"DELETE FROM {t} WHERE id = 'job-0036'",
] {
exec(runtime, &statement.replace("{t}", "jobs"));
}
let indexed = cases
.iter()
.map(|case| observe_indexed(runtime, case))
.collect::<Vec<_>>();
for index in indexes {
let name = index.split_whitespace().nth(2).expect("index name");
exec(runtime, &format!("DROP INDEX {name} ON jobs"));
}
let mut mismatches = Vec::new();
for (case, actual) in cases.iter().zip(&indexed) {
let before = reads();
let expected = observe(runtime, &case.sql.replace("{t}", "jobs"), &case.params);
assert_eq!(reads(), before, "no index left: {}", case.sql);
if *actual != expected {
mismatches.push(format!(
"{}\n indexed: {actual:?}\n scanned: {expected:?}",
case.sql
));
}
}
assert!(
mismatches.is_empty(),
"after changes:\n{}",
mismatches.join("\n")
);
}
#[test]
fn expression_residual_matches_the_scan_over_resident_indexes() {
let runtime =
RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("in-memory runtime");
differential(
&runtime,
&[
"CREATE INDEX jobs_environment ON jobs (environment) USING HASH",
"CREATE INDEX jobs_window_start ON jobs (window_start) USING BTREE",
],
false,
);
}
#[test]
fn expression_residual_matches_the_scan_over_paged_composite_indexes() {
let directory = tempfile::tempdir().expect("directory");
let mut runtime = RedDBRuntime::with_options(
RedDBOptions::persistent(directory.path().join("jobs.rdb"))
.with_memory_budget(256 * 1024 * 1024)
.with_bounded_disk_residency(true),
)
.expect("runtime");
drop(runtime.background_tasks.take());
differential(
&runtime,
&[
"CREATE INDEX jobs_window ON jobs \
(environment, park_id, completed_at, streamed_at, window_start, id)",
"CREATE INDEX jobs_reconcile ON jobs \
(environment, park_id, completed_at, streamed_at, reconcile_after, id)",
],
true,
);
}
#[test]
fn only_trailing_pure_expression_conjuncts_are_admitted() {
use reddb_rql::ast::QueryExpr;
let runtime =
RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("in-memory runtime");
exec(&runtime, "CREATE TABLE t (a TEXT, b TEXT, c INTEGER)");
exec(&runtime, "CREATE INDEX t_a ON t (a) USING HASH");
let store = runtime.index_store_ref();
let lookup = |predicate: &str| {
let sql = format!("SELECT a FROM t WHERE {predicate}");
let QueryExpr::Table(query) = reddb_rql::parser::parse(&sql).expect("parse").query
else {
panic!("table query")
};
let filter = reddb_rql::sql_lowering::effective_table_filter(&query).expect("filter");
super::lookup_filter(&filter, "t", store).map(|lookup| format!("{lookup:?}"))
};
let plain = lookup("a = 'x' AND c > 1").map(|_| ());
assert_eq!(
plain, None,
"a filter without expressions is not this path's"
);
let admitted = lookup("a = 'x' AND c > 1 AND UPPER(b) = 'Y' AND COALESCE(c, 0) + 1 > 2")
.expect("trailing pure expressions");
assert!(!admitted.contains("CompareExpr"), "{admitted}");
assert!(
admitted.contains("\"a\"") && admitted.contains("\"c\""),
"{admitted}"
);
for rejected in [
"UPPER(b) = 'Y' AND a = 'x'",
"a = 'x' AND (UPPER(b) = 'Y' OR c = 1)",
"a = 'x' AND NOT (UPPER(b) = 'Y')",
"a = 'x' AND UPPER(b) = 'Y' AND c > 1",
"c > 1 AND UPPER(b) = 'Y'",
"a = 'x' AND EMBED(b) IS NOT NULL",
"a = 'x' AND PG_TRY_ADVISORY_LOCK(c) = true",
] {
assert_eq!(lookup(rejected), None, "{rejected}");
}
}
}