rhei 1.5.0

Lightweight serverless HTAP engine — Rusqlite (OLTP) + DuckDB/DataFusion (OLAP) with CDC replication
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
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
//! Integration tests for the Rhei HTAP engine.
//!
//! These tests exercise the full OLTP -> CDC -> Sync -> OLAP pipeline
//! using a temporary database.

use std::sync::Arc;

use arrow::datatypes::{DataType, Field, Schema};
use tempfile::TempDir;

use rhei::{HtapConfig, HtapEngine, OlapEngine, TableSchema};

/// Helper: define a simple `users` table schema.
fn users_schema() -> TableSchema {
    TableSchema::new(
        "users",
        Arc::new(Schema::new(vec![
            Field::new("id", DataType::Int64, false),
            Field::new("name", DataType::Utf8, true),
            Field::new("age", DataType::Int64, true),
        ])),
        vec!["id".to_string()],
    )
}

/// 2-column users schema (used as starting point for add_column tests).
fn users_two_col_schema() -> TableSchema {
    TableSchema::new(
        "users",
        Arc::new(Schema::new(vec![
            Field::new("id", DataType::Int64, false),
            Field::new("name", DataType::Utf8, true),
        ])),
        vec!["id".to_string()],
    )
}

/// orders table schema for initial_sync_all tests.
fn orders_schema() -> TableSchema {
    TableSchema::new(
        "orders",
        Arc::new(Schema::new(vec![
            Field::new("id", DataType::Int64, false),
            Field::new("user_id", DataType::Int64, true),
            Field::new("total", DataType::Int64, true),
        ])),
        vec!["id".to_string()],
    )
}

/// Helper: query OLAP `SELECT COUNT(*) FROM <table>` and return the count.
async fn olap_count(engine: &HtapEngine, table: &str) -> i64 {
    let batches = engine
        .olap()
        .query(&format!("SELECT COUNT(*) FROM {table}"))
        .await
        .unwrap();
    batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::Int64Array>()
        .unwrap()
        .value(0)
}

// ---------------------------------------------------------------------------
// Shared backend tests — generated once per OLAP backend via macro
// ---------------------------------------------------------------------------

/// Generate the shared backend tests for a given module / engine constructor.
macro_rules! backend_tests {
    ($mod_name:ident, $make_engine:ident) => {
        mod $mod_name {
            use super::*;
            use std::time::Duration;
            use rhei::OltpEngine;

            #[tokio::test]
            async fn full_htap_pipeline() {
                let tmp = TempDir::new().unwrap();
                let engine = $make_engine(&tmp).await;

                engine
                    .execute(
                        "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                        &[],
                    )
                    .await
                    .unwrap();

                engine.register_table(users_schema()).await.unwrap();

                engine
                    .execute("INSERT INTO users VALUES (1, 'Alice', 30)", &[])
                    .await
                    .unwrap();
                engine
                    .execute("INSERT INTO users VALUES (2, 'Bob', 25)", &[])
                    .await
                    .unwrap();
                engine
                    .execute("INSERT INTO users VALUES (3, 'Charlie', 35)", &[])
                    .await
                    .unwrap();

                let sync_result = engine.sync_now().await.unwrap();
                assert_eq!(sync_result.events_processed, 3);
                assert_eq!(sync_result.rows_inserted, 3);
                assert_eq!(sync_result.rows_updated, 0);
                assert_eq!(sync_result.rows_deleted, 0);

                let olap_batches = engine
                    .olap()
                    .query("SELECT COUNT(*) FROM users")
                    .await
                    .unwrap();
                assert_eq!(olap_batches.len(), 1);
                let count = olap_count(&engine, "users").await;
                assert_eq!(count, 3);

                let status = engine.sync_status().await.unwrap();
                assert_eq!(status.lag, 0);
            }

            #[tokio::test]
            async fn update_and_delete_sync() {
                let tmp = TempDir::new().unwrap();
                let engine = $make_engine(&tmp).await;

                engine
                    .execute(
                        "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                        &[],
                    )
                    .await
                    .unwrap();
                engine.register_table(users_schema()).await.unwrap();

                // Insert
                engine
                    .execute("INSERT INTO users VALUES (1, 'Alice', 30)", &[])
                    .await
                    .unwrap();
                engine.sync_now().await.unwrap();

                // Update
                engine
                    .execute("UPDATE users SET age = 31 WHERE id = 1", &[])
                    .await
                    .unwrap();
                let sync_result = engine.sync_now().await.unwrap();
                assert_eq!(sync_result.rows_updated, 1);

                // Delete
                engine
                    .execute("DELETE FROM users WHERE id = 1", &[])
                    .await
                    .unwrap();
                let sync_result = engine.sync_now().await.unwrap();
                assert_eq!(sync_result.rows_deleted, 1);
            }

            #[tokio::test]
            async fn query_routing() {
                let tmp = TempDir::new().unwrap();
                let engine = $make_engine(&tmp).await;

                engine
                    .execute(
                        "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                        &[],
                    )
                    .await
                    .unwrap();
                engine.register_table(users_schema()).await.unwrap();

                engine
                    .execute("INSERT INTO users VALUES (1, 'Alice', 30)", &[])
                    .await
                    .unwrap();
                engine
                    .execute("INSERT INTO users VALUES (2, 'Bob', 25)", &[])
                    .await
                    .unwrap();
                engine.sync_now().await.unwrap();

                // Simple SELECT with WHERE should route to OLTP
                let result = engine
                    .query("SELECT * FROM users WHERE id = 1")
                    .await
                    .unwrap();
                assert_eq!(result.len(), 1);

                // Aggregate query should route to OLAP
                let result = engine.query("SELECT COUNT(*) FROM users").await.unwrap();
                assert_eq!(result.len(), 1);

                // Force OLAP hint
                let result = engine
                    .query_with_hint("SELECT * FROM users", rhei::QueryHint::ForceOlap)
                    .await
                    .unwrap();
                assert_eq!(result.len(), 1);
                let total_rows: usize = result.iter().map(|b| b.num_rows()).sum();
                assert_eq!(total_rows, 2);
            }

            #[tokio::test]
            async fn initial_sync() {
                let tmp = TempDir::new().unwrap();
                let engine = $make_engine(&tmp).await;

                engine
                    .execute(
                        "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                        &[],
                    )
                    .await
                    .unwrap();

                // Insert 3 rows BEFORE register_table — no CDC triggers yet
                engine
                    .execute("INSERT INTO users VALUES (1, 'Alice', 30)", &[])
                    .await
                    .unwrap();
                engine
                    .execute("INSERT INTO users VALUES (2, 'Bob', 25)", &[])
                    .await
                    .unwrap();
                engine
                    .execute("INSERT INTO users VALUES (3, 'Charlie', 35)", &[])
                    .await
                    .unwrap();

                // register_table creates an empty OLAP mirror but does not copy data
                engine.register_table(users_schema()).await.unwrap();

                let count = olap_count(&engine, "users").await;
                assert_eq!(count, 0, "OLAP should be empty before initial_sync");

                // Bulk-load existing OLTP rows into OLAP
                let rows = engine.initial_sync("users").await.unwrap();
                assert_eq!(rows, 3);

                let count = olap_count(&engine, "users").await;
                assert_eq!(count, 3, "OLAP should have 3 rows after initial_sync");

                // CDC log is empty — rows were inserted before triggers were set up
                let cdc_batches = engine
                    .oltp()
                    .unwrap()
                    .query("SELECT COUNT(*) FROM _rhei_cdc_log", &[])
                    .await
                    .unwrap();
                let cdc_count = cdc_batches[0]
                    .column(0)
                    .as_any()
                    .downcast_ref::<arrow::array::Int64Array>()
                    .unwrap()
                    .value(0);
                assert_eq!(
                    cdc_count, 0,
                    "CDC log should be empty — initial_sync bypasses CDC"
                );
            }

            #[tokio::test]
            async fn add_column() {
                let tmp = TempDir::new().unwrap();
                let engine = $make_engine(&tmp).await;

                engine
                    .execute(
                        "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)",
                        &[],
                    )
                    .await
                    .unwrap();
                engine.register_table(users_two_col_schema()).await.unwrap();

                engine
                    .execute("INSERT INTO users VALUES (1, 'Alice')", &[])
                    .await
                    .unwrap();
                engine.sync_now().await.unwrap();

                // Alter OLTP schema first, then propagate to registry + OLAP + CDC triggers
                engine
                    .execute("ALTER TABLE users ADD COLUMN age INTEGER", &[])
                    .await
                    .unwrap();
                engine
                    .add_column("users", "age", DataType::Int64)
                    .await
                    .unwrap();

                assert_eq!(
                    engine
                        .schema_registry()
                        .get("users")
                        .unwrap()
                        .arrow_schema
                        .fields()
                        .len(),
                    3,
                    "schema registry should have 3 fields after add_column"
                );

                // Insert a row that includes the new column
                engine
                    .execute("INSERT INTO users VALUES (2, 'Bob', 30)", &[])
                    .await
                    .unwrap();
                let sync_result = engine.sync_now().await.unwrap();
                assert_eq!(sync_result.rows_inserted, 1);

                // OLAP result should include the new `age` column
                let batches = engine
                    .olap()
                    .query("SELECT age FROM users WHERE id = 2")
                    .await
                    .unwrap();
                let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
                assert_eq!(total_rows, 1);
                assert!(
                    batches[0].schema().index_of("age").is_ok(),
                    "OLAP result should include the new 'age' column"
                );
            }

            #[tokio::test]
            async fn drop_column() {
                let tmp = TempDir::new().unwrap();
                let engine = $make_engine(&tmp).await;

                engine
                    .execute(
                        "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                        &[],
                    )
                    .await
                    .unwrap();
                engine.register_table(users_schema()).await.unwrap();

                engine
                    .execute("INSERT INTO users VALUES (1, 'Alice', 30)", &[])
                    .await
                    .unwrap();
                engine.sync_now().await.unwrap();

                // drop_column handles the OLTP ALTER TABLE internally (SQLite rejects
                // DROP COLUMN while CDC triggers reference the column, so teardown must
                // happen first inside drop_column).
                engine.drop_column("users", "age").await.unwrap();

                assert_eq!(
                    engine
                        .schema_registry()
                        .get("users")
                        .unwrap()
                        .arrow_schema
                        .fields()
                        .len(),
                    2,
                    "schema registry should have 2 fields after drop_column"
                );

                // Insert a row without the dropped column
                engine
                    .execute("INSERT INTO users VALUES (2, 'Bob')", &[])
                    .await
                    .unwrap();
                let sync_result = engine.sync_now().await.unwrap();
                assert_eq!(sync_result.rows_inserted, 1);

                // OLAP result should NOT contain the dropped `age` column
                let batches = engine
                    .olap()
                    .query("SELECT * FROM users WHERE id = 2")
                    .await
                    .unwrap();
                let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
                assert_eq!(total_rows, 1);
                assert!(
                    batches[0].schema().index_of("age").is_err(),
                    "OLAP result should not include the dropped 'age' column"
                );

                // Attempting to drop a PK column must fail
                assert!(
                    engine.drop_column("users", "id").await.is_err(),
                    "dropping a PK column should return an error"
                );
            }

            #[tokio::test]
            async fn batch_insert_sync() {
                let tmp = TempDir::new().unwrap();
                let engine = $make_engine(&tmp).await;

                engine
                    .execute(
                        "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                        &[],
                    )
                    .await
                    .unwrap();
                engine.register_table(users_schema()).await.unwrap();

                for i in 1..=5 {
                    engine
                        .execute(
                            &format!("INSERT INTO users VALUES ({i}, 'User{i}', {})", 20 + i),
                            &[],
                        )
                        .await
                        .unwrap();
                }

                let result = engine.sync_now().await.unwrap();
                assert_eq!(result.events_processed, 5);
                assert_eq!(result.rows_inserted, 5);

                let count = olap_count(&engine, "users").await;
                assert_eq!(count, 5);
            }

            #[tokio::test]
            async fn cdc_pruning_after_sync() {
                let tmp = TempDir::new().unwrap();
                let engine = $make_engine(&tmp).await;

                engine
                    .execute(
                        "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                        &[],
                    )
                    .await
                    .unwrap();
                engine.register_table(users_schema()).await.unwrap();

                engine
                    .execute("INSERT INTO users VALUES (1, 'Alice', 30)", &[])
                    .await
                    .unwrap();
                engine
                    .execute("INSERT INTO users VALUES (2, 'Bob', 25)", &[])
                    .await
                    .unwrap();

                let cdc_before = engine
                    .oltp()
                    .unwrap()
                    .query("SELECT COUNT(*) as cnt FROM _rhei_cdc_log", &[])
                    .await
                    .unwrap();
                let before_count = cdc_before[0]
                    .column(0)
                    .as_any()
                    .downcast_ref::<arrow::array::Int64Array>()
                    .unwrap()
                    .value(0);
                assert_eq!(before_count, 2, "CDC log should have 2 events before sync");

                let result = engine.sync_now().await.unwrap();
                assert_eq!(result.events_processed, 2);
                assert!(
                    result.pruned_count.is_some(),
                    "pruned_count should be set when pruning is enabled"
                );
                assert_eq!(result.pruned_count.unwrap(), 2);

                let cdc_after = engine
                    .oltp()
                    .unwrap()
                    .query("SELECT COUNT(*) as cnt FROM _rhei_cdc_log", &[])
                    .await
                    .unwrap();
                let count_array = cdc_after[0]
                    .column(0)
                    .as_any()
                    .downcast_ref::<arrow::array::Int64Array>()
                    .unwrap();
                assert_eq!(
                    count_array.value(0),
                    0,
                    "CDC log should be empty after pruning"
                );
            }

            #[tokio::test]
            async fn background_sync_loop() {
                let tmp = TempDir::new().unwrap();
                let mut engine = $make_engine(&tmp).await;

                engine
                    .execute(
                        "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                        &[],
                    )
                    .await
                    .unwrap();
                engine.register_table(users_schema()).await.unwrap();

                engine
                    .execute("INSERT INTO users VALUES (1, 'Alice', 30)", &[])
                    .await
                    .unwrap();

                engine.start_sync(Duration::from_millis(50));
                assert!(engine.is_sync_running());

                tokio::time::sleep(Duration::from_millis(500)).await;

                let count = olap_count(&engine, "users").await;
                assert_eq!(
                    count, 1,
                    "background sync should have replicated the row to OLAP"
                );

                engine.stop_sync().await;
                assert!(!engine.is_sync_running());

                let status = engine.sync_status().await.unwrap();
                assert!(!status.running);
            }

            #[tokio::test]
            async fn concurrent_reads_and_writes() {
                let tmp = TempDir::new().unwrap();
                let engine = Arc::new($make_engine(&tmp).await);

                engine
                    .execute(
                        "CREATE TABLE items (id INTEGER PRIMARY KEY, val INTEGER)",
                        &[],
                    )
                    .await
                    .unwrap();
                engine
                    .register_table(TableSchema::new(
                        "items",
                        Arc::new(arrow::datatypes::Schema::new(vec![
                            arrow::datatypes::Field::new("id", DataType::Int64, false),
                            arrow::datatypes::Field::new("val", DataType::Int64, true),
                        ])),
                        vec!["id".to_string()],
                    ))
                    .await
                    .unwrap();

                let handles: Vec<_> = (1i64..=8)
                    .map(|i| {
                        let eng = Arc::clone(&engine);
                        tokio::spawn(async move {
                            eng.execute(
                                &format!("INSERT INTO items VALUES ({i}, {i})"),
                                &[],
                            )
                            .await
                            .unwrap();
                            eng.oltp()
                                .unwrap()
                                .query("SELECT COUNT(*) FROM items", &[])
                                .await
                                .unwrap();
                        })
                    })
                    .collect();
                for h in handles {
                    h.await.unwrap();
                }

                engine.sync_now().await.unwrap();

                let count = olap_count(&engine, "items").await;
                assert_eq!(count, 8, "all 8 rows should have replicated to OLAP");
            }

            #[tokio::test]
            async fn initial_sync_empty_table() {
                let tmp = TempDir::new().unwrap();
                let engine = $make_engine(&tmp).await;

                engine
                    .execute(
                        "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                        &[],
                    )
                    .await
                    .unwrap();
                engine.register_table(users_schema()).await.unwrap();

                // No rows inserted — exercises the early-return branch
                let rows = engine.initial_sync("users").await.unwrap();
                assert_eq!(rows, 0);

                let count = olap_count(&engine, "users").await;
                assert_eq!(count, 0);
            }

            #[tokio::test]
            async fn initial_sync_all() {
                let tmp = TempDir::new().unwrap();
                let engine = $make_engine(&tmp).await;

                // Populate users (2 rows) before registering
                engine
                    .execute(
                        "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                        &[],
                    )
                    .await
                    .unwrap();
                engine
                    .execute("INSERT INTO users VALUES (1, 'Alice', 30)", &[])
                    .await
                    .unwrap();
                engine
                    .execute("INSERT INTO users VALUES (2, 'Bob', 25)", &[])
                    .await
                    .unwrap();

                // Populate orders (3 rows) before registering
                engine
                    .execute(
                        "CREATE TABLE orders (id INTEGER PRIMARY KEY, user_id INTEGER, total INTEGER)",
                        &[],
                    )
                    .await
                    .unwrap();
                engine
                    .execute("INSERT INTO orders VALUES (1, 1, 100)", &[])
                    .await
                    .unwrap();
                engine
                    .execute("INSERT INTO orders VALUES (2, 1, 200)", &[])
                    .await
                    .unwrap();
                engine
                    .execute("INSERT INTO orders VALUES (3, 2, 150)", &[])
                    .await
                    .unwrap();

                engine.register_table(users_schema()).await.unwrap();
                engine.register_table(orders_schema()).await.unwrap();

                let total = engine.initial_sync_all().await.unwrap();
                assert_eq!(total, 5);

                let users_count = olap_count(&engine, "users").await;
                assert_eq!(users_count, 2);

                let orders_count = olap_count(&engine, "orders").await;
                assert_eq!(orders_count, 3);
            }

            #[tokio::test]
            async fn ddl_lock_add_column_during_sync() {
                let tmp = TempDir::new().unwrap();
                let mut engine = $make_engine(&tmp).await;

                engine
                    .execute(
                        "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)",
                        &[],
                    )
                    .await
                    .unwrap();
                engine.register_table(users_two_col_schema()).await.unwrap();

                // Insert data and start background sync
                for i in 1..=5 {
                    engine
                        .execute(
                            &format!("INSERT INTO users VALUES ({}, 'User{}')", i, i),
                            &[],
                        )
                        .await
                        .unwrap();
                }
                engine.start_sync(Duration::from_millis(50));

                // Let sync pick up some events
                tokio::time::sleep(Duration::from_millis(150)).await;

                // Add a column while background sync is running
                engine
                    .execute("ALTER TABLE users ADD COLUMN age INTEGER", &[])
                    .await
                    .unwrap();
                engine
                    .add_column("users", "age", DataType::Int64)
                    .await
                    .unwrap();

                // Insert with new schema
                engine
                    .execute("INSERT INTO users VALUES (6, 'User6', 25)", &[])
                    .await
                    .unwrap();

                // Let sync catch up
                tokio::time::sleep(Duration::from_millis(200)).await;
                engine.stop_sync().await;

                // Verify OLAP has consistent data — all rows should be present
                let count = olap_count(&engine, "users").await;
                assert!(
                    count >= 5,
                    "OLAP should have at least 5 rows, got {}",
                    count
                );

                // Verify the post-add_column row is queryable with the new column
                let batches = engine
                    .olap()
                    .query("SELECT age FROM users WHERE id = 6")
                    .await
                    .unwrap();
                let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
                assert_eq!(total_rows, 1, "post-add_column row should be in OLAP");
            }

            #[tokio::test]
            async fn ddl_lock_drop_column_consistency() {
                let tmp = TempDir::new().unwrap();
                let mut engine = $make_engine(&tmp).await;

                engine
                    .execute(
                        "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                        &[],
                    )
                    .await
                    .unwrap();
                engine.register_table(users_schema()).await.unwrap();

                // Insert and start background sync
                engine
                    .execute("INSERT INTO users VALUES (1, 'Alice', 30)", &[])
                    .await
                    .unwrap();
                engine.start_sync(Duration::from_millis(50));

                // Let sync pick up the first insert
                tokio::time::sleep(Duration::from_millis(150)).await;

                // Drop column while sync is running
                engine.drop_column("users", "age").await.unwrap();

                // Schema registry should reflect the change
                let schema = engine.schema_registry().get("users").unwrap();
                assert_eq!(schema.arrow_schema.fields().len(), 2);

                // Insert without the dropped column
                engine
                    .execute("INSERT INTO users VALUES (2, 'Bob')", &[])
                    .await
                    .unwrap();

                // Let sync catch up
                tokio::time::sleep(Duration::from_millis(200)).await;
                engine.stop_sync().await;

                // Verify OLAP query works without the dropped column
                let batches = engine
                    .olap()
                    .query("SELECT name FROM users WHERE id = 1")
                    .await
                    .unwrap();
                let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
                assert_eq!(total_rows, 1, "pre-drop row should still be in OLAP");
            }
        }
    };
}

// ---------------------------------------------------------------------------
// DataFusion backend — shared tests + extras
// ---------------------------------------------------------------------------

async fn make_datafusion_engine(tmp: &TempDir) -> HtapEngine {
    let db_path = tmp.path().join("test.db");
    let config = HtapConfig {
        oltp_path: db_path.to_str().unwrap().to_string(),
        olap_in_memory: true,
        olap_path: None,
        sync_batch_size: 100,
        prune_after_sync: true,
        sync_interval: None,
        ..Default::default()
    };
    HtapEngine::new(config)
        .await
        .expect("failed to create HtapEngine")
}

backend_tests!(datafusion_tests, make_datafusion_engine);

mod datafusion_extra_tests {
    use super::*;
    use rhei::OltpEngine;

    async fn make_engine(tmp: &TempDir) -> HtapEngine {
        make_datafusion_engine(tmp).await
    }

    #[tokio::test]
    async fn test_wal_mode_enabled() {
        let tmp = TempDir::new().unwrap();
        let engine = make_engine(&tmp).await;
        let batches = engine
            .oltp()
            .unwrap()
            .query("PRAGMA journal_mode", &[])
            .await
            .unwrap();
        let mode = batches[0]
            .column(0)
            .as_any()
            .downcast_ref::<arrow::array::StringArray>()
            .unwrap()
            .value(0);
        assert_eq!(mode, "wal", "WAL mode should be active on a file-backed DB");
    }

    #[tokio::test]
    async fn test_schema_evolution_cdc_triggers_rebuilt() {
        let tmp = TempDir::new().unwrap();
        let engine = make_engine(&tmp).await;

        engine
            .execute(
                "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)",
                &[],
            )
            .await
            .unwrap();
        engine.register_table(users_two_col_schema()).await.unwrap();

        engine
            .execute("INSERT INTO users VALUES (1, 'Alice')", &[])
            .await
            .unwrap();
        engine.sync_now().await.unwrap();

        // Add a Float64 column — CDC triggers must be rebuilt to capture it
        engine
            .execute("ALTER TABLE users ADD COLUMN score REAL", &[])
            .await
            .unwrap();
        engine
            .add_column("users", "score", DataType::Float64)
            .await
            .unwrap();

        // Insert with the new column — rebuilt trigger must capture the value
        engine
            .execute("INSERT INTO users VALUES (2, 'Bob', 9.5)", &[])
            .await
            .unwrap();
        engine.sync_now().await.unwrap();

        let batches = engine
            .olap()
            .query("SELECT score FROM users WHERE id = 2")
            .await
            .unwrap();
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, 1);
        assert!(
            !batches[0].column(0).is_null(0),
            "score should not be NULL — rebuilt CDC trigger must have captured the value"
        );
    }
}

// ---------------------------------------------------------------------------
// DuckDB backend — shared tests + extras
// ---------------------------------------------------------------------------

#[cfg(feature = "duckdb-backend")]
async fn make_duckdb_engine(tmp: &TempDir) -> HtapEngine {
    use rhei::OlapBackendType;

    let db_path = tmp.path().join("test.db");
    let config = HtapConfig {
        oltp_path: db_path.to_str().unwrap().to_string(),
        olap_in_memory: true,
        olap_path: None,
        sync_batch_size: 100,
        prune_after_sync: true,
        sync_interval: None,
        olap_backend: OlapBackendType::DuckDb,
        read_pool_size: 4,
        ..Default::default()
    };
    HtapEngine::new(config)
        .await
        .expect("failed to create HtapEngine")
}

#[cfg(feature = "duckdb-backend")]
backend_tests!(duckdb_tests, make_duckdb_engine);

#[cfg(feature = "duckdb-backend")]
mod duckdb_extra_tests {
    use super::*;

    use rhei::OltpEngine;
    use serde_json::json;

    async fn make_engine(tmp: &TempDir) -> HtapEngine {
        make_duckdb_engine(tmp).await
    }

    #[tokio::test]
    async fn test_oltp_create_and_query() {
        let tmp = TempDir::new().unwrap();
        let engine = make_engine(&tmp).await;

        engine
            .execute(
                "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                &[],
            )
            .await
            .unwrap();

        engine
            .execute("INSERT INTO users VALUES (1, 'Alice', 30)", &[])
            .await
            .unwrap();
        engine
            .execute("INSERT INTO users VALUES (2, 'Bob', 25)", &[])
            .await
            .unwrap();

        let batches = engine
            .oltp()
            .unwrap()
            .query("SELECT * FROM users ORDER BY id", &[])
            .await
            .unwrap();
        assert_eq!(batches.len(), 1);
        assert_eq!(batches[0].num_rows(), 2);
    }

    #[tokio::test]
    async fn test_register_table_sets_up_cdc() {
        let tmp = TempDir::new().unwrap();
        let engine = make_engine(&tmp).await;

        engine
            .execute(
                "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                &[],
            )
            .await
            .unwrap();

        engine.register_table(users_schema()).await.unwrap();

        engine
            .execute("INSERT INTO users VALUES (1, 'Alice', 30)", &[])
            .await
            .unwrap();

        let cdc_batches = engine
            .oltp()
            .unwrap()
            .query("SELECT * FROM _rhei_cdc_log", &[])
            .await
            .unwrap();
        assert_eq!(cdc_batches.len(), 1);
        assert!(
            cdc_batches[0].num_rows() >= 1,
            "CDC log should have at least 1 event"
        );
    }

    #[tokio::test]
    async fn test_parameterized_execute() {
        let tmp = TempDir::new().unwrap();
        let engine = make_engine(&tmp).await;

        engine
            .execute(
                "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                &[],
            )
            .await
            .unwrap();

        engine
            .execute(
                "INSERT INTO users VALUES (?1, ?2, ?3)",
                &[json!(1), json!("Alice"), json!(30)],
            )
            .await
            .unwrap();

        let batches = engine
            .oltp()
            .unwrap()
            .query("SELECT name FROM users WHERE id = 1", &[])
            .await
            .unwrap();
        assert_eq!(batches[0].num_rows(), 1);
    }
}

// ---------------------------------------------------------------------------
// Temporal mode tests (SCD Type 2 -- works with standard CDC)
// ---------------------------------------------------------------------------
#[cfg(feature = "datafusion-backend")]
mod temporal_tests {
    use super::*;
    use arrow::array::{Array, Int64Array, StringArray};
    use rhei::SyncMode;

    async fn make_temporal_engine(tmp: &TempDir) -> HtapEngine {
        let config = HtapConfig {
            oltp_path: tmp.path().join("temporal.db").to_str().unwrap().to_string(),
            sync_mode: SyncMode::Temporal,
            ..Default::default()
        };
        HtapEngine::new(config).await.unwrap()
    }

    #[tokio::test]
    async fn test_temporal_mode_with_cdc() {
        let tmp = TempDir::new().unwrap();
        let engine = make_temporal_engine(&tmp).await;

        engine
            .execute(
                "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                &[],
            )
            .await
            .unwrap();
        engine.register_table(users_schema()).await.unwrap();

        // INSERT a row
        engine
            .execute(
                "INSERT INTO users (id, name, age) VALUES (1, 'Alice', 30)",
                &[],
            )
            .await
            .unwrap();

        let result = engine.sync_now().await.unwrap();
        assert!(result.events_processed >= 1);
        assert!(result.rows_inserted >= 1);

        // Query OLAP -- should have the row with temporal columns
        let batches = engine
            .olap()
            .query("SELECT * FROM users WHERE _rhei_operation = 'I' AND name = 'Alice'")
            .await
            .unwrap();
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, 1);

        let schema = batches[0].schema();
        assert!(schema.field_with_name("_rhei_valid_from").is_ok());
        assert!(schema.field_with_name("_rhei_valid_to").is_ok());
        assert!(schema.field_with_name("_rhei_operation").is_ok());

        let op_col = batches[0]
            .column(schema.index_of("_rhei_operation").unwrap())
            .as_any()
            .downcast_ref::<StringArray>()
            .unwrap();
        assert_eq!(op_col.value(0), "I"); // INSERT operation

        let valid_to = batches[0]
            .column(schema.index_of("_rhei_valid_to").unwrap())
            .as_any()
            .downcast_ref::<Int64Array>()
            .unwrap();
        assert!(valid_to.is_null(0)); // Current version — valid_to is NULL
    }

    #[tokio::test]
    async fn test_temporal_update_creates_history() {
        let tmp = TempDir::new().unwrap();
        let engine = make_temporal_engine(&tmp).await;

        engine
            .execute(
                "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                &[],
            )
            .await
            .unwrap();
        engine.register_table(users_schema()).await.unwrap();

        // INSERT
        engine
            .execute(
                "INSERT INTO users (id, name, age) VALUES (1, 'Alice', 30)",
                &[],
            )
            .await
            .unwrap();
        engine.sync_now().await.unwrap();

        // UPDATE
        engine
            .execute("UPDATE users SET name = 'Bob', age = 31 WHERE id = 1", &[])
            .await
            .unwrap();
        let result = engine.sync_now().await.unwrap();
        assert_eq!(result.rows_updated, 1);

        // OLAP should now have 2 rows: original (closed) + updated (current)
        let batches = engine
            .olap()
            .query("SELECT * FROM users ORDER BY _rhei_valid_from ASC")
            .await
            .unwrap();

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, 2, "should have 2 versions (original + updated)");

        let schema = batches[0].schema();
        let op_idx = schema.index_of("_rhei_operation").unwrap();
        let valid_to_idx = schema.index_of("_rhei_valid_to").unwrap();

        let ops = batches[0]
            .column(op_idx)
            .as_any()
            .downcast_ref::<StringArray>()
            .unwrap();
        let valid_to = batches[0]
            .column(valid_to_idx)
            .as_any()
            .downcast_ref::<Int64Array>()
            .unwrap();

        // First row: original INSERT, should be closed (valid_to is NOT null)
        assert_eq!(ops.value(0), "I");
        assert!(!valid_to.is_null(0), "original version should be closed");

        // Second row: UPDATE version, should be current (valid_to is NULL)
        assert_eq!(ops.value(1), "U");
        assert!(valid_to.is_null(1), "updated version should be current");
    }
}

// ---------------------------------------------------------------------------
// RocksDB CDC bridge tests
// ---------------------------------------------------------------------------
#[cfg(all(feature = "datafusion-backend", feature = "rocksdb-cdc"))]
mod rocksdb_bridge_tests {
    use super::*;
    use rhei::OltpEngine;

    async fn make_bridge_engine(tmp: &TempDir) -> HtapEngine {
        let db_path = tmp.path().join("bridge_test.db");
        let rocksdb_path = tmp.path().join("bridge_rocksdb");
        let config = HtapConfig {
            oltp_path: db_path.to_str().unwrap().to_string(),
            olap_in_memory: true,
            olap_path: None,
            sync_batch_size: 100,
            prune_after_sync: true,
            sync_interval: None,
            rocksdb_cdc_path: Some(rocksdb_path.to_str().unwrap().to_string()),
            ..Default::default()
        };
        HtapEngine::new(config)
            .await
            .expect("failed to create HtapEngine with RocksDB bridge")
    }

    /// Full HTAP pipeline through the RocksDB bridge: inserts flow through
    /// SQLite CDC triggers -> RocksDB durable log -> sync -> OLAP.
    #[tokio::test]
    async fn test_bridge_full_pipeline() {
        let tmp = TempDir::new().unwrap();
        let engine = make_bridge_engine(&tmp).await;

        engine
            .execute(
                "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                &[],
            )
            .await
            .unwrap();
        engine.register_table(users_schema()).await.unwrap();

        engine
            .execute("INSERT INTO users VALUES (1, 'Alice', 30)", &[])
            .await
            .unwrap();
        engine
            .execute("INSERT INTO users VALUES (2, 'Bob', 25)", &[])
            .await
            .unwrap();
        engine
            .execute("INSERT INTO users VALUES (3, 'Charlie', 35)", &[])
            .await
            .unwrap();

        let sync_result = engine.sync_now().await.unwrap();
        assert_eq!(
            sync_result.events_processed, 3,
            "bridge should process 3 events"
        );
        assert_eq!(sync_result.rows_inserted, 3);
        assert_eq!(sync_result.rows_updated, 0);
        assert_eq!(sync_result.rows_deleted, 0);

        let count = olap_count(&engine, "users").await;
        assert_eq!(count, 3, "OLAP should have 3 rows after bridge sync");

        let status = engine.sync_status().await.unwrap();
        assert_eq!(status.lag, 0, "no lag after sync");
    }

    /// Verify that after bridging, the SQLite CDC log is pruned (events moved to RocksDB).
    #[tokio::test]
    async fn test_bridge_prunes_sqlite_log() {
        let tmp = TempDir::new().unwrap();
        let engine = make_bridge_engine(&tmp).await;

        engine
            .execute(
                "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                &[],
            )
            .await
            .unwrap();
        engine.register_table(users_schema()).await.unwrap();

        engine
            .execute("INSERT INTO users VALUES (1, 'Alice', 30)", &[])
            .await
            .unwrap();
        engine
            .execute("INSERT INTO users VALUES (2, 'Bob', 25)", &[])
            .await
            .unwrap();

        // Before sync: SQLite CDC log has 2 events.
        let cdc_before = engine
            .oltp()
            .unwrap()
            .query("SELECT COUNT(*) FROM _rhei_cdc_log", &[])
            .await
            .unwrap();
        let before_count = cdc_before[0]
            .column(0)
            .as_any()
            .downcast_ref::<arrow::array::Int64Array>()
            .unwrap()
            .value(0);
        assert_eq!(
            before_count, 2,
            "SQLite CDC log should have 2 events before sync"
        );

        // Sync: bridge drains SQLite into RocksDB, then prunes SQLite.
        let result = engine.sync_now().await.unwrap();
        assert_eq!(result.events_processed, 2);

        // After sync: SQLite CDC log should be empty (events moved to RocksDB and pruned
        // there too since prune_after_sync=true).
        let cdc_after = engine
            .oltp()
            .unwrap()
            .query("SELECT COUNT(*) FROM _rhei_cdc_log", &[])
            .await
            .unwrap();
        let after_count = cdc_after[0]
            .column(0)
            .as_any()
            .downcast_ref::<arrow::array::Int64Array>()
            .unwrap()
            .value(0);
        assert_eq!(
            after_count, 0,
            "SQLite CDC log should be empty after bridge sync (events moved to RocksDB)"
        );
    }

    /// Verify the bridge correctly handles UPDATE and DELETE events.
    #[tokio::test]
    async fn test_bridge_update_delete() {
        let tmp = TempDir::new().unwrap();
        let engine = make_bridge_engine(&tmp).await;

        engine
            .execute(
                "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                &[],
            )
            .await
            .unwrap();
        engine.register_table(users_schema()).await.unwrap();

        engine
            .execute("INSERT INTO users VALUES (1, 'Alice', 30)", &[])
            .await
            .unwrap();
        engine.sync_now().await.unwrap();

        // Update via bridge
        engine
            .execute("UPDATE users SET age = 31 WHERE id = 1", &[])
            .await
            .unwrap();
        let sync_result = engine.sync_now().await.unwrap();
        assert_eq!(sync_result.rows_updated, 1, "bridge should sync UPDATE");

        // Delete via bridge
        engine
            .execute("DELETE FROM users WHERE id = 1", &[])
            .await
            .unwrap();
        let sync_result = engine.sync_now().await.unwrap();
        assert_eq!(sync_result.rows_deleted, 1, "bridge should sync DELETE");

        let count = olap_count(&engine, "users").await;
        assert_eq!(count, 0, "OLAP should be empty after delete");
    }

    /// Verify that a second sync cycle (simulating restart after a crash)
    /// re-delivers events that were in RocksDB but not yet applied to OLAP.
    /// This tests the durability guarantee of the bridge.
    #[tokio::test]
    async fn test_bridge_rocksdb_durability() {
        let tmp = TempDir::new().unwrap();
        let engine = make_bridge_engine(&tmp).await;

        engine
            .execute(
                "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                &[],
            )
            .await
            .unwrap();
        engine.register_table(users_schema()).await.unwrap();

        engine
            .execute("INSERT INTO users VALUES (1, 'Alice', 30)", &[])
            .await
            .unwrap();
        engine
            .execute("INSERT INTO users VALUES (2, 'Bob', 25)", &[])
            .await
            .unwrap();

        // First sync cycle: events are bridged into RocksDB and applied to OLAP.
        let result = engine.sync_now().await.unwrap();
        assert_eq!(result.events_processed, 2);

        // Second sync cycle: RocksDB log has no new events (already pruned),
        // so this should be a no-op.
        let result2 = engine.sync_now().await.unwrap();
        assert_eq!(
            result2.events_processed, 0,
            "second sync cycle should process 0 events (already applied and pruned)"
        );

        let count = olap_count(&engine, "users").await;
        assert_eq!(
            count, 2,
            "OLAP should still have 2 rows after idempotent second sync"
        );
    }

    /// Verify that running multiple consecutive sync cycles after a batch of
    /// INSERTs does not duplicate rows in OLAP.
    ///
    /// This is the integration-level proof of the idempotent bridge fix: even if
    /// the bridge were called multiple times for the same SQLite rows (e.g. after
    /// a prune failure), the bridge watermark prevents re-appending those rows to
    /// RocksDB, so OLAP counts remain correct.
    #[tokio::test]
    async fn test_bridge_idempotent_no_duplicates() {
        let tmp = TempDir::new().unwrap();
        let engine = make_bridge_engine(&tmp).await;

        engine
            .execute(
                "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                &[],
            )
            .await
            .unwrap();
        engine.register_table(users_schema()).await.unwrap();

        // Insert 3 rows.
        engine
            .execute("INSERT INTO users VALUES (1, 'Alice', 30)", &[])
            .await
            .unwrap();
        engine
            .execute("INSERT INTO users VALUES (2, 'Bob', 25)", &[])
            .await
            .unwrap();
        engine
            .execute("INSERT INTO users VALUES (3, 'Charlie', 35)", &[])
            .await
            .unwrap();

        // First sync: bridges SQLite events into RocksDB, applies them to OLAP.
        let result1 = engine.sync_now().await.unwrap();
        assert_eq!(
            result1.events_processed, 3,
            "first sync should process 3 events"
        );

        // Second sync: no new SQLite events, bridge watermark up-to-date.
        // Must produce 0 new events regardless of SQLite log state.
        let result2 = engine.sync_now().await.unwrap();
        assert_eq!(
            result2.events_processed, 0,
            "second sync must not re-process already-bridged events"
        );

        // Third sync for good measure.
        let result3 = engine.sync_now().await.unwrap();
        assert_eq!(
            result3.events_processed, 0,
            "third sync must also be a no-op"
        );

        // OLAP must have exactly 3 rows — not 6 or 9.
        let count = olap_count(&engine, "users").await;
        assert_eq!(
            count, 3,
            "OLAP must have exactly 3 rows; duplicate bridging would inflate this"
        );
    }

    /// Verify that `sync_status().lag` is nonzero when there are un-bridged
    /// SQLite events, and drops to zero after a successful sync.
    ///
    /// This tests the Fix 2 change to `latest_seq` for the `RocksDbBridge`
    /// variant: pending SQLite events must be reflected in the lag metric so
    /// that dashboards and monitoring show pending work correctly.
    #[tokio::test]
    async fn test_bridge_lag_reflects_sqlite_backlog() {
        let tmp = TempDir::new().unwrap();
        let engine = make_bridge_engine(&tmp).await;

        engine
            .execute(
                "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                &[],
            )
            .await
            .unwrap();
        engine.register_table(users_schema()).await.unwrap();

        // Insert rows — these sit in `_rhei_cdc_log` (SQLite) until the next sync.
        engine
            .execute("INSERT INTO users VALUES (1, 'Alice', 30)", &[])
            .await
            .unwrap();
        engine
            .execute("INSERT INTO users VALUES (2, 'Bob', 25)", &[])
            .await
            .unwrap();

        // Before sync: lag should be > 0 because SQLite has pending events that
        // have not yet been bridged into RocksDB.
        let status_before = engine.sync_status().await.unwrap();
        assert!(
            status_before.lag > 0,
            "lag should be nonzero before sync (SQLite backlog not yet bridged); \
             got lag = {}",
            status_before.lag
        );

        // After sync: all events bridged and applied; lag should be 0.
        engine.sync_now().await.unwrap();
        let status_after = engine.sync_status().await.unwrap();
        assert_eq!(
            status_after.lag, 0,
            "lag should be 0 after sync; got {}",
            status_after.lag
        );
    }
}

// ---------------------------------------------------------------------------
// Schema registry persistence tests
// ---------------------------------------------------------------------------

#[cfg(feature = "datafusion-backend")]
mod schema_persistence_tests {
    use super::*;

    /// Create a fresh engine with a given OLTP db path and schema registry path.
    async fn make_engine_with_registry(oltp_path: &str, registry_path: &str) -> HtapEngine {
        let config = HtapConfig {
            oltp_path: oltp_path.to_string(),
            schema_registry_path: Some(registry_path.to_string()),
            ..Default::default()
        };
        HtapEngine::new(config)
            .await
            .expect("failed to create engine")
    }

    #[tokio::test]
    async fn schema_persists_across_restarts() {
        let tmp = TempDir::new().unwrap();
        let db_path = tmp.path().join("persist.db").to_str().unwrap().to_string();
        let reg_path = tmp
            .path()
            .join("registry.json")
            .to_str()
            .unwrap()
            .to_string();

        // --- First engine instance: register the table ---
        {
            let engine = make_engine_with_registry(&db_path, &reg_path).await;
            engine
                .execute(
                    "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                    &[],
                )
                .await
                .unwrap();
            engine.register_table(users_schema()).await.unwrap();

            // Verify registry file was created
            assert!(
                std::path::Path::new(&reg_path).exists(),
                "registry JSON file should have been created after register_table"
            );
        }

        // --- Second engine instance: registry should be restored ---
        {
            // NOTE: In the restored engine the OLAP mirror is empty (in-memory DataFusion
            // does not persist across processes); what we verify is that the schema
            // registry knows about the table without calling register_table again.
            let engine = make_engine_with_registry(&db_path, &reg_path).await;

            let names = engine.schema_registry().table_names();
            assert!(
                names.contains(&"users".to_string()),
                "schema registry should contain 'users' after restart, got: {names:?}"
            );

            let schema = engine.schema_registry().get("users").unwrap();
            assert_eq!(schema.name, "users");
            assert_eq!(schema.primary_key, vec!["id".to_string()]);
            assert_eq!(schema.arrow_schema.fields().len(), 3);
        }
    }

    #[tokio::test]
    async fn schema_persist_round_trips_types() {
        let tmp = TempDir::new().unwrap();
        let db_path = tmp.path().join("types.db").to_str().unwrap().to_string();
        let reg_path = tmp
            .path()
            .join("types_registry.json")
            .to_str()
            .unwrap()
            .to_string();

        let rich_schema = TableSchema::new(
            "events",
            Arc::new(Schema::new(vec![
                Field::new("id", DataType::Int64, false),
                Field::new("score", DataType::Float64, true),
                Field::new("label", DataType::Utf8, true),
                Field::new("active", DataType::Boolean, true),
                Field::new("data", DataType::Binary, true),
            ])),
            vec!["id".to_string()],
        );

        // Register in first engine
        {
            let engine = make_engine_with_registry(&db_path, &reg_path).await;
            engine
                .execute(
                    "CREATE TABLE events (id INTEGER PRIMARY KEY, score REAL, label TEXT, active INTEGER, data BLOB)",
                    &[],
                )
                .await
                .unwrap();
            engine.register_table(rich_schema).await.unwrap();
        }

        // Reload in second engine and verify types
        {
            let engine = make_engine_with_registry(&db_path, &reg_path).await;
            let schema = engine.schema_registry().get("events").unwrap();
            assert_eq!(schema.arrow_schema.fields().len(), 5);

            let f = |name: &str| schema.arrow_schema.field_with_name(name).unwrap().clone();
            assert_eq!(*f("id").data_type(), DataType::Int64);
            assert_eq!(*f("score").data_type(), DataType::Float64);
            assert_eq!(*f("label").data_type(), DataType::Utf8);
            assert_eq!(*f("active").data_type(), DataType::Boolean);
            assert_eq!(*f("data").data_type(), DataType::Binary);
        }
    }
}

// ---------------------------------------------------------------------------
// Sidecar mode tests (timestamp-based CDC from external DB)
// ---------------------------------------------------------------------------
#[cfg(all(feature = "datafusion-backend", feature = "sidecar"))]
mod sidecar_tests {
    use super::*;
    use arrow::array::StringArray;
    use rhei::{
        DeleteDetection, SidecarConfig, SidecarSource, SyncMode, TimestampCdcConfig,
        TimestampTableConfig,
    };

    fn external_users_table_config() -> TimestampTableConfig {
        TimestampTableConfig {
            table_name: "users".to_string(),
            created_at_column: "created_at".to_string(),
            updated_at_column: "updated_at".to_string(),
            primary_key: vec!["id".to_string()],
            columns: vec![],
        }
    }

    fn external_users_schema() -> TableSchema {
        TableSchema::new(
            "users",
            Arc::new(Schema::new(vec![
                Field::new("id", DataType::Int64, false),
                Field::new("name", DataType::Utf8, true),
                Field::new("created_at", DataType::Int64, false),
                Field::new("updated_at", DataType::Int64, false),
            ])),
            vec!["id".to_string()],
        )
    }

    /// Set up an external SQLite DB with a users table.
    fn setup_external_db(path: &str) {
        let conn = rusqlite::Connection::open(path).unwrap();
        conn.execute_batch(
            "CREATE TABLE users (
                id INTEGER PRIMARY KEY,
                name TEXT,
                created_at INTEGER NOT NULL,
                updated_at INTEGER NOT NULL
            )",
        )
        .unwrap();
    }

    #[tokio::test]
    async fn test_sidecar_temporal_full_pipeline() {
        let tmp = TempDir::new().unwrap();
        let ext_path = tmp.path().join("external.db");
        let ext_path_str = ext_path.to_str().unwrap();

        // Set up external DB with data
        setup_external_db(ext_path_str);
        {
            let conn = rusqlite::Connection::open(ext_path_str).unwrap();
            conn.execute(
                "INSERT INTO users (id, name, created_at, updated_at) VALUES (1, 'Alice', 1000, 1000)",
                [],
            )
            .unwrap();
            conn.execute(
                "INSERT INTO users (id, name, created_at, updated_at) VALUES (2, 'Bob', 1001, 1001)",
                [],
            )
            .unwrap();
        }

        // Create sidecar engine
        let config = HtapConfig {
            oltp_path: tmp.path().join("local.db").to_str().unwrap().to_string(),
            sync_mode: SyncMode::Temporal,
            sidecar: Some(SidecarConfig {
                source: SidecarSource::Sqlite(ext_path_str.to_string()),
                timestamp_config: TimestampCdcConfig {
                    tables: vec![external_users_table_config()],
                    poll_batch_size: 100,
                    delete_detection: DeleteDetection::Disabled,
                },
                enable_local_oltp: false,
                watermark_path: None,
            }),
            ..Default::default()
        };
        let engine = HtapEngine::new(config).await.unwrap();
        engine
            .register_table(external_users_schema())
            .await
            .unwrap();

        // Sync
        let result = engine.sync_now().await.unwrap();
        assert_eq!(result.events_processed, 2);
        assert_eq!(result.rows_inserted, 2);

        // Query OLAP — should have temporal rows
        let batches = engine
            .olap()
            .query("SELECT * FROM users ORDER BY id")
            .await
            .unwrap();
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, 2);

        let schema = batches[0].schema();
        assert!(schema.field_with_name("_rhei_valid_from").is_ok());
        assert!(schema.field_with_name("_rhei_valid_to").is_ok());
        assert!(schema.field_with_name("_rhei_operation").is_ok());
    }

    #[tokio::test]
    async fn test_sidecar_oltp_disabled() {
        let tmp = TempDir::new().unwrap();
        let ext_path = tmp.path().join("external.db");
        let ext_path_str = ext_path.to_str().unwrap();
        setup_external_db(ext_path_str);

        let config = HtapConfig {
            oltp_path: tmp.path().join("local.db").to_str().unwrap().to_string(),
            sync_mode: SyncMode::Destructive,
            sidecar: Some(SidecarConfig {
                source: SidecarSource::Sqlite(ext_path_str.to_string()),
                timestamp_config: TimestampCdcConfig {
                    tables: vec![external_users_table_config()],
                    poll_batch_size: 100,
                    delete_detection: DeleteDetection::Disabled,
                },
                enable_local_oltp: false,
                watermark_path: None,
            }),
            ..Default::default()
        };
        let engine = HtapEngine::new(config).await.unwrap();

        // OLTP should not be available
        assert!(engine.oltp().is_none());

        // execute() should fail
        let err = engine.execute("INSERT INTO foo VALUES (1)", &[]).await;
        assert!(err.is_err());
    }

    #[tokio::test]
    async fn test_sidecar_point_in_time_query() {
        let tmp = TempDir::new().unwrap();
        let ext_path = tmp.path().join("external.db");
        let ext_path_str = ext_path.to_str().unwrap();

        setup_external_db(ext_path_str);
        {
            let conn = rusqlite::Connection::open(ext_path_str).unwrap();
            // Insert at time 1000
            conn.execute(
                "INSERT INTO users (id, name, created_at, updated_at) VALUES (1, 'Alice', 1000, 1000)",
                [],
            )
            .unwrap();
        }

        let config = HtapConfig {
            oltp_path: tmp.path().join("local.db").to_str().unwrap().to_string(),
            sync_mode: SyncMode::Temporal,
            sidecar: Some(SidecarConfig {
                source: SidecarSource::Sqlite(ext_path_str.to_string()),
                timestamp_config: TimestampCdcConfig {
                    tables: vec![external_users_table_config()],
                    poll_batch_size: 100,
                    delete_detection: DeleteDetection::Disabled,
                },
                enable_local_oltp: false,
                watermark_path: None,
            }),
            ..Default::default()
        };
        let engine = HtapEngine::new(config).await.unwrap();
        engine
            .register_table(external_users_schema())
            .await
            .unwrap();

        // First sync (picks up INSERT at time 1000)
        engine.sync_now().await.unwrap();

        // Now update the external DB at time 2000
        {
            let conn = rusqlite::Connection::open(ext_path_str).unwrap();
            conn.execute(
                "UPDATE users SET name = 'Bob', updated_at = 2000 WHERE id = 1",
                [],
            )
            .unwrap();
        }

        // Second sync (picks up UPDATE at time 2000)
        let result = engine.sync_now().await.unwrap();
        assert_eq!(result.events_processed, 1);
        assert_eq!(result.rows_updated, 1);

        // Point-in-time query: "What was user 1 at time 1500?"
        // At time 1500, the original INSERT (valid_from=1000) should be current.
        let batches = engine
            .olap()
            .query(
                "SELECT name FROM users WHERE id = 1 \
                 AND _rhei_valid_from <= 1500 \
                 AND (_rhei_valid_to IS NULL OR _rhei_valid_to > 1500)",
            )
            .await
            .unwrap();
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, 1);
        let name = batches[0]
            .column(0)
            .as_any()
            .downcast_ref::<StringArray>()
            .unwrap()
            .value(0);
        assert_eq!(name, "Alice", "at time 1500, user should still be Alice");

        // Point-in-time query: "What was user 1 at time 2500?"
        // At time 2500, the UPDATE (valid_from=2000) should be current.
        let batches = engine
            .olap()
            .query(
                "SELECT name FROM users WHERE id = 1 \
                 AND _rhei_valid_from <= 2500 \
                 AND (_rhei_valid_to IS NULL OR _rhei_valid_to > 2500)",
            )
            .await
            .unwrap();
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, 1);
        let name = batches[0]
            .column(0)
            .as_any()
            .downcast_ref::<StringArray>()
            .unwrap()
            .value(0);
        assert_eq!(name, "Bob", "at time 2500, user should be Bob");
    }
}

// ---------------------------------------------------------------------------
// register_table idempotency tests (Issue 1 fix)
// ---------------------------------------------------------------------------

mod register_table_idempotency {
    use super::*;

    async fn make_engine(tmp: &TempDir) -> HtapEngine {
        make_datafusion_engine(tmp).await
    }

    /// Re-registering the exact same schema after the table already exists in the
    /// registry must succeed — this is the rh-serve restart scenario.
    #[tokio::test]
    async fn register_table_idempotent_matching_schema() {
        let tmp = TempDir::new().unwrap();
        let engine = make_engine(&tmp).await;

        engine
            .execute(
                "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                &[],
            )
            .await
            .unwrap();

        // First registration — should succeed.
        engine.register_table(users_schema()).await.unwrap();

        // Second registration with the identical schema — must return Ok(()) (idempotent).
        engine
            .register_table(users_schema())
            .await
            .expect("register_table with matching schema must be idempotent (Ok)");
    }

    /// Registering a schema that conflicts (different column types) with one that is
    /// already in the registry must return an error with a clear message.
    #[tokio::test]
    async fn register_table_errors_on_conflicting_schema() {
        let tmp = TempDir::new().unwrap();
        let engine = make_engine(&tmp).await;

        engine
            .execute(
                "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
                &[],
            )
            .await
            .unwrap();

        // First registration.
        engine.register_table(users_schema()).await.unwrap();

        // Build a schema with a *different* type for the `age` column (Float64 vs Int64).
        let conflicting = TableSchema::new(
            "users",
            Arc::new(arrow::datatypes::Schema::new(vec![
                arrow::datatypes::Field::new("id", DataType::Int64, false),
                arrow::datatypes::Field::new("name", DataType::Utf8, true),
                arrow::datatypes::Field::new("age", DataType::Float64, true), // was Int64
            ])),
            vec!["id".to_string()],
        );

        let result = engine.register_table(conflicting).await;
        assert!(
            result.is_err(),
            "register_table with conflicting schema must return an error"
        );
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("different schema"),
            "error message should mention 'different schema', got: {err_msg}"
        );
    }
}