mirage-analyzer 1.2.7

Path-Aware Code Intelligence Engine for Rust
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
//! Path caching with BLAKE3 content addressing
//!
//! This module provides database-backed caching for enumerated execution paths.
//! Paths are stored with their BLAKE3 hash as the primary key, providing automatic
//! deduplication and tamper detection. Cache entries are invalidated when function
//! content changes (detected via function_hash comparison).

use anyhow::{Context, Result};
use rusqlite::{params, Connection};
use std::collections::HashMap;

use crate::cfg::{BlockId, Path, PathKind};

/// Path cache manager (placeholder for future cache management features)
///
/// This struct is a placeholder for future cache management functionality
/// such as cache statistics, manual invalidation controls, and cache warming.
#[derive(Debug, Clone)]
pub struct PathCache {
    _private: (),
}

impl PathCache {
    /// Create a new path cache manager
    pub fn new() -> Self {
        Self { _private: () }
    }
}

impl Default for PathCache {
    fn default() -> Self {
        Self::new()
    }
}

/// Store enumerated paths in the database
///
/// # Arguments
///
/// * `conn` - Database connection
/// * `function_id` - ID of the function these paths belong to
/// * `paths` - Slice of paths to store
///
/// # Returns
///
/// Ok(()) on success, error on database failure
///
/// # Algorithm
///
/// 1. Begin transaction (BEGIN IMMEDIATE to prevent write conflicts)
/// 2. For each path:
///    - Insert into cfg_paths table with BLAKE3 path_id as primary key
///    - Insert each block into cfg_path_elements with sequence_order
/// 3. Commit transaction
///
/// # Transactions
///
/// Uses IMMEDIATE transaction mode to prevent write conflicts in concurrent access.
/// Transaction is automatically rolled back on error.
pub fn store_paths(conn: &mut Connection, function_id: i64, paths: &[Path]) -> Result<()> {
    // Begin transaction for atomicity
    conn.execute("BEGIN IMMEDIATE TRANSACTION", [])
        .context("Failed to begin transaction for store_paths")?;

    // Prepare insert statements for efficiency
    let mut insert_path_stmt = conn.prepare_cached(
        "INSERT INTO cfg_paths (path_id, function_id, path_kind, entry_block, exit_block, length, created_at)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
    ).context("Failed to prepare cfg_paths insert statement")?;

    let mut insert_element_stmt = conn
        .prepare_cached(
            "INSERT INTO cfg_path_elements (path_id, sequence_order, block_id)
         VALUES (?1, ?2, ?3)",
        )
        .context("Failed to prepare cfg_path_elements insert statement")?;

    let now = chrono::Utc::now().timestamp();

    for path in paths {
        // Convert PathKind to string for storage
        let kind_str = path_kind_to_str(path.kind);

        // Insert the path metadata
        insert_path_stmt
            .execute(params![
                &path.path_id,
                function_id,
                kind_str,
                path.entry as i64,
                path.exit as i64,
                path.len() as i64,
                now,
            ])
            .with_context(|| format!("Failed to insert path {}", path.path_id))?;

        // Insert each block in the path
        for (idx, &block_id) in path.blocks.iter().enumerate() {
            insert_element_stmt
                .execute(params![&path.path_id, idx as i64, block_id as i64,])
                .with_context(|| {
                    format!("Failed to insert element {} for path {}", idx, path.path_id)
                })?;
        }
    }

    // Commit transaction
    conn.execute("COMMIT", [])
        .context("Failed to commit transaction for store_paths")?;

    Ok(())
}

/// Batch size for UNION ALL inserts
///
/// Larger batches reduce round-trips but increase statement preparation time.
/// 20 rows per batch provides good balance (measured ~50ms for 1000 elements).
const BATCH_SIZE: usize = 20;

/// Store enumerated paths in the database with optimized batch inserts
///
/// This is an optimized version of `store_paths` that uses batched inserts
/// with UNION ALL to reduce database round-trips.
///
/// # Performance
///
/// - 100 paths (1000 elements): <100ms
/// - Uses PRAGMA optimizations for bulk inserts
/// - Batches elements with UNION ALL (20 per statement)
///
/// # Arguments
///
/// * `conn` - Database connection
/// * `function_id` - ID of the function these paths belong to
/// * `paths` - Slice of paths to store
///
/// # Returns
///
/// Ok(()) on success, error on database failure
///
/// # Algorithm
///
/// 1. Begin IMMEDIATE transaction
/// 2. Optimize SQLite for bulk inserts:
///    - Set journal_mode = OFF (faster, less safe during crashes)
///    - Set synchronous = OFF (faster, less durable)
///    - Set cache_size = -64000 (64MB cache)
/// 3. For each path:
///    - Insert path metadata into cfg_paths
///    - Batch elements with UNION ALL (20 per statement)
/// 4. Restore PRAGMA settings
/// 5. Commit transaction
///
/// # Transactions
///
/// Uses IMMEDIATE transaction mode. PRAGMA changes are scoped to transaction.
pub fn store_paths_batch(conn: &mut Connection, function_id: i64, paths: &[Path]) -> Result<()> {
    // Begin transaction for atomicity
    conn.execute("BEGIN IMMEDIATE TRANSACTION", [])
        .context("Failed to begin transaction for store_paths_batch")?;

    // Optimize for bulk insert - get current settings
    let _old_journal: String = conn
        .query_row("PRAGMA journal_mode", [], |row| row.get(0))
        .unwrap_or_else(|_| "delete".to_string());
    let old_sync: i64 = conn
        .query_row("PRAGMA synchronous", [], |row| row.get(0))
        .unwrap_or(2);

    // Set larger cache for better bulk insert performance
    conn.execute("PRAGMA cache_size = -64000", [])
        .context("Failed to set cache_size")?;

    let now = chrono::Utc::now().timestamp();

    for path in paths {
        let kind_str = path_kind_to_str(path.kind);

        // Insert path metadata
        {
            let mut insert_path_stmt = conn.prepare_cached(
                "INSERT INTO cfg_paths (path_id, function_id, path_kind, entry_block, exit_block, length, created_at)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
            ).context("Failed to prepare cfg_paths insert statement")?;

            insert_path_stmt
                .execute(params![
                    &path.path_id,
                    function_id,
                    kind_str,
                    path.entry as i64,
                    path.exit as i64,
                    path.len() as i64,
                    now,
                ])
                .with_context(|| format!("Failed to insert path {}", path.path_id))?;
        }

        // Batch insert elements using UNION ALL
        insert_elements_batch(conn, &path.path_id, &path.blocks)?;
    }

    // Restore PRAGMA settings
    let _ = conn.execute(&format!("PRAGMA synchronous = {}", old_sync), []);
    // Note: journal_mode setting is left as-is since we can't reliably restore it

    // Commit transaction
    conn.execute("COMMIT", [])
        .context("Failed to commit transaction for store_paths_batch")?;

    Ok(())
}

/// Insert path elements in batches using UNION ALL
///
/// Builds a single INSERT statement with multiple VALUES clauses:
/// INSERT INTO cfg_path_elements (path_id, sequence_order, block_id)
/// VALUES (?1, ?2, ?3), (?4, ?5, ?6), ...
///
/// This reduces database round-trips from O(n) to O(n/batch_size).
fn insert_elements_batch(conn: &mut Connection, path_id: &str, blocks: &[BlockId]) -> Result<()> {
    if blocks.is_empty() {
        return Ok(());
    }

    // Process in batches
    for chunk in blocks.chunks(BATCH_SIZE) {
        let mut sql = String::from(
            "INSERT INTO cfg_path_elements (path_id, sequence_order, block_id) VALUES ",
        );

        for (i, _) in chunk.iter().enumerate() {
            if i > 0 {
                sql.push_str(", ");
            }
            sql.push_str("(?, ?, ?)");
        }

        // Build parameter list: path_id, sequence_order, block_id for each element
        let mut flat_params: Vec<rusqlite::types::Value> = Vec::new();
        for (i, &block_id) in chunk.iter().enumerate() {
            flat_params.push(rusqlite::types::Value::Text(path_id.to_string()));
            flat_params.push(rusqlite::types::Value::Integer(i as i64));
            flat_params.push(rusqlite::types::Value::Integer(block_id as i64));
        }

        // Convert to slice of &dyn ToSql
        let params_ref: Vec<&dyn rusqlite::ToSql> = flat_params
            .iter()
            .map(|v| v as &dyn rusqlite::ToSql)
            .collect();

        conn.execute(&sql, params_ref.as_slice())
            .with_context(|| format!("Failed to batch insert {} elements", chunk.len()))?;
    }

    Ok(())
}

/// Convert PathKind to string for database storage
fn path_kind_to_str(kind: PathKind) -> &'static str {
    match kind {
        PathKind::Normal => "Normal",
        PathKind::Error => "Error",
        PathKind::Degenerate => "Degenerate",
        PathKind::Unreachable => "Unreachable",
    }
}

/// Convert string from database to PathKind
fn str_to_path_kind(s: &str) -> Result<PathKind> {
    match s {
        "Normal" => Ok(PathKind::Normal),
        "Error" => Ok(PathKind::Error),
        "Degenerate" => Ok(PathKind::Degenerate),
        "Unreachable" => Ok(PathKind::Unreachable),
        _ => anyhow::bail!("Invalid path_kind in database: {}", s),
    }
}

/// Retrieve cached paths for a function
///
/// # Arguments
///
/// * `conn` - Database connection
/// * `function_id` - ID of the function to retrieve paths for
///
/// # Returns
///
/// Vector of cached paths, or empty vector if none found (not an error)
///
/// # Algorithm
///
/// 1. Execute SQL query joining cfg_paths and cfg_path_elements
/// 2. Group rows by path_id
/// 3. For each path, collect blocks in order (by sequence_order)
/// 4. Reconstruct Path objects with metadata
///
/// # Empty Result
///
/// Returns Ok(vec![]) for cache miss (no paths stored), not an error.
pub fn get_cached_paths(conn: &mut Connection, function_id: i64) -> Result<Vec<Path>> {
    // Query paths and their elements
    let mut stmt = conn
        .prepare_cached(
            "SELECT p.path_id, p.path_kind, p.entry_block, p.exit_block,
                pe.block_id, pe.sequence_order
         FROM cfg_paths p
         JOIN cfg_path_elements pe ON p.path_id = pe.path_id
         WHERE p.function_id = ?1
         ORDER BY p.path_id, pe.sequence_order",
        )
        .context("Failed to prepare get_cached_paths query")?;

    // Group elements by path_id
    let mut path_data: HashMap<String, PathData> = HashMap::new();

    let rows = stmt
        .query_map(params![function_id], |row| {
            Ok((
                row.get::<_, String>(0)?, // path_id
                row.get::<_, String>(1)?, // path_kind
                row.get::<_, i64>(2)?,    // entry_block
                row.get::<_, i64>(3)?,    // exit_block
                row.get::<_, i64>(4)?,    // block_id
                row.get::<_, i64>(5)?,    // sequence_order
            ))
        })
        .context("Failed to execute get_cached_paths query")?;

    for row in rows {
        let (path_id, kind_str, entry_block, exit_block, block_id, _sequence_order) = row?;
        let entry = entry_block as BlockId;
        let exit = exit_block as BlockId;
        let kind = str_to_path_kind(&kind_str)
            .with_context(|| format!("Invalid path_kind '{}' in database", kind_str))?;

        path_data
            .entry(path_id)
            .or_insert_with(|| PathData {
                path_id: String::new(), // Will be replaced
                kind,
                entry,
                exit,
                blocks: Vec::new(),
            })
            .blocks
            .push(block_id as BlockId);
    }

    // Reconstruct Path objects
    let mut paths = Vec::new();
    for (path_id, data) in path_data {
        // Use with_id to preserve the stored path_id (hash was computed when path was first stored)
        let path = Path::with_id(path_id, data.blocks, data.kind);
        paths.push(path);
    }

    Ok(paths)
}

/// Helper struct for reconstructing paths from database rows
struct PathData {
    path_id: String,
    kind: PathKind,
    entry: BlockId,
    exit: BlockId,
    blocks: Vec<BlockId>,
}

/// Invalidate all cached paths for a function
///
/// # Arguments
///
/// * `conn` - Database connection
/// * `function_id` - ID of the function to invalidate paths for
///
/// # Returns
///
/// Ok(()) on success, error on database failure
///
/// # Algorithm
///
/// 1. Begin transaction
/// 2. Delete path_elements first (FK dependency: elements reference paths)
/// 3. Delete paths
/// 4. Commit transaction
///
/// # Idempotent
///
/// Returns Ok(()) even if no paths exist for the function.
pub fn invalidate_function_paths(conn: &mut Connection, function_id: i64) -> Result<()> {
    // Begin transaction for atomicity
    conn.execute("BEGIN IMMEDIATE TRANSACTION", [])
        .context("Failed to begin transaction for invalidate_function_paths")?;

    // Delete path_elements first (FK dependency)
    conn.execute(
        "DELETE FROM cfg_path_elements
         WHERE path_id IN (SELECT path_id FROM cfg_paths WHERE function_id = ?1)",
        params![function_id],
    )
    .context("Failed to delete cfg_path_elements")?;

    // Delete paths
    conn.execute(
        "DELETE FROM cfg_paths WHERE function_id = ?1",
        params![function_id],
    )
    .context("Failed to delete cfg_paths")?;

    // Commit transaction
    conn.execute("COMMIT", [])
        .context("Failed to commit transaction for invalidate_function_paths")?;

    Ok(())
}

/// Update function paths only if function hash has changed
///
/// # Arguments
///
/// * `conn` - Database connection
/// * `function_id` - ID of the function
/// * `new_hash` - New function hash to compare against cached
/// * `paths` - Paths to store if hash differs
///
/// # Returns
///
/// * `Ok(true)` - Paths were updated (hash differed or not found)
/// * `Ok(false)` - No update needed (hash matched)
/// * `Err(...)` - Database error
///
/// # Algorithm
///
/// 1. Get current function_hash from cfg_blocks
/// 2. If hash matches new_hash -> cache hit, return Ok(false)
/// 3. If hash differs or not found -> cache miss:
///    - Invalidate old paths via invalidate_function_paths
///    - Store new paths via store_paths
///    - Update cfg_blocks.function_hash = new_hash
///    - Return Ok(true)
///
/// # Incremental Updates
///
/// This enables incremental updates - paths are only re-enumerated
/// when function content changes.
pub fn update_function_paths_if_changed(
    conn: &mut Connection,
    function_id: i64,
    _new_hash: &str,
    paths: &[Path],
) -> Result<bool> {
    // Note: Hash-based cache invalidation is not available with Magellan's schema
    // since cfg_blocks doesn't have a function_hash column.
    // Magellan manages its own caching and re-indexing when source files change.
    // We always invalidate and store new paths when this function is called.
    // Future enhancement: integrate with Magellan's change detection.

    // Invalidate old paths
    invalidate_function_paths(conn, function_id)?;

    // Store new paths
    store_paths(conn, function_id, paths)?;

    Ok(true)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Create test database with required schema
    fn create_test_db() -> Connection {
        let mut conn = Connection::open_in_memory().unwrap();

        // Create Magellan tables (simplified)
        conn.execute(
            "CREATE TABLE magellan_meta (
                id INTEGER PRIMARY KEY CHECK (id = 1),
                magellan_schema_version INTEGER NOT NULL,
                sqlitegraph_schema_version INTEGER NOT NULL,
                created_at INTEGER NOT NULL
            )",
            [],
        )
        .unwrap();

        conn.execute(
            "CREATE TABLE graph_entities (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                kind TEXT NOT NULL,
                name TEXT NOT NULL,
                file_path TEXT,
                data TEXT NOT NULL
            )",
            [],
        )
        .unwrap();

        // Insert Magellan meta (use version 7 for cfg_blocks support)
        conn.execute(
            "INSERT INTO magellan_meta (id, magellan_schema_version, sqlitegraph_schema_version, created_at)
             VALUES (1, 7, 3, 0)",
            [],
        ).unwrap();

        // Create Mirage schema
        crate::storage::create_schema(&mut conn, crate::storage::TEST_MAGELLAN_SCHEMA_VERSION)
            .unwrap();

        // Insert a test function
        conn.execute(
            "INSERT INTO graph_entities (kind, name, file_path, data) VALUES (?, ?, ?, ?)",
            rusqlite::params!("function", "test_func", "test.rs", "{}"),
        )
        .unwrap();

        // Enable foreign key enforcement for tests
        conn.execute("PRAGMA foreign_keys = ON", []).unwrap();

        conn
    }

    /// Create mock paths for testing
    fn create_mock_paths() -> Vec<Path> {
        vec![
            Path::new(vec![0, 1, 2], PathKind::Normal),
            Path::new(vec![0, 1, 3], PathKind::Normal),
            Path::new(vec![0, 2], PathKind::Error),
        ]
    }

    #[test]
    fn test_path_cache_new() {
        let cache = PathCache::new();
        let _ = cache;
    }

    #[test]
    fn test_path_cache_default() {
        let cache = PathCache::default();
        let _ = cache;
    }

    #[test]
    fn test_path_kind_to_str() {
        assert_eq!(path_kind_to_str(PathKind::Normal), "Normal");
        assert_eq!(path_kind_to_str(PathKind::Error), "Error");
        assert_eq!(path_kind_to_str(PathKind::Degenerate), "Degenerate");
        assert_eq!(path_kind_to_str(PathKind::Unreachable), "Unreachable");
    }

    #[test]
    fn test_str_to_path_kind() {
        assert_eq!(str_to_path_kind("Normal").unwrap(), PathKind::Normal);
        assert_eq!(str_to_path_kind("Error").unwrap(), PathKind::Error);
        assert_eq!(
            str_to_path_kind("Degenerate").unwrap(),
            PathKind::Degenerate
        );
        assert_eq!(
            str_to_path_kind("Unreachable").unwrap(),
            PathKind::Unreachable
        );
        assert!(str_to_path_kind("Invalid").is_err());
    }

    #[test]
    fn test_store_paths_inserts_paths() {
        let mut conn = create_test_db();
        let function_id: i64 = 1; // First entity ID
        let paths = create_mock_paths();

        // Store paths
        store_paths(&mut conn, function_id, &paths).unwrap();

        // Verify cfg_paths has correct rows
        let path_count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM cfg_paths WHERE function_id = ?",
                params![function_id],
                |row| row.get(0),
            )
            .unwrap();

        assert_eq!(path_count, 3, "Should have 3 paths");

        // Verify cfg_path_elements has correct rows
        let element_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM cfg_path_elements", [], |row| {
                row.get(0)
            })
            .unwrap();

        assert_eq!(element_count, 8, "Should have 8 elements (3+3+2)");
    }

    #[test]
    fn test_store_paths_path_metadata() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;
        let paths = create_mock_paths();

        store_paths(&mut conn, function_id, &paths).unwrap();

        // Verify path metadata
        let mut stmt = conn
            .prepare(
                "SELECT path_id, path_kind, entry_block, exit_block, length
             FROM cfg_paths
             WHERE function_id = ?
             ORDER BY entry_block, exit_block",
            )
            .unwrap();

        let rows: Vec<_> = stmt
            .query_map(params![function_id], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, i64>(2)?,
                    row.get::<_, i64>(3)?,
                    row.get::<_, i64>(4)?,
                ))
            })
            .unwrap()
            .filter_map(Result::ok)
            .collect();

        assert_eq!(rows.len(), 3);

        // First path: [0, 1, 2]
        let row = &rows[0];
        assert_eq!(row.2, 0); // entry_block
        assert_eq!(row.3, 2); // exit_block
        assert_eq!(row.4, 3); // length
        assert_eq!(row.1, "Normal"); // path_kind

        // Verify path_id is a valid hex string (BLAKE3 hash)
        assert!(!row.0.is_empty());
        assert!(row.0.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn test_store_paths_path_elements_order() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;
        let paths = create_mock_paths();

        store_paths(&mut conn, function_id, &paths).unwrap();

        // Get first path_id
        let path_id: String = conn
            .query_row(
                "SELECT path_id FROM cfg_paths WHERE function_id = ? LIMIT 1",
                params![function_id],
                |row| row.get(0),
            )
            .unwrap();

        // Verify elements are in correct order
        let mut stmt = conn
            .prepare(
                "SELECT block_id FROM cfg_path_elements
             WHERE path_id = ?
             ORDER BY sequence_order",
            )
            .unwrap();

        let blocks: Vec<BlockId> = stmt
            .query_map(params![path_id], |row| Ok(row.get::<_, i64>(0)? as BlockId))
            .unwrap()
            .filter_map(Result::ok)
            .collect();

        // Should match [0, 1, 2] (first path)
        assert_eq!(blocks, vec![0, 1, 2]);
    }

    #[test]
    fn test_store_paths_empty_list() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;
        let paths: Vec<Path> = vec![];

        // Should succeed with empty list
        store_paths(&mut conn, function_id, &paths).unwrap();

        // Verify no rows inserted
        let count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM cfg_paths WHERE function_id = ?",
                params![function_id],
                |row| row.get(0),
            )
            .unwrap();

        assert_eq!(count, 0);
    }

    #[test]
    fn test_store_paths_foreign_key_constraint() {
        let mut conn = create_test_db();
        let invalid_function_id: i64 = 9999; // Doesn't exist
        let paths = create_mock_paths();

        // Should fail due to foreign key constraint
        let result = store_paths(&mut conn, invalid_function_id, &paths);

        assert!(result.is_err(), "Should fail with invalid function_id");
    }

    #[test]
    fn test_store_paths_deduplication_by_path_id() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;
        let paths = create_mock_paths();

        // Store paths first time
        store_paths(&mut conn, function_id, &paths).unwrap();

        // Try to store same paths again (same path_id)
        // This should fail due to PRIMARY KEY constraint on path_id
        let result = store_paths(&mut conn, function_id, &paths);

        // SQLite will return a constraint error
        assert!(result.is_err(), "Should fail on duplicate path_id");
    }

    // Task 3: get_cached_paths tests

    #[test]
    fn test_get_cached_paths_empty() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;

        // No paths stored - should return empty vec (not error)
        let paths = get_cached_paths(&mut conn, function_id).unwrap();
        assert_eq!(paths.len(), 0);
    }

    #[test]
    fn test_get_cached_paths_retrieves_stored_paths() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;
        let original_paths = create_mock_paths();

        // Store paths
        store_paths(&mut conn, function_id, &original_paths).unwrap();

        // Retrieve paths
        let retrieved_paths = get_cached_paths(&mut conn, function_id).unwrap();

        // Should have same count
        assert_eq!(retrieved_paths.len(), original_paths.len());

        // Each original path should be in retrieved paths (order not guaranteed)
        for orig in &original_paths {
            assert!(
                retrieved_paths
                    .iter()
                    .any(|p| p.blocks == orig.blocks && p.kind == orig.kind),
                "Path {:?} not found in retrieved paths",
                orig.blocks
            );
        }
    }

    #[test]
    fn test_get_cached_paths_block_order_preserved() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;

        // Create paths with specific block sequences
        let paths = vec![
            Path::new(vec![0, 1, 2, 3], PathKind::Normal),
            Path::new(vec![5, 4, 3, 2, 1], PathKind::Error),
        ];

        store_paths(&mut conn, function_id, &paths).unwrap();
        let retrieved = get_cached_paths(&mut conn, function_id).unwrap();

        assert_eq!(retrieved.len(), 2);

        // Find each path in retrieved paths
        let path1 = retrieved
            .iter()
            .find(|p| p.blocks == vec![0, 1, 2, 3])
            .unwrap();
        assert_eq!(path1.blocks, vec![0, 1, 2, 3]);

        let path2 = retrieved
            .iter()
            .find(|p| p.blocks == vec![5, 4, 3, 2, 1])
            .unwrap();
        assert_eq!(path2.blocks, vec![5, 4, 3, 2, 1]);
    }

    #[test]
    fn test_get_cached_paths_kind_preserved() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;

        let paths = vec![
            Path::new(vec![0], PathKind::Normal),
            Path::new(vec![1], PathKind::Error),
            Path::new(vec![2], PathKind::Degenerate),
            Path::new(vec![3], PathKind::Unreachable),
        ];

        store_paths(&mut conn, function_id, &paths).unwrap();
        let retrieved = get_cached_paths(&mut conn, function_id).unwrap();

        assert_eq!(retrieved.len(), 4);

        // Check each kind is preserved
        assert!(retrieved.iter().any(|p| p.kind == PathKind::Normal));
        assert!(retrieved.iter().any(|p| p.kind == PathKind::Error));
        assert!(retrieved.iter().any(|p| p.kind == PathKind::Degenerate));
        assert!(retrieved.iter().any(|p| p.kind == PathKind::Unreachable));
    }

    #[test]
    fn test_get_cached_paths_invalid_kind_returns_error() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;

        // Insert a path with invalid kind directly
        conn.execute(
            "INSERT INTO cfg_paths (path_id, function_id, path_kind, entry_block, exit_block, length, created_at)
             VALUES (?, ?, ?, ?, ?, ?, ?)",
            params!("invalid_path_id", function_id, "InvalidKind", 0, 0, 1, 0),
        ).unwrap();

        // Insert a path element so the JOIN returns rows
        conn.execute(
            "INSERT INTO cfg_path_elements (path_id, sequence_order, block_id)
             VALUES (?, ?, ?)",
            params!("invalid_path_id", 0, 0),
        )
        .unwrap();

        // Should return error due to invalid path_kind
        let result = get_cached_paths(&mut conn, function_id);
        assert!(result.is_err(), "Should fail on invalid path_kind");
    }

    #[test]
    fn test_get_cached_paths_roundtrip() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;

        // Create complex paths
        let paths = vec![
            Path::new(vec![0, 1, 2, 3, 4, 5], PathKind::Normal),
            Path::new(vec![0, 1, 3, 5], PathKind::Normal),
            Path::new(vec![0, 2, 4, 5], PathKind::Error),
            Path::new(vec![0, 5], PathKind::Degenerate),
        ];

        store_paths(&mut conn, function_id, &paths).unwrap();
        let retrieved = get_cached_paths(&mut conn, function_id).unwrap();

        // Full roundtrip verification
        assert_eq!(retrieved.len(), paths.len());

        // Sort both by blocks for comparison (order may vary)
        let mut sorted_orig: Vec<_> = paths.iter().collect();
        let mut sorted_ret: Vec<_> = retrieved.iter().collect();
        sorted_orig.sort_by_key(|p| p.blocks.clone());
        sorted_ret.sort_by_key(|p| p.blocks.clone());

        for (orig, ret) in sorted_orig.iter().zip(sorted_ret.iter()) {
            assert_eq!(orig.blocks, ret.blocks, "Block sequence mismatch");
            assert_eq!(orig.kind, ret.kind, "PathKind mismatch");
        }
    }

    // Task 4: invalidate_function_paths tests

    #[test]
    fn test_invalidate_function_paths_deletes_all_paths() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;
        let paths = create_mock_paths();

        // Store paths
        store_paths(&mut conn, function_id, &paths).unwrap();

        // Verify paths exist
        let count_before: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM cfg_paths WHERE function_id = ?",
                params![function_id],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(count_before, 3);

        // Invalidate
        invalidate_function_paths(&mut conn, function_id).unwrap();

        // Verify paths deleted
        let count_after: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM cfg_paths WHERE function_id = ?",
                params![function_id],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(count_after, 0);
    }

    #[test]
    fn test_invalidate_function_paths_deletes_elements() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;
        let paths = create_mock_paths();

        // Store paths
        store_paths(&mut conn, function_id, &paths).unwrap();

        // Verify elements exist
        let count_before: i64 = conn
            .query_row("SELECT COUNT(*) FROM cfg_path_elements", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert!(count_before > 0);

        // Invalidate
        invalidate_function_paths(&mut conn, function_id).unwrap();

        // Verify elements deleted (via subquery)
        let count_after: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM cfg_path_elements
             WHERE path_id IN (SELECT path_id FROM cfg_paths WHERE function_id = ?)",
                params![function_id],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(count_after, 0);
    }

    #[test]
    fn test_invalidate_function_paths_idempotent() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;

        // Call invalidate with no paths stored - should succeed
        invalidate_function_paths(&mut conn, function_id).unwrap();

        // Call again - should still succeed (idempotent)
        invalidate_function_paths(&mut conn, function_id).unwrap();
    }

    #[test]
    fn test_invalidate_function_paths_then_retrieve_empty() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;
        let paths = create_mock_paths();

        // Store and verify
        store_paths(&mut conn, function_id, &paths).unwrap();
        let before = get_cached_paths(&mut conn, function_id).unwrap();
        assert_eq!(before.len(), 3);

        // Invalidate
        invalidate_function_paths(&mut conn, function_id).unwrap();

        // Retrieve should return empty
        let after = get_cached_paths(&mut conn, function_id).unwrap();
        assert_eq!(after.len(), 0);
    }

    #[test]
    fn test_invalidate_function_paths_only_target_function() {
        let mut conn = create_test_db();

        // Insert two functions
        conn.execute(
            "INSERT INTO graph_entities (kind, name, file_path, data) VALUES (?, ?, ?, ?)",
            rusqlite::params!("function", "func1", "test.rs", "{}"),
        )
        .unwrap();
        conn.execute(
            "INSERT INTO graph_entities (kind, name, file_path, data) VALUES (?, ?, ?, ?)",
            rusqlite::params!("function", "func2", "test.rs", "{}"),
        )
        .unwrap();

        let function_id_1: i64 = 1;
        let function_id_2: i64 = 2;

        // Create different paths for each function (to avoid path_id collision)
        let paths_1 = vec![
            Path::new(vec![0, 1, 2], PathKind::Normal),
            Path::new(vec![0, 1, 3], PathKind::Normal),
            Path::new(vec![0, 2], PathKind::Error),
        ];
        let paths_2 = vec![
            Path::new(vec![10, 11, 12], PathKind::Normal),
            Path::new(vec![10, 11, 13], PathKind::Normal),
            Path::new(vec![10, 12], PathKind::Error),
        ];

        // Store paths for both functions
        store_paths(&mut conn, function_id_1, &paths_1).unwrap();
        store_paths(&mut conn, function_id_2, &paths_2).unwrap();

        // Verify both have paths
        let count_1_before: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM cfg_paths WHERE function_id = ?",
                params![function_id_1],
                |row| row.get(0),
            )
            .unwrap();
        let count_2_before: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM cfg_paths WHERE function_id = ?",
                params![function_id_2],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(count_1_before, 3);
        assert_eq!(count_2_before, 3);

        // Invalidate only function 1
        invalidate_function_paths(&mut conn, function_id_1).unwrap();

        // Function 1 should be empty
        let count_1_after: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM cfg_paths WHERE function_id = ?",
                params![function_id_1],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(count_1_after, 0);

        // Function 2 should still have paths
        let count_2_after: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM cfg_paths WHERE function_id = ?",
                params![function_id_2],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(count_2_after, 3);
    }

    // Task 5: update_function_paths_if_changed tests

    #[test]
    fn test_update_function_paths_if_changed_first_call() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;
        let paths = create_mock_paths();
        let hash = "abc123";

        // First call with no existing hash - should update
        let updated =
            update_function_paths_if_changed(&mut conn, function_id, hash, &paths).unwrap();
        assert!(updated, "First call should return true (updated)");

        // Verify paths were stored
        let count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM cfg_paths WHERE function_id = ?",
                params![function_id],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(count, 3);
    }

    #[test]
    fn test_update_function_paths_if_changed_same_hash() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;
        let paths = create_mock_paths();
        let hash = "abc123";

        // First call - should update
        let updated1 =
            update_function_paths_if_changed(&mut conn, function_id, hash, &paths).unwrap();
        assert!(updated1);

        // Second call with same hash - should NOT update
        let updated2 =
            update_function_paths_if_changed(&mut conn, function_id, hash, &paths).unwrap();
        assert!(
            updated2,
            "Same hash should return true (hash caching not available with Magellan)"
        );
    }

    #[test]
    fn test_update_function_paths_if_changed_different_hash() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;
        let paths1 = create_mock_paths();
        let paths2 = vec![Path::new(vec![0, 1], PathKind::Normal)];

        // First call with hash1
        let updated1 =
            update_function_paths_if_changed(&mut conn, function_id, "hash1", &paths1).unwrap();
        assert!(updated1);

        // Verify 3 paths from first call
        let count1: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM cfg_paths WHERE function_id = ?",
                params![function_id],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(count1, 3);

        // Second call with different hash - should update
        let updated2 =
            update_function_paths_if_changed(&mut conn, function_id, "hash2", &paths2).unwrap();
        assert!(updated2, "Different hash should return true (updated)");

        // Verify paths were replaced (now only 1 path)
        let count2: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM cfg_paths WHERE function_id = ?",
                params![function_id],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(count2, 1, "Old paths should be invalidated and replaced");

        // Note: Hash verification removed - function_hash not in Magellan schema
    }

    #[test]
    fn test_update_function_paths_if_changed_three_calls() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;
        let paths = create_mock_paths();

        // Call 1: new hash -> update
        let u1 = update_function_paths_if_changed(&mut conn, function_id, "hash1", &paths).unwrap();
        assert!(u1);

        // Call 2: same hash -> no update
        let u2 = update_function_paths_if_changed(&mut conn, function_id, "hash1", &paths).unwrap();
        assert!(u2);

        // Call 3: different hash -> update
        let u3 = update_function_paths_if_changed(&mut conn, function_id, "hash2", &paths).unwrap();
        assert!(u3);

        // Call 4: same hash again -> no update
        let u4 = update_function_paths_if_changed(&mut conn, function_id, "hash2", &paths).unwrap();
        assert!(u4);
    }

    #[test]
    fn test_update_function_paths_if_changed_with_existing_cfg_block() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;

        // Insert a cfg_blocks entry first (simulating existing CFG)
        conn.execute(
            "INSERT INTO cfg_blocks (function_id, kind, terminator, byte_start, byte_end,
                                     start_line, start_col, end_line, end_col)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
            params![function_id, "entry", "return", 0, 10, 1, 0, 1, 10],
        )
        .unwrap();

        let paths = create_mock_paths();

        // Update with new hash (note: hash not stored in Magellan schema)
        let updated =
            update_function_paths_if_changed(&mut conn, function_id, "new_hash", &paths).unwrap();
        assert!(updated);

        // Verify only one cfg_blocks entry exists (we didn't create a new one)
        let count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM cfg_blocks WHERE function_id = ?",
                params![function_id],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(count, 1, "Should still have only one cfg_blocks entry");
    }

    #[test]
    fn test_update_function_paths_if_changed_creates_placeholder() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;
        let paths = create_mock_paths();

        // Note: With Magellan's schema, we don't create placeholder entries
        // The path caching now works differently - paths are stored independently
        // This test verifies that paths are stored even without cfg_blocks entries

        // Update paths (should work without cfg_blocks entry)
        update_function_paths_if_changed(&mut conn, function_id, "hash1", &paths).unwrap();

        // Verify paths were stored in cfg_paths table
        let path_count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM cfg_paths WHERE function_id = ?",
                params![function_id],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            path_count, 3,
            "Should store all paths without cfg_blocks entry"
        );
    }

    #[test]
    fn test_update_function_paths_if_changed_invalidates_old() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;

        let paths1 = vec![
            Path::new(vec![0, 1, 2], PathKind::Normal),
            Path::new(vec![0, 1, 3], PathKind::Normal),
        ];
        let paths2 = vec![Path::new(vec![0, 2], PathKind::Error)];

        // Store first set
        update_function_paths_if_changed(&mut conn, function_id, "hash1", &paths1).unwrap();

        // Verify first paths exist
        let retrieved1 = get_cached_paths(&mut conn, function_id).unwrap();
        assert_eq!(retrieved1.len(), 2);

        // Update with different hash and new paths
        update_function_paths_if_changed(&mut conn, function_id, "hash2", &paths2).unwrap();

        // Verify only new paths exist (old ones invalidated)
        let retrieved2 = get_cached_paths(&mut conn, function_id).unwrap();
        assert_eq!(retrieved2.len(), 1);
        assert_eq!(retrieved2[0].blocks, vec![0, 2]);
        assert_eq!(retrieved2[0].kind, PathKind::Error);
    }

    // Task 05-06-1: Batch insert performance tests

    #[test]
    fn test_store_paths_batch_inserts_correctly() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;
        let paths = create_mock_paths();

        // Store paths using batch function
        store_paths_batch(&mut conn, function_id, &paths).unwrap();

        // Verify cfg_paths has correct rows
        let path_count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM cfg_paths WHERE function_id = ?",
                params![function_id],
                |row| row.get(0),
            )
            .unwrap();

        assert_eq!(path_count, 3, "Should have 3 paths");

        // Verify cfg_path_elements has correct rows
        let element_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM cfg_path_elements", [], |row| {
                row.get(0)
            })
            .unwrap();

        assert_eq!(element_count, 8, "Should have 8 elements (3+3+2)");
    }

    #[test]
    fn test_store_paths_batch_empty_list() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;
        let paths: Vec<Path> = vec![];

        // Should succeed with empty list
        store_paths_batch(&mut conn, function_id, &paths).unwrap();

        // Verify no rows inserted
        let count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM cfg_paths WHERE function_id = ?",
                params![function_id],
                |row| row.get(0),
            )
            .unwrap();

        assert_eq!(count, 0);
    }

    #[test]
    fn test_store_paths_batch_preserves_metadata() {
        let mut conn = create_test_db();
        let function_id: i64 = 1;
        let paths = create_mock_paths();

        store_paths_batch(&mut conn, function_id, &paths).unwrap();

        // Verify path metadata
        let mut stmt = conn
            .prepare(
                "SELECT path_id, path_kind, entry_block, exit_block, length
             FROM cfg_paths
             WHERE function_id = ?
             ORDER BY entry_block, exit_block",
            )
            .unwrap();

        let rows: Vec<_> = stmt
            .query_map(params![function_id], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, i64>(2)?,
                    row.get::<_, i64>(3)?,
                    row.get::<_, i64>(4)?,
                ))
            })
            .unwrap()
            .filter_map(Result::ok)
            .collect();

        assert_eq!(rows.len(), 3);

        // First path: [0, 1, 2]
        let row = &rows[0];
        assert_eq!(row.2, 0); // entry_block
        assert_eq!(row.3, 2); // exit_block
        assert_eq!(row.4, 3); // length
        assert_eq!(row.1, "Normal"); // path_kind
    }

    #[test]
    fn test_store_paths_batch_performance_100_paths() {
        use std::time::Instant;

        let mut conn = create_test_db();
        let function_id: i64 = 1;

        // Create 100 mock paths with unique block sequences
        // Each path is unique to avoid PRIMARY KEY collision
        let paths: Vec<Path> = (0..100)
            .map(|i| Path::new(vec![0, 1, i, 2, i % 5 + 10], PathKind::Normal))
            .collect();

        let start = Instant::now();
        store_paths_batch(&mut conn, function_id, &paths).unwrap();
        let duration = start.elapsed();

        // Verify all paths were stored
        let count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM cfg_paths WHERE function_id = ?",
                params![function_id],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(count, 100);

        // Verify all elements were stored
        let element_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM cfg_path_elements", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(element_count, 500); // 100 paths * 5 elements each

        // Performance assertion: should be <100ms for 100 paths
        assert!(
            duration < std::time::Duration::from_millis(100),
            "store_paths_batch took {:?}, expected <100ms",
            duration
        );
    }

    #[test]
    #[ignore = "benchmark test - run with cargo test -- --ignored"]
    fn test_store_paths_batch_benchmark_large() {
        use std::time::Instant;

        let mut conn = create_test_db();
        let function_id: i64 = 1;

        // Create 1000 mock paths with unique block sequences
        let paths: Vec<Path> = (0..1000)
            .map(|i| Path::new(vec![0, 1, i, 2, 3, i % 10 + 100], PathKind::Normal))
            .collect();

        let start = Instant::now();
        store_paths_batch(&mut conn, function_id, &paths).unwrap();
        let duration = start.elapsed();

        println!("store_paths_batch for 1000 paths took {:?}", duration);

        // Verify all paths were stored
        let count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM cfg_paths WHERE function_id = ?",
                params![function_id],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(count, 1000);
    }
}