reddb-io-server 1.43.21

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
//! Indexed reads for a WHERE whose expression predicates trail its plain
//! AND conjuncts (#3074).
//!
//! `WHERE environment = 'stg' AND … AND COALESCE(reconcile_after, '') <= $1`
//! used to read the whole table: one `CompareExpr` anywhere in the filter
//! made the optimistic indexed read ineligible. Here the plain conjuncts name
//! the candidate rows through the lookups the sorted-index and hash paths
//! use, and the canonical table plan applies the complete WHERE, the expression
//! conjuncts included, then ORDER BY and the window, to those candidates
//! exactly as it does to every row of a full scan.
//!
//! [`lookup_filter`] admits a filter when:
//! - it is an AND of conjuncts and every `CompareExpr` is one of them, never
//!   under OR or NOT;
//! - every expression conjunct follows every plain conjunct. A row the index
//!   does not name fails a plain conjunct, and the full scan stops at that
//!   conjunct before it reaches any expression. The expressions are thus
//!   evaluated on exactly the rows the full scan evaluates them on, with the
//!   same results and the same errors;
//! - the expressions are pure: columns, literals, bound parameters,
//!   operators, CAST, CASE and the deterministic built-ins in
//!   [`PURE_SCALAR_FUNCTIONS`]. A writer racing the optimistic read repeats
//!   it, so anything with an effect, a cost or a subquery keeps the old path;
//! - some plain conjunct names a column an index of the table covers.

use super::super::index_store::IndexStore;
use super::*;
use crate::storage::unified::hash_index::HashCandidates;

thread_local! {
    /// Reads this thread answered from index candidates under an expression
    /// residual.
    pub(crate) static EXPRESSION_RESIDUAL_READS: std::cell::Cell<u64> =
        const { std::cell::Cell::new(0) };
}

/// Deterministic scalar built-ins without effects, context reads or cost.
/// Both the typed evaluator and its fallback resolve these names to built-in
/// code only.
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",
];

/// Whether evaluating `expr` twice for the same row is unobservable.
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,
    }
}

/// The conjuncts of `filter` in evaluation order.
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,
    }
}

/// The plain conjuncts of `filter` that name its index candidates, when
/// `filter` ends in pure expression conjuncts the module documentation
/// admits. `None` leaves the query on the path it took before.
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;
            }
            // An expression under OR or NOT, or a plain test after an
            // expression, would change which rows evaluate the expression.
            _ 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)))
}

/// Candidate rows for `lookup`, from the lookups the sorted-index and hash
/// paths use: a superset of the rows `lookup` admits, or `None` when no index
/// answers it. Admission failures are authoritative.
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}"))
                    })?;
                // A miss does not rule out rows equal to the literal under
                // SQL coercion: only a hit names candidates.
                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;

    /// The plain conjuncts of the STG reconcile query (#3074).
    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 {
        /// Index candidates under the expression residual.
        Indexed,
        /// The read the query took before #3074.
        Old,
        /// Either; only the result is checked.
        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![
            // Controls without expressions: the paths they took before.
            case("SELECT * FROM {t} WHERE {base}", Any),
            case(
                "SELECT * FROM {t} WHERE {base} AND reconcile_after IS NULL",
                Any,
            ),
            // COALESCE over NULL, empty, past, boundary and future values.
            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,
            ),
            // Expressions over columns no index covers.
            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,
            ),
            // NULL semantics.
            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,
            ),
            // The parser may lower NOT IN to a negated filter: either path.
            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,
            ),
            // A plain test no index answers, then two expressions.
            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,
            ),
            // ORDER BY and the window run over the candidates.
            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,
            ),
            // A range on the index after the equality prefix.
            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,
            ),
            // The expression fails on exactly the rows it failed on before.
            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,
            ),
            // An expression under OR or NOT.
            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,
            ),
            // An expression before a plain test.
            case(
                "SELECT id FROM {t} WHERE UPPER(environment) = 'STG' AND park_id = 'p1' \
                 AND completed_at IS NULL",
                Old,
            ),
            // No plain test an index covers.
            case(
                "SELECT id FROM {t} WHERE attempts >= 0 AND UPPER(note) = 'HELLO'",
                Old,
            ),
            // A function outside the pure set.
            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())
    }

    /// The operators of a plan from its root, with the scan labels that
    /// execute alike folded together.
    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
    }

    /// The candidate plan runs the operators the scan's plan runs.
    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:?}"));
    }

    /// The columns and rows of a read, each row rendered field by field, or
    /// its error. Rows are sorted unless the query orders them. Without
    /// ORDER BY the columns of `SELECT *` are sampled from rows in an
    /// unspecified order, and a row an UPDATE rewrote names a column the
    /// others lack, so those are not compared.
    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))
    }

    /// `observe`, checking which read answered.
    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(", ")
                ),
            );
        }
    }

    /// Results with indexes equal the full-scan results, before and after
    /// changes the published indexes have not seen.
    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<_>>();
        // Without its indexes the table is scanned, as before #3074.
        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}");
        }
    }
}