fsqlite-core 0.3.0

Core engine: connection, prepare, schema, DDL/DML codegen
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
710
711
712
713
714
//! EXPLAIN and EXPLAIN QUERY PLAN execution (§12.12, bd-7pxb).
//!
//! EXPLAIN returns VDBE bytecode as a result set with columns:
//!   addr, opcode, p1, p2, p3, p4, p5, comment
//!
//! EXPLAIN QUERY PLAN returns a tree-structured plan with columns:
//!   id, parent, notused, detail

use std::collections::{HashMap, HashSet};

use fsqlite_types::opcode::{Opcode, P4};
use fsqlite_vdbe::VdbeProgram;

// ---------------------------------------------------------------------------
// EXPLAIN result row
// ---------------------------------------------------------------------------

/// A single row from EXPLAIN output (invariant #10).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExplainRow {
    /// Instruction address (0-based).
    pub addr: i32,
    /// Opcode name (e.g., "Init", "OpenRead").
    pub opcode: String,
    /// First parameter.
    pub p1: i32,
    /// Second parameter (often a jump target).
    pub p2: i32,
    /// Third parameter.
    pub p3: i32,
    /// Fourth parameter (text representation).
    pub p4: String,
    /// Fifth parameter (flags).
    pub p5: u16,
    /// Comment (auto-generated from opcode semantics).
    pub comment: String,
}

/// Generate EXPLAIN output for a compiled VDBE program.
///
/// Returns one row per instruction with columns:
/// addr, opcode, p1, p2, p3, p4, p5, comment (invariant #10).
#[must_use]
pub fn explain_program(program: &VdbeProgram) -> Vec<ExplainRow> {
    program
        .ops()
        .iter()
        .enumerate()
        .map(|(i, op)| {
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            let addr = i as i32;
            ExplainRow {
                addr,
                opcode: format!("{:?}", op.opcode),
                p1: op.p1,
                p2: op.p2,
                p3: op.p3,
                p4: format!("{:?}", op.p4),
                p5: op.p5,
                comment: opcode_comment(op.opcode, op.p1, op.p2, op.p3),
            }
        })
        .collect()
}

/// Auto-generate a comment for an opcode based on its semantics.
fn opcode_comment(opcode: Opcode, p1: i32, p2: i32, p3: i32) -> String {
    match opcode {
        Opcode::Init => format!("start at {p2}"),
        Opcode::Goto => format!("goto {p2}"),
        Opcode::Halt => {
            if p1 == 0 {
                String::new()
            } else {
                format!("error code {p1}")
            }
        }
        Opcode::Transaction => {
            if p2 == 0 {
                "read transaction".to_owned()
            } else {
                "write transaction".to_owned()
            }
        }
        Opcode::OpenRead | Opcode::OpenWrite => format!("root={p2}"),
        Opcode::Column => format!("r[{p3}]=cursor[{p1}].column[{p2}]"),
        Opcode::ResultRow => format!("output r[{p1}..{p1}+{p2}]"),
        Opcode::Rewind => format!("if eof goto {p2}"),
        Opcode::Next => format!("goto {p2} if more rows"),
        Opcode::Close => format!("close cursor {p1}"),
        _ => String::new(),
    }
}

// ---------------------------------------------------------------------------
// EXPLAIN QUERY PLAN
// ---------------------------------------------------------------------------

/// A single row from EXPLAIN QUERY PLAN output (invariant #11).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EqpRow {
    /// Node id in the plan tree.
    pub id: i32,
    /// Parent node id (0 for root nodes).
    pub parent: i32,
    /// Not used (always 0, kept for compatibility).
    pub notused: i32,
    /// Human-readable description of this plan step.
    pub detail: String,
}

/// Generate EXPLAIN QUERY PLAN output for a compiled VDBE program.
///
/// Returns a tree-structured plan with columns: id, parent, notused, detail
/// (invariant #11). The tree structure is expressed via id/parent relationships
/// (invariant #23).
#[must_use]
pub fn explain_query_plan(program: &VdbeProgram) -> Vec<EqpRow> {
    let ops = program.ops();
    let mut rows = Vec::new();
    let mut next_id = 1_i32;
    let mut index_step_by_cursor: HashMap<i32, usize> = HashMap::new();
    let mut index_name_by_cursor: HashMap<i32, String> = HashMap::new();
    let mut index_used = HashSet::new();
    let mut index_with_table_lookup = HashSet::new();
    let mut last_idxrowid_cursor = None;
    let mut saw_sorter = false;

    // Scan for table/index opens and infer index/sorter usage.
    for op in ops {
        match op.opcode {
            Opcode::OpenRead | Opcode::OpenWrite => {
                let scan_type = if op.opcode == Opcode::OpenRead {
                    "SCAN"
                } else {
                    "SEARCH"
                };
                let detail = match &op.p4 {
                    P4::Table(name) => format!("{scan_type} {name}"),
                    P4::Index(name) => format!("{scan_type} INDEX {name}"),
                    _ => format!("{scan_type} {:?}", op.p4),
                };
                rows.push(EqpRow {
                    id: next_id,
                    parent: 0,
                    notused: 0,
                    detail,
                });
                if let P4::Index(name) = &op.p4 {
                    index_step_by_cursor.insert(op.p1, rows.len() - 1);
                    index_name_by_cursor.insert(op.p1, name.clone());
                }
                next_id += 1;
            }
            Opcode::SeekGE
            | Opcode::SeekLE
            | Opcode::SeekGT
            | Opcode::SeekLT
            | Opcode::IdxGE
            | Opcode::IdxGT
            | Opcode::IdxLE
            | Opcode::IdxLT
            | Opcode::Rewind
            | Opcode::Last
            | Opcode::Next
            | Opcode::Prev => {
                if index_name_by_cursor.contains_key(&op.p1) {
                    index_used.insert(op.p1);
                }
            }
            Opcode::IdxRowid => {
                if index_name_by_cursor.contains_key(&op.p1) {
                    index_used.insert(op.p1);
                    last_idxrowid_cursor = Some(op.p1);
                }
            }
            Opcode::SeekRowid => {
                if let Some(index_cursor) = last_idxrowid_cursor {
                    index_with_table_lookup.insert(index_cursor);
                }
                last_idxrowid_cursor = None;
            }
            Opcode::SorterOpen | Opcode::SorterInsert | Opcode::SorterSort => {
                saw_sorter = true;
            }
            _ => {
                last_idxrowid_cursor = None;
            }
        }
    }

    // Annotate index rows as covering vs non-covering.
    for index_cursor in index_used {
        let Some(step_idx) = index_step_by_cursor.get(&index_cursor).copied() else {
            continue;
        };
        let Some(index_name) = index_name_by_cursor.get(&index_cursor) else {
            continue;
        };
        let usage = if index_with_table_lookup.contains(&index_cursor) {
            format!(" USING INDEX {index_name}")
        } else {
            format!(" USING COVERING INDEX {index_name}")
        };
        if !rows[step_idx].detail.contains("USING ") {
            rows[step_idx].detail.push_str(&usage);
        }
    }

    if saw_sorter {
        rows.push(EqpRow {
            id: next_id,
            parent: 0,
            notused: 0,
            detail: "USE TEMP B-TREE FOR ORDER BY".to_owned(),
        });
    }

    // If no table opens found, emit a minimal plan.
    if rows.is_empty() {
        rows.push(EqpRow {
            id: 1,
            parent: 0,
            notused: 0,
            detail: "SCAN CONSTANT ROW".to_owned(),
        });
    }

    rows
}

/// The index access path an aggregate program actually executes.
///
/// bd-2dgf5 / bd-jyyae.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AggregateIndexSeek {
    /// Name of the index the program seeks.
    pub index_name: String,
    /// True when the seek satisfies every aggregate from the index entry alone,
    /// i.e. the program never looks the row up in the table.
    pub covering: bool,
}

/// Read an aggregate's index access path off the *emitted program*.
///
/// bd-2dgf5 / bd-jyyae. `EXPLAIN QUERY PLAN` normally renders from the planner
/// directive, and `planner_select_directive_with_stats` refuses to produce one for
/// an aggregate — so an aggregate that seeks used to print `SCAN t`. The obvious
/// repair, re-checking in the EQP path the same conditions codegen checked, is the
/// bug bd-jyyae is about: the two copies drift, and then EQP confidently describes
/// a plan the program never runs (it once reported `SEARCH` for an `IN (...)` whose
/// program was a bare `Rewind`/`Next` scan).
///
/// So decide nothing here. An index cursor is SEARCHed exactly when a `Seek*`
/// positions it, and the index is COVERING exactly when no `IdxRowid` on that cursor
/// feeds a `SeekRowid` into the table. Both facts are properties of the opcodes.
///
/// Returns `None` unless the program is an aggregate (`AggStep`) driven by exactly
/// one seeked index cursor; every other shape keeps the existing EQP rendering.
#[must_use]
pub fn aggregate_index_seek_facts(program: &VdbeProgram) -> Option<AggregateIndexSeek> {
    let ops = program.ops();
    if !ops.iter().any(|op| op.opcode == Opcode::AggStep) {
        return None;
    }

    let mut index_name_by_cursor: HashMap<i32, &str> = HashMap::new();
    for op in ops {
        if op.opcode == Opcode::OpenRead
            && let P4::Index(name) = &op.p4
        {
            index_name_by_cursor.insert(op.p1, name.as_str());
        }
    }

    let mut seeked: Vec<i32> = Vec::new();
    for op in ops {
        let positions_index = matches!(
            op.opcode,
            Opcode::SeekGE | Opcode::SeekGT | Opcode::SeekLE | Opcode::SeekLT
        ) && index_name_by_cursor.contains_key(&op.p1);
        if positions_index && !seeked.contains(&op.p1) {
            seeked.push(op.p1);
        }
    }
    let [cursor] = seeked[..] else {
        return None;
    };

    // A table lookup is an `IdxRowid` on the seeked cursor feeding a `SeekRowid`.
    // Any other opcode in between breaks the pairing, exactly as in
    // `explain_query_plan`'s covering-vs-non-covering annotation.
    let mut rowid_from_seeked_cursor = false;
    let mut table_lookup = false;
    for op in ops {
        match op.opcode {
            Opcode::IdxRowid => rowid_from_seeked_cursor = op.p1 == cursor,
            Opcode::SeekRowid => {
                table_lookup |= rowid_from_seeked_cursor;
                rowid_from_seeked_cursor = false;
            }
            _ => rowid_from_seeked_cursor = false,
        }
    }

    Some(AggregateIndexSeek {
        index_name: (*index_name_by_cursor.get(&cursor)?).to_owned(),
        covering: !table_lookup,
    })
}

/// True when the emitted program positions a cursor opened on `index_name`
/// with a key seek (`SeekGE`/`SeekGT`/`SeekLE`/`SeekLT`).
///
/// bd-jyyae: `EXPLAIN QUERY PLAN` renders the planner directive, but codegen
/// can decline the directive's access path — `IN (SELECT ...)` predicates
/// compile to a full table scan probing an ephemeral membership index, while
/// the directive still claims `SEARCH ... USING INDEX`. The claim is true
/// exactly when a seek opcode positions a cursor opened on that index — a
/// property of the opcodes, not of planner intent. `Rewind`/`Next` on an
/// index cursor is a scan of the index, not a search, and deliberately does
/// not count.
#[must_use]
pub fn program_seeks_named_index(program: &VdbeProgram, index_name: &str) -> bool {
    let ops = program.ops();
    let mut index_cursors: HashSet<i32> = HashSet::new();
    for op in ops {
        if matches!(op.opcode, Opcode::OpenRead | Opcode::OpenWrite)
            && let P4::Index(name) = &op.p4
            && name == index_name
        {
            index_cursors.insert(op.p1);
        }
    }
    if index_cursors.is_empty() {
        return false;
    }
    ops.iter().any(|op| {
        matches!(
            op.opcode,
            Opcode::SeekGE | Opcode::SeekGT | Opcode::SeekLE | Opcode::SeekLT
        ) && index_cursors.contains(&op.p1)
    })
}

/// True when the emitted program probes a cursor opened on `table_name`
/// directly by rowid (`SeekRowid`/`NotExists`).
///
/// bd-jyyae companion to [`program_seeks_named_index`] for the
/// `SEARCH ... USING INTEGER PRIMARY KEY (rowid=?)` directive claim. The
/// probe must target a cursor opened on the named table so that a rowid seek
/// elsewhere in the program (an index's table-lookup leg, a subquery) cannot
/// vouch for a main-table claim.
#[must_use]
pub fn program_seeks_rowid_on_table(program: &VdbeProgram, table_name: &str) -> bool {
    let ops = program.ops();
    let mut table_cursors: HashSet<i32> = HashSet::new();
    for op in ops {
        if matches!(op.opcode, Opcode::OpenRead | Opcode::OpenWrite)
            && let P4::Table(name) = &op.p4
            && name == table_name
        {
            table_cursors.insert(op.p1);
        }
    }
    if table_cursors.is_empty() {
        return false;
    }
    ops.iter().any(|op| {
        matches!(op.opcode, Opcode::SeekRowid | Opcode::NotExists) && table_cursors.contains(&op.p1)
    })
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use fsqlite_types::opcode::{Opcode, P4};
    use fsqlite_vdbe::ProgramBuilder;

    fn build_simple_select_program() -> VdbeProgram {
        let mut b = ProgramBuilder::new();
        let end_label = b.emit_label();
        let done_label = b.emit_label();

        b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
        b.emit_op(Opcode::Transaction, 0, 0, 0, P4::None, 0);
        b.emit_op(Opcode::OpenRead, 0, 2, 0, P4::Table("t".to_owned()), 0);
        b.emit_jump_to_label(Opcode::Rewind, 0, 0, done_label, P4::None, 0);
        b.emit_op(Opcode::Column, 0, 0, 1, P4::None, 0);
        b.emit_op(Opcode::ResultRow, 1, 1, 0, P4::None, 0);
        b.emit_op(Opcode::Next, 0, 4, 0, P4::None, 0);
        b.resolve_label(done_label);
        b.emit_op(Opcode::Close, 0, 0, 0, P4::None, 0);
        b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
        b.resolve_label(end_label);

        b.finish().unwrap()
    }

    // === Test 20: EXPLAIN returns VDBE bytecode with correct columns ===
    #[test]
    fn test_explain_returns_bytecode() {
        let prog = build_simple_select_program();
        let rows = explain_program(&prog);

        // Should have rows for each instruction.
        assert!(!rows.is_empty());
        assert_eq!(rows[0].addr, 0);

        // Check column presence (addr, opcode, p1, p2, p3, p4, p5, comment).
        let init_row = &rows[0];
        assert_eq!(init_row.opcode, "Init");
        // p5 is present.
        assert_eq!(init_row.p5, 0);
        // Comment is present.
        assert!(init_row.comment.contains("start at"));
    }

    // === Test 21: EXPLAIN QUERY PLAN returns id, parent, notused, detail ===
    #[test]
    fn test_explain_query_plan_columns() {
        let prog = build_simple_select_program();
        let rows = explain_query_plan(&prog);

        assert!(!rows.is_empty());
        let row = &rows[0];
        // Verify all four columns are present.
        assert!(row.id > 0);
        assert_eq!(row.parent, 0);
        assert_eq!(row.notused, 0);
        assert!(!row.detail.is_empty());
    }

    // === Test 22: EQP detail shows index usage ===
    #[test]
    fn test_explain_query_plan_shows_index() {
        // Build a program that probes an index and then looks up table rows.
        let mut b = ProgramBuilder::new();
        let end_label = b.emit_label();
        let done_label = b.emit_label();
        let skip_label = b.emit_label();

        b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
        b.emit_op(Opcode::Transaction, 0, 0, 0, P4::None, 0);
        b.emit_op(Opcode::OpenRead, 0, 2, 0, P4::Table("t".to_owned()), 0);
        b.emit_op(
            Opcode::OpenRead,
            1,
            3,
            0,
            P4::Index("idx_t_a".to_owned()),
            0,
        );
        b.emit_jump_to_label(Opcode::Rewind, 1, 0, done_label, P4::None, 0);
        b.emit_op(Opcode::IdxRowid, 1, 2, 0, P4::None, 0);
        b.emit_jump_to_label(Opcode::SeekRowid, 0, 2, skip_label, P4::None, 0);
        b.emit_op(Opcode::Column, 0, 0, 1, P4::None, 0);
        b.emit_op(Opcode::ResultRow, 1, 1, 0, P4::None, 0);
        b.resolve_label(skip_label);
        b.emit_op(Opcode::Next, 1, 5, 0, P4::None, 0);
        b.resolve_label(done_label);
        b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
        b.resolve_label(end_label);

        let prog = b.finish().unwrap();
        let rows = explain_query_plan(&prog);

        // Should show index usage.
        let has_index = rows.iter().any(|r| r.detail.contains("USING INDEX"));
        assert!(has_index, "EQP should show index usage, got: {rows:?}");
    }

    // === Test 23: EQP id/parent form correct tree ===
    #[test]
    fn test_explain_query_plan_tree_structure() {
        let prog = build_simple_select_program();
        let rows = explain_query_plan(&prog);

        // Root nodes have parent=0.
        for row in &rows {
            if row.parent == 0 {
                // Root node — id should be positive.
                assert!(row.id > 0);
            } else {
                // Child node — parent should reference an existing node.
                assert!(rows.iter().any(|r| r.id == row.parent));
            }
        }

        // Ids should be unique.
        let mut ids: Vec<i32> = rows.iter().map(|r| r.id).collect();
        ids.sort_unstable();
        ids.dedup();
        assert_eq!(ids.len(), rows.len());
    }

    #[test]
    fn test_explain_query_plan_shows_covering_index() {
        let mut b = ProgramBuilder::new();
        let end_label = b.emit_label();
        let done_label = b.emit_label();

        b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
        b.emit_op(Opcode::Transaction, 0, 0, 0, P4::None, 0);
        b.emit_op(
            Opcode::OpenRead,
            1,
            3,
            0,
            P4::Index("idx_t_b".to_owned()),
            0,
        );
        b.emit_jump_to_label(Opcode::Rewind, 1, 0, done_label, P4::None, 0);
        b.emit_op(Opcode::Column, 1, 0, 1, P4::None, 0);
        b.emit_op(Opcode::ResultRow, 1, 1, 0, P4::None, 0);
        b.emit_op(Opcode::Next, 1, 4, 0, P4::None, 0);
        b.resolve_label(done_label);
        b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
        b.resolve_label(end_label);

        let prog = b.finish().unwrap();
        let rows = explain_query_plan(&prog);
        let has_covering = rows
            .iter()
            .any(|row| row.detail.contains("USING COVERING INDEX idx_t_b"));
        assert!(
            has_covering,
            "EQP should show covering-index usage, got: {rows:?}"
        );
    }

    #[test]
    fn test_explain_query_plan_shows_temp_btree_for_order_by() {
        let mut b = ProgramBuilder::new();
        let end_label = b.emit_label();
        let done_label = b.emit_label();

        b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
        b.emit_op(Opcode::Transaction, 0, 0, 0, P4::None, 0);
        b.emit_op(Opcode::OpenRead, 0, 2, 0, P4::Table("t".to_owned()), 0);
        b.emit_op(Opcode::SorterOpen, 1, 1, 0, P4::Str("+".to_owned()), 0);
        b.emit_jump_to_label(Opcode::Rewind, 0, 0, done_label, P4::None, 0);
        b.emit_op(Opcode::Column, 0, 0, 2, P4::None, 0);
        b.emit_op(Opcode::MakeRecord, 2, 1, 3, P4::None, 0);
        b.emit_op(Opcode::SorterInsert, 1, 3, 0, P4::None, 0);
        b.resolve_label(done_label);
        b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
        b.resolve_label(end_label);

        let prog = b.finish().unwrap();
        let rows = explain_query_plan(&prog);
        let has_temp_btree = rows
            .iter()
            .any(|row| row.detail == "USE TEMP B-TREE FOR ORDER BY");
        assert!(
            has_temp_btree,
            "EQP should include temp B-tree marker for sorter plans, got: {rows:?}"
        );
    }

    /// The truthful equality-probe shape: `SeekGE` positions the index
    /// cursor, `IdxRowid`/`SeekRowid` fetch the table row (the program
    /// `EXPLAIN SELECT * FROM t WHERE k = 2` actually emits).
    fn build_index_seek_program() -> VdbeProgram {
        let mut b = ProgramBuilder::new();
        let end_label = b.emit_label();
        let done_label = b.emit_label();
        let skip_label = b.emit_label();

        b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
        b.emit_op(Opcode::Transaction, 0, 0, 0, P4::None, 0);
        b.emit_op(Opcode::OpenRead, 0, 2, 0, P4::Table("t".to_owned()), 0);
        b.emit_op(
            Opcode::OpenRead,
            1,
            3,
            0,
            P4::Index("idx_t_k".to_owned()),
            0,
        );
        b.emit_jump_to_label(Opcode::SeekGE, 1, 0, done_label, P4::None, 0);
        b.emit_op(Opcode::IdxRowid, 1, 9, 0, P4::None, 0);
        b.emit_jump_to_label(Opcode::SeekRowid, 0, 9, skip_label, P4::None, 0);
        b.emit_op(Opcode::Column, 0, 1, 2, P4::None, 0);
        b.emit_op(Opcode::ResultRow, 2, 1, 0, P4::None, 0);
        b.resolve_label(skip_label);
        b.emit_op(Opcode::Next, 1, 5, 0, P4::None, 0);
        b.resolve_label(done_label);
        b.emit_op(Opcode::Close, 1, 0, 0, P4::None, 0);
        b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
        b.resolve_label(end_label);

        b.finish().unwrap()
    }

    /// The bd-jyyae divergence shape: full `Rewind`/`Next` scan of the table
    /// with an ephemeral membership probe (`OpenAutoindex` + `Found`) — the
    /// program `SELECT * FROM t WHERE k IN (SELECT id FROM r)` actually
    /// emits. No cursor is ever opened on `idx_t_k`, and no seek runs.
    fn build_in_subquery_scan_program() -> VdbeProgram {
        let mut b = ProgramBuilder::new();
        let end_label = b.emit_label();
        let done_label = b.emit_label();
        let skip_label = b.emit_label();

        b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
        b.emit_op(Opcode::Transaction, 0, 0, 0, P4::None, 0);
        b.emit_op(Opcode::OpenRead, 0, 2, 0, P4::Table("t".to_owned()), 0);
        b.emit_jump_to_label(Opcode::Rewind, 0, 0, done_label, P4::None, 0);
        b.emit_op(Opcode::Column, 0, 1, 5, P4::None, 0);
        b.emit_op(Opcode::MakeRecord, 5, 1, 7, P4::None, 0);
        b.emit_jump_to_label(Opcode::Found, 12294, 0, skip_label, P4::None, 0);
        b.emit_op(Opcode::Rowid, 0, 1, 0, P4::None, 0);
        b.emit_op(Opcode::ResultRow, 1, 1, 0, P4::None, 0);
        b.resolve_label(skip_label);
        b.emit_op(Opcode::Next, 0, 4, 0, P4::None, 0);
        b.resolve_label(done_label);
        b.emit_op(Opcode::Close, 0, 0, 0, P4::None, 0);
        b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
        b.resolve_label(end_label);

        b.finish().unwrap()
    }

    // === bd-jyyae: directive seek claims must be provable from the opcodes ===

    #[test]
    fn test_program_seeks_named_index_true_for_seek_shape() {
        let prog = build_index_seek_program();
        assert!(program_seeks_named_index(&prog, "idx_t_k"));
    }

    #[test]
    fn test_program_seeks_named_index_false_for_in_subquery_scan() {
        let prog = build_in_subquery_scan_program();
        assert!(
            !program_seeks_named_index(&prog, "idx_t_k"),
            "a Rewind/Next membership-probe scan must not vouch for a SEARCH claim"
        );
    }

    #[test]
    fn test_program_seeks_named_index_false_for_index_only_scan() {
        // An index cursor driven only by Rewind/Next is an index SCAN, not a
        // SEARCH: the equality/range claim must not be vouched for.
        let mut b = ProgramBuilder::new();
        let end_label = b.emit_label();
        let done_label = b.emit_label();

        b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
        b.emit_op(Opcode::Transaction, 0, 0, 0, P4::None, 0);
        b.emit_op(
            Opcode::OpenRead,
            1,
            3,
            0,
            P4::Index("idx_t_k".to_owned()),
            0,
        );
        b.emit_jump_to_label(Opcode::Rewind, 1, 0, done_label, P4::None, 0);
        b.emit_op(Opcode::Column, 1, 0, 1, P4::None, 0);
        b.emit_op(Opcode::ResultRow, 1, 1, 0, P4::None, 0);
        b.emit_op(Opcode::Next, 1, 4, 0, P4::None, 0);
        b.resolve_label(done_label);
        b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
        b.resolve_label(end_label);

        let prog = b.finish().unwrap();
        assert!(!program_seeks_named_index(&prog, "idx_t_k"));
    }

    #[test]
    fn test_program_seeks_rowid_on_table_true_for_rowid_probe() {
        let mut b = ProgramBuilder::new();
        let end_label = b.emit_label();
        let done_label = b.emit_label();

        b.emit_jump_to_label(Opcode::Init, 0, 0, end_label, P4::None, 0);
        b.emit_op(Opcode::Transaction, 0, 0, 0, P4::None, 0);
        b.emit_op(Opcode::OpenRead, 0, 2, 0, P4::Table("t".to_owned()), 0);
        b.emit_jump_to_label(Opcode::SeekRowid, 0, 1, done_label, P4::None, 0);
        b.emit_op(Opcode::Column, 0, 1, 2, P4::None, 0);
        b.emit_op(Opcode::ResultRow, 2, 1, 0, P4::None, 0);
        b.resolve_label(done_label);
        b.emit_op(Opcode::Halt, 0, 0, 0, P4::None, 0);
        b.resolve_label(end_label);

        let prog = b.finish().unwrap();
        assert!(program_seeks_rowid_on_table(&prog, "t"));
        assert!(
            !program_seeks_rowid_on_table(&prog, "other"),
            "a rowid probe on t must not vouch for a claim about another table"
        );
    }

    #[test]
    fn test_program_seeks_rowid_on_table_false_for_scan() {
        let prog = build_simple_select_program();
        assert!(!program_seeks_rowid_on_table(&prog, "t"));
    }

    #[test]
    fn test_index_table_lookup_leg_does_not_vouch_for_table_rowid_claim() {
        // The SeekRowid in an index seek's table-lookup leg targets the table
        // cursor, so it legitimately proves a rowid probe on that cursor —
        // but the *index* claim for an unrelated index must still fail.
        let prog = build_index_seek_program();
        assert!(!program_seeks_named_index(&prog, "idx_other"));
    }
}