khive-db 0.24.0

SQLite storage backend: entities, edges, notes, events, FTS5, sqlite-vec vectors.
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
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
//! SQL-backed `EntityStore` implementation.

use std::collections::HashSet;
use std::sync::Arc;

use async_trait::async_trait;
use rusqlite::OptionalExtension;
use uuid::Uuid;

use khive_storage::attachment::{Attachment, AttachmentSubstrate};
use khive_storage::entity::{
    Entity, EntityAlias, EntityAliasOrigin, EntityFilter, EntityKeyHolder, EntityTombstones,
    EntityTypeCounts,
};
use khive_storage::error::StorageError;
use khive_storage::types::{
    BatchWriteSummary, DeleteMode, Page, PageRequest, SeekCursor, SeekPage, SqlStatement, SqlValue,
};
use khive_storage::EntityStore;
use khive_storage::StorageCapability;

use crate::error::SqliteError;
use crate::pool::ConnectionPool;
use crate::sql_bridge::bind_params;
use crate::stores::attachment::{attachment_upsert_statement, delete_record_attachments_statement};
use crate::writer_task::{execute_wrapped_transaction, WriterTaskHandle};

fn map_err(e: rusqlite::Error, op: &'static str) -> StorageError {
    StorageError::driver(StorageCapability::Entities, op, e)
}

fn map_sqlite_err(e: SqliteError, op: &'static str) -> StorageError {
    e.into_storage_error(StorageCapability::Entities, op)
}

const NAMESPACE_COUNT_CHUNK_SIZE: usize = 500;

const ENTITIES_COUNT_BY_TYPE_SQL: &str = include_str!("../../sql/entities-count-by-type.sql");

/// The `aliases` column of an entity read (ADR-221 section 2): a JSON array
/// of `[alias, origin]` pairs for the entity's alias rows, `[]` when it has
/// none. The query must read the entity from a table named `entities`.
/// [`parse_entity_aliases`] reads the value. The store's own entity reads end
/// with the same subquery, and a test holds the two texts equal.
pub const ENTITY_ALIASES_COLUMN: &str =
    "(SELECT json_group_array(json_array(entity_alias.alias, entity_alias.origin)) \
     FROM entity_aliases AS entity_alias \
     WHERE entity_alias.entity_id = entities.id \
     AND entity_alias.namespace = entities.namespace)";

// Every part is a string literal, so a source scan of the statements that
// use these columns reads the whole text. The aliases subquery repeats
// `ENTITY_ALIASES_COLUMN`.
const ENTITY_SELECT_COLUMNS: &str = concat!(
    "entities.id, entities.namespace, entities.kind, entities.entity_type, entities.name, \
     entities.description, entities.properties, entities.tags, entities.created_at, \
     entities.updated_at, entities.deleted_at, entities.merged_into, entities.merge_event_id, \
     (SELECT attachment.content_ref FROM attachments AS attachment \
      WHERE attachment.record_uuid = entities.id \
        AND attachment.substrate = 'entity' AND attachment.role = 'content') AS content_ref, \
     entities.version, ",
    "(SELECT json_group_array(json_array(entity_alias.alias, entity_alias.origin)) \
     FROM entity_aliases AS entity_alias \
     WHERE entity_alias.entity_id = entities.id \
     AND entity_alias.namespace = entities.namespace)",
    " AS aliases"
);

// ---------------------------------------------------------------------------
// Pure statement builders (ADR-099 B3 r6 structural cut)
//
// These carry NO I/O — they turn an already-computed `Entity` (or a bare id)
// into the exact `SqlStatement` this store executes. `upsert_entity` and
// `delete_entity` below call them and execute the result; ADR-099's atomic
// prepare path (`khive-runtime`) calls them too, to build the same statement
// for its own guarded, synchronous apply. One statement generator, two
// execution mechanisms (async trait dispatch vs. synchronous atomic unit) —
// per ADR-099's accepted "handler-logic-duplication objection" text, the
// bulk-apply path reuses the handler's existing statement generation instead
// of re-deriving it.
// ---------------------------------------------------------------------------

/// Insert at version one, or replace the fields and advance the existing row once.
pub fn entity_upsert_statement(entity: &Entity) -> SqlStatement {
    let mut statement = entity_write_statement(entity, "INSERT", "entity-upsert");
    statement.sql.push_str(
        " ON CONFLICT(id) DO UPDATE SET namespace=excluded.namespace, kind=excluded.kind, \
         entity_type=excluded.entity_type, name=excluded.name, description=excluded.description, \
         properties=excluded.properties, tags=excluded.tags, created_at=excluded.created_at, \
         updated_at=excluded.updated_at, deleted_at=excluded.deleted_at, \
         merged_into=excluded.merged_into, merge_event_id=excluded.merge_event_id, \
         version=entities.version+1",
    );
    statement
}

fn entity_write_statement(entity: &Entity, insert: &str, label: &str) -> SqlStatement {
    let properties_str = entity
        .properties
        .as_ref()
        .map(|v| serde_json::to_string(v).unwrap_or_default());
    let tags_str = serde_json::to_string(&entity.tags).unwrap_or_else(|_| "[]".to_string());
    SqlStatement {
        sql: format!(
            "{insert} INTO entities \
              (id, namespace, kind, entity_type, name, description, properties, tags, \
               created_at, updated_at, deleted_at, merged_into, merge_event_id) \
              VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)"
        ),
        params: vec![
            SqlValue::Text(entity.id.to_string()),
            SqlValue::Text(entity.namespace.clone()),
            SqlValue::Text(entity.kind.clone()),
            match &entity.entity_type {
                Some(t) => SqlValue::Text(t.clone()),
                None => SqlValue::Null,
            },
            SqlValue::Text(entity.name.clone()),
            match &entity.description {
                Some(d) => SqlValue::Text(d.clone()),
                None => SqlValue::Null,
            },
            match properties_str {
                Some(p) => SqlValue::Text(p),
                None => SqlValue::Null,
            },
            SqlValue::Text(tags_str),
            SqlValue::Integer(entity.created_at),
            SqlValue::Integer(entity.updated_at),
            match entity.deleted_at {
                Some(d) => SqlValue::Integer(d),
                None => SqlValue::Null,
            },
            match entity.merged_into {
                Some(u) => SqlValue::Text(u.to_string()),
                None => SqlValue::Null,
            },
            match entity.merge_event_id {
                Some(u) => SqlValue::Text(u.to_string()),
                None => SqlValue::Null,
            },
        ],
        label: Some(label.to_string()),
    }
}

/// Claim caller `key` for `kind` in `namespace` on behalf of `entity_id`.
///
/// Inserts one row when no live holder has the key and none otherwise, so an
/// atomic plan guards it at exactly one affected row: zero means another
/// entity holds the key, and the caller re-reads the holder (ADR-221 section 1).
pub fn entity_key_claim_statement(
    namespace: &str,
    kind: &str,
    key: &str,
    entity_id: Uuid,
    created_at: i64,
) -> SqlStatement {
    SqlStatement {
        sql: "INSERT INTO entity_keys (namespace, kind, key, entity_id, created_at) \
              SELECT ?1, ?2, ?3, ?4, ?5 \
              WHERE NOT EXISTS (SELECT 1 FROM entity_keys \
                WHERE namespace = ?1 AND kind = ?2 AND key = ?3 AND released_at IS NULL)"
            .to_string(),
        params: vec![
            SqlValue::Text(namespace.to_string()),
            SqlValue::Text(kind.to_string()),
            SqlValue::Text(key.to_string()),
            SqlValue::Text(entity_id.to_string()),
            SqlValue::Integer(created_at),
        ],
        label: Some(ENTITY_KEY_CLAIM_LABEL.to_string()),
    }
}

/// Statement label of [`entity_key_claim_statement`], matched by callers that
/// read a failed claim guard as a held key.
pub const ENTITY_KEY_CLAIM_LABEL: &str = "entity-key-claim";

/// Store `alias` for `entity_id` with `origin` (ADR-221 section 2).
///
/// An alias the entity already holds keeps its row and origin, so the
/// statement affects one row or none; callers do not guard it.
pub fn entity_alias_insert_statement(
    namespace: &str,
    entity_id: Uuid,
    alias: &str,
    origin: EntityAliasOrigin,
    created_at: i64,
) -> SqlStatement {
    SqlStatement {
        sql: "INSERT OR IGNORE INTO entity_aliases \
              (namespace, entity_id, alias, origin, created_at) \
              VALUES (?1, ?2, ?3, ?4, ?5)"
            .to_string(),
        params: vec![
            SqlValue::Text(namespace.to_string()),
            SqlValue::Text(entity_id.to_string()),
            SqlValue::Text(alias.to_string()),
            SqlValue::Text(origin.as_str().to_string()),
            SqlValue::Integer(created_at),
        ],
        label: Some("entity-alias-insert".to_string()),
    }
}

/// Remove caller-origin `alias` from `entity_id`. Aliases written by a
/// rename or a merge are never removed by it (ADR-221 section 2).
pub fn entity_caller_alias_delete_statement(
    namespace: &str,
    entity_id: Uuid,
    alias: &str,
) -> SqlStatement {
    SqlStatement {
        sql: "DELETE FROM entity_aliases \
              WHERE namespace = ?1 AND entity_id = ?2 AND alias = ?3 AND origin = 'caller'"
            .to_string(),
        params: vec![
            SqlValue::Text(namespace.to_string()),
            SqlValue::Text(entity_id.to_string()),
            SqlValue::Text(alias.to_string()),
        ],
        label: Some("entity-caller-alias-delete".to_string()),
    }
}

/// Remove the alias row of `entity_id` equal to `name`, whatever wrote it.
/// An alias never equals its entity's name, so an entity renamed to an alias
/// it holds loses that row, of any origin (ADR-221 section 2).
pub fn entity_name_alias_delete_statement(
    namespace: &str,
    entity_id: Uuid,
    name: &str,
) -> SqlStatement {
    SqlStatement {
        sql: "DELETE FROM entity_aliases \
              WHERE namespace = ?1 AND entity_id = ?2 AND alias = ?3"
            .to_string(),
        params: vec![
            SqlValue::Text(namespace.to_string()),
            SqlValue::Text(entity_id.to_string()),
            SqlValue::Text(name.to_string()),
        ],
        label: Some("entity-name-alias-delete".to_string()),
    }
}

/// Remove every alias row of `entity_id`. A merge carries the merged-away
/// entity's names to the kept entity as `merge` aliases and drops the merged-away
/// entity's own rows (ADR-221 section 3).
pub fn entity_aliases_delete_all_statement(namespace: &str, entity_id: Uuid) -> SqlStatement {
    SqlStatement {
        sql: "DELETE FROM entity_aliases WHERE namespace = ?1 AND entity_id = ?2".to_string(),
        params: vec![
            SqlValue::Text(namespace.to_string()),
            SqlValue::Text(entity_id.to_string()),
        ],
        label: Some("entity-aliases-delete-all".to_string()),
    }
}

/// Held keys of one entity as `(kind, key)` rows, ordered by kind then key.
/// Parameters: `?1` namespace, `?2` entity id.
pub const ENTITY_HELD_KEYS_SQL: &str = "SELECT kind, key FROM entity_keys \
     WHERE namespace = ?1 AND entity_id = ?2 AND released_at IS NULL \
     ORDER BY kind, key";

/// The entity holding one key, if any. Parameters: `?1` namespace, `?2` kind,
/// `?3` key.
pub const ENTITY_KEY_HOLDER_SQL: &str = "SELECT entity_id FROM entity_keys \
     WHERE namespace = ?1 AND kind = ?2 AND key = ?3 AND released_at IS NULL";

/// Every key row of one namespace, held or released, as
/// `(entity_id, kind, key, released_at)` rows ordered by entity, kind and key.
/// Parameter: `?1` namespace.
pub const NAMESPACE_KEY_ROWS_SQL: &str = "SELECT entity_id, kind, key, released_at \
     FROM entity_keys WHERE namespace = ?1 ORDER BY entity_id, kind, key";

/// Hand a held key of `from_id` to `into_id` under `into_kind`, as a merge does
/// before it tombstones `from_id`: the tombstone releases every key its row
/// still holds (ADR-221 section 3). Affects one row while the key is held.
pub fn entity_key_move_statement(
    namespace: &str,
    from_id: Uuid,
    from_kind: &str,
    key: &str,
    into_id: Uuid,
    into_kind: &str,
) -> SqlStatement {
    SqlStatement {
        sql: "UPDATE entity_keys SET entity_id = ?5, kind = ?6 \
              WHERE namespace = ?1 AND entity_id = ?2 AND kind = ?3 AND key = ?4 \
                AND released_at IS NULL"
            .to_string(),
        params: vec![
            SqlValue::Text(namespace.to_string()),
            SqlValue::Text(from_id.to_string()),
            SqlValue::Text(from_kind.to_string()),
            SqlValue::Text(key.to_string()),
            SqlValue::Text(into_id.to_string()),
            SqlValue::Text(into_kind.to_string()),
        ],
        label: Some("entity-key-move".to_string()),
    }
}

/// Remove a held key row of `entity_id`. A merge drops the merged-away
/// entity's row for a key the kept entity already holds (ADR-221 section 3).
pub fn entity_key_drop_statement(
    namespace: &str,
    entity_id: Uuid,
    kind: &str,
    key: &str,
) -> SqlStatement {
    SqlStatement {
        sql: "DELETE FROM entity_keys \
              WHERE namespace = ?1 AND entity_id = ?2 AND kind = ?3 AND key = ?4 \
                AND released_at IS NULL"
            .to_string(),
        params: vec![
            SqlValue::Text(namespace.to_string()),
            SqlValue::Text(entity_id.to_string()),
            SqlValue::Text(kind.to_string()),
            SqlValue::Text(key.to_string()),
        ],
        label: Some("entity-key-drop".to_string()),
    }
}

/// Conditional-insert companion to [`entity_upsert_statement`]. Every
/// conflict leaves the existing row untouched so a caller can read the
/// winner and explicitly reapply its intended delta.
pub fn entity_insert_if_absent_statement(entity: &Entity) -> SqlStatement {
    let mut statement = entity_upsert_statement(entity);
    statement.sql = "INSERT INTO entities \
              (id, namespace, kind, entity_type, name, description, properties, tags, \
               created_at, updated_at, deleted_at, merged_into, merge_event_id) \
              VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13) \
              ON CONFLICT DO NOTHING"
        .to_string();
    statement.label = Some("entity-insert-if-absent".to_string());
    statement
}

/// Full-entity compare-and-swap update used after caller-side normalization
/// was derived from a read snapshot. Unlike [`entity_upsert_statement`], this
/// never inserts and cannot overwrite a row whose revision or deletion
/// marker moved after the snapshot was read. The replacement revision must
/// also be strictly greater than the persisted snapshot timestamp. The
/// replacement's `version` is the expected persisted snapshot revision; the
/// UPDATE advances it exactly once. Timestamp equality
/// is a refused CAS, never a successful write with an unchanged concurrency
/// token. Mirrors `note_replace_if_unchanged_statement`
/// (`crates/khive-db/src/stores/note.rs`).
pub fn entity_replace_if_unchanged_statement(
    entity: &Entity,
    expected_updated_at: i64,
    expected_deleted_at: Option<i64>,
) -> SqlStatement {
    let properties_str = entity
        .properties
        .as_ref()
        .map(|v| serde_json::to_string(v).unwrap_or_default());
    let tags_str = serde_json::to_string(&entity.tags).unwrap_or_else(|_| "[]".to_string());
    SqlStatement {
        sql: "UPDATE entities SET \
                namespace = ?1, kind = ?2, entity_type = ?3, name = ?4, description = ?5, \
                properties = ?6, tags = ?7, updated_at = ?8, deleted_at = ?9, \
                merged_into = ?10, merge_event_id = ?11, version = version + 1 \
              WHERE id = ?12 AND updated_at = ?13 AND deleted_at IS ?14 \
                AND ?8 > updated_at AND version = ?15"
            .to_string(),
        params: vec![
            SqlValue::Text(entity.namespace.clone()),
            SqlValue::Text(entity.kind.clone()),
            match &entity.entity_type {
                Some(t) => SqlValue::Text(t.clone()),
                None => SqlValue::Null,
            },
            SqlValue::Text(entity.name.clone()),
            match &entity.description {
                Some(d) => SqlValue::Text(d.clone()),
                None => SqlValue::Null,
            },
            match properties_str {
                Some(p) => SqlValue::Text(p),
                None => SqlValue::Null,
            },
            SqlValue::Text(tags_str),
            SqlValue::Integer(entity.updated_at),
            match entity.deleted_at {
                Some(d) => SqlValue::Integer(d),
                None => SqlValue::Null,
            },
            match entity.merged_into {
                Some(u) => SqlValue::Text(u.to_string()),
                None => SqlValue::Null,
            },
            match entity.merge_event_id {
                Some(u) => SqlValue::Text(u.to_string()),
                None => SqlValue::Null,
            },
            SqlValue::Text(entity.id.to_string()),
            SqlValue::Integer(expected_updated_at),
            match expected_deleted_at {
                Some(value) => SqlValue::Integer(value),
                None => SqlValue::Null,
            },
            SqlValue::Integer(entity.version),
        ],
        label: Some("entity-replace-if-unchanged".to_string()),
    }
}

/// The exact soft-delete `UPDATE` this store's `delete_entity(Soft)` issues.
pub fn entity_soft_delete_statement(id: Uuid, deleted_at: i64) -> SqlStatement {
    SqlStatement {
        sql: "UPDATE entities SET deleted_at = ?1, version = version + 1 WHERE id = ?2 AND deleted_at IS NULL".to_string(),
        params: vec![
            SqlValue::Integer(deleted_at),
            SqlValue::Text(id.to_string()),
        ],
        label: Some("entity-delete-soft".to_string()),
    }
}

/// Preserve merge provenance when tombstoning a live source in its existing namespace.
pub fn entity_merge_tombstone_statement(
    namespace: &str,
    from_id: Uuid,
    into_id: Uuid,
    merge_event_id: Uuid,
    now: i64,
) -> SqlStatement {
    SqlStatement::new(
        "UPDATE entities \
             SET deleted_at = ?1, merged_into = ?2, merge_event_id = ?3, updated_at = ?1, version = version + 1 \
             WHERE namespace = ?4 AND id = ?5 AND deleted_at IS NULL",
        vec![
            SqlValue::Integer(now),
            SqlValue::Text(into_id.to_string()),
            SqlValue::Text(merge_event_id.to_string()),
            SqlValue::Text(namespace.to_string()),
            SqlValue::Text(from_id.to_string()),
        ],
    )
    .labelled("entity-merge-tombstone")
}

/// The exact hard-delete `DELETE` this store's `delete_entity(Hard)` issues
/// (no `deleted_at` predicate — purges live and already-tombstoned rows).
pub fn entity_hard_delete_statement(id: Uuid) -> SqlStatement {
    SqlStatement {
        sql: "DELETE FROM entities WHERE id = ?1".to_string(),
        params: vec![SqlValue::Text(id.to_string())],
        label: Some("entity-delete-hard".to_string()),
    }
}

/// An EntityStore backed by SQLite. Namespace is the caller's responsibility.
///
/// UUID is globally unique — get/delete by ID alone. Query/count use the
/// namespace parameter as passed. Read routing is always pool-backed; the
/// constructor's legacy file-backed flag is retained for API compatibility.
pub struct SqlEntityStore {
    pool: Arc<ConnectionPool>,
    writer_task: Option<WriterTaskHandle>,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum EntityPageMode {
    ExactTotal,
    CountFree,
}

impl EntityPageMode {
    fn operation(self) -> &'static str {
        match self {
            Self::ExactTotal => "query_entities",
            Self::CountFree => "query_entities_count_free",
        }
    }
}

impl SqlEntityStore {
    /// Create a new store.
    ///
    /// When `KHIVE_WRITE_QUEUE=1` (`PoolConfig::write_queue_enabled`), every
    /// write path on this store — the batch `upsert_entities` (its own
    /// explicit flag check) AND every single-row write routed through the
    /// shared `with_writer` helper (`upsert_entity`, `delete_entity`) —
    /// routes through the pool-wide `WriterTask`
    /// (`ConnectionPool::writer_task_handle`) instead of the legacy
    /// pool-mutex path. The handle is a clone of the ONE writer task owned
    /// by `pool` — constructing multiple stores (or multiple namespaces)
    /// over the same pool never spawns more than one writer task; see
    /// `ConnectionPool::writer_task_handle`'s doc comment for why that
    /// matters. `None` (falling back to the legacy path for every write)
    /// if the resolved flag is off, or if the writer task failed to spawn
    /// (for example, an in-memory pool, which has no standalone-connection
    /// support) — enabled by default for file-backed pools; explicit
    /// off/degraded fallback remains possible.
    pub fn new(pool: Arc<ConnectionPool>, _is_file_backed: bool) -> Self {
        // Enabled by default for file-backed pools; explicit off/degraded
        // fallback remains possible: a missing writer task — whether
        // explicitly disabled, spawn degraded (e.g. in-memory pool), or no
        // Tokio runtime was available at this first access (ADR-067
        // Component A runtime-handle guard) — is cached without failing
        // construction. Every write re-resolves it; strict mode refuses a
        // remaining miss and compatibility mode may use the legacy path.
        let writer_task = pool.writer_task_handle().ok().flatten();

        Self { pool, writer_task }
    }

    fn current_writer_task(
        &self,
        operation: &'static str,
    ) -> Result<Option<WriterTaskHandle>, StorageError> {
        self.pool
            .writer_task_for_write(self.writer_task.as_ref(), operation)
    }

    /// Route a single-row write through the pool-wide `WriterTask` when
    /// the write queue is enabled and a handle is available. Strict mode
    /// refuses a missing handle; compatibility mode falls back to the legacy
    /// pool-mutex path.
    ///
    /// ADR-067 Component A (Fork C slice 2): this is the ONE routing point
    /// for every `with_writer` caller in this store — `upsert_entity`,
    /// `delete_entity` (soft/hard) all reach the WriterTask through this
    /// helper rather than each duplicating the flag check. `f` must be
    /// DML-only (a single statement, no bare `BEGIN IMMEDIATE`): on the
    /// flag-on path it runs inside the WriterTask's own transaction, and a
    /// nested `BEGIN IMMEDIATE` would violate SQLite's nested-transaction
    /// rule. `upsert_entities` (the batch method) performs the same write-time
    /// lookup first; a non-strict `None` then falls through this helper, which
    /// records the actual compatibility fallback. Strict mode returns before
    /// either direct-writer seam is reached.
    async fn with_writer<F, R>(&self, op: &'static str, f: F) -> Result<R, StorageError>
    where
        F: FnOnce(&rusqlite::Connection) -> Result<R, rusqlite::Error> + Send + 'static,
        R: Send + 'static,
    {
        if let Some(writer_task) = self.current_writer_task(op)? {
            return writer_task
                .send_bounded_at(move |conn| f(conn).map_err(|e| map_err(e, op)), op)
                .await;
        }

        self.pool
            .record_direct_route(crate::timeout_sink::Site::DirectRouteEntity);
        let pool = Arc::clone(&self.pool);
        tokio::task::spawn_blocking(move || {
            let guard = pool
                .autocommit_write_unit()
                .map_err(|e| map_sqlite_err(e, op))?;
            f(guard.conn())
                .map_err(|e| map_err(e, op))
                .map_err(crate::error::statement_failure)
                .inspect_err(|error| pool.record_direct_writer_error(error))
        })
        .await
        .map_err(|e| StorageError::driver(StorageCapability::Entities, op, e))?
    }

    /// Route multi-statement entity mutations through one write transaction.
    /// The writer task already supplies that transaction; the direct fallback
    /// opens and closes its own fail-closed `BEGIN IMMEDIATE` unit.
    async fn with_writer_tx<F, R>(&self, op: &'static str, f: F) -> Result<R, StorageError>
    where
        F: FnOnce(&rusqlite::Connection) -> Result<R, rusqlite::Error> + Send + 'static,
        R: Send + 'static,
    {
        if let Some(writer_task) = self.current_writer_task(op)? {
            return writer_task
                .send_bounded_at(move |conn| f(conn).map_err(|error| map_err(error, op)), op)
                .await;
        }

        self.pool
            .record_direct_route(crate::timeout_sink::Site::DirectRouteEntity);
        let pool = Arc::clone(&self.pool);
        tokio::task::spawn_blocking(move || {
            let mut guard = pool
                .transaction_write_unit()
                .map_err(|error| map_sqlite_err(error, op))
                .inspect_err(|error| pool.record_direct_writer_error(error))?;
            let conn = guard.conn();
            let (result, terminal_state) = execute_wrapped_transaction(conn, op, move |conn| {
                f(conn).map_err(|error| map_err(error, op))
            });
            if terminal_state.is_some() {
                pool.retire_pooled_writer(guard.conn_mut());
            }
            result.inspect_err(|error| pool.record_direct_writer_error(error))
        })
        .await
        .map_err(|error| StorageError::driver(StorageCapability::Entities, op, error))?
    }

    async fn with_reader<F, R>(&self, op: &'static str, f: F) -> Result<R, StorageError>
    where
        F: FnOnce(&rusqlite::Connection) -> Result<R, rusqlite::Error> + Send + 'static,
        R: Send + 'static,
    {
        super::run_pooled_store_read(
            Arc::clone(&self.pool),
            StorageCapability::Entities,
            op,
            move |conn| f(conn).map_err(|error| map_err(error, op)),
        )
        .await
    }

    async fn with_list_reader<F, R>(
        &self,
        op: &'static str,
        index: Option<&'static str>,
        mut read: F,
    ) -> Result<R, StorageError>
    where
        F: FnMut(&rusqlite::Connection, bool) -> Result<R, rusqlite::Error> + Send + 'static,
        R: Send + 'static,
    {
        let dispatch = tracing::dispatcher::get_default(Clone::clone);
        self.with_reader(op, move |conn| match read(conn, true) {
            Ok(value) => Ok(value),
            Err(error) => {
                let Some(index) = index.filter(|index| missing_list_index(&error, index)) else {
                    return Err(error);
                };
                tracing::dispatcher::with_default(&dispatch, || {
                    tracing::warn!(
                        index,
                        operation = op,
                        "entity list index missing; retrying without forced index"
                    );
                });
                read(conn, false)
            }
        })
        .await
    }

    async fn query_entities_page(
        &self,
        namespace: &str,
        filter: EntityFilter,
        page: PageRequest,
        mode: EntityPageMode,
    ) -> Result<Page<Entity>, StorageError> {
        let operation = mode.operation();
        super::validate_json_equality_paths(
            &filter.property_equalities,
            StorageCapability::Entities,
            operation,
        )?;
        super::validate_json_prefix_paths(
            &filter.property_prefixes,
            StorageCapability::Entities,
            operation,
        )?;
        let namespace = namespace.to_string();
        let skip_total = mode == EntityPageMode::CountFree || is_complete_id_lookup(&filter, &page);
        let limit_i64 = i64::from(page.limit);
        let offset_i64 = i64::try_from(page.offset).map_err(|_| StorageError::InvalidInput {
            capability: StorageCapability::Entities,
            operation: operation.into(),
            message: format!(
                "PageRequest: offset must be <= i64::MAX, got {}",
                page.offset
            ),
        })?;

        let streaming = mode == EntityPageMode::CountFree && is_entity_streaming_page(&filter);
        let index = if streaming {
            entity_count_free_index(&filter)
        } else {
            entity_list_index(&filter)
        };
        let read = move |conn: &rusqlite::Connection, force_index| {
            let total = if filter.names_ci.is_empty() && !skip_total {
                let (count_sql, count_params) = build_entity_where(&namespace, &filter);
                let sql = entity_list_query(
                    &filter,
                    build_entity_count_query(&filter, &count_sql),
                    force_index,
                );
                let mut stmt = conn.prepare(&sql)?;
                let param_refs: Vec<&dyn rusqlite::types::ToSql> =
                    count_params.iter().map(|p| p.as_ref()).collect();
                Some(stmt.query_row(param_refs.as_slice(), |row| row.get::<_, i64>(0))? as u64)
            } else {
                None
            };

            let mut lookup_filter = filter.clone();
            lookup_filter.names_ci.clear();
            let effective_filter = if filter.names_ci.is_empty() {
                &filter
            } else {
                &lookup_filter
            };
            let (where_sql, mut data_params) = if streaming {
                build_entity_streaming_where(&namespace, effective_filter)
            } else {
                build_entity_where(&namespace, effective_filter)
            };

            let candidate_param_indices = if filter.names_ci.is_empty() {
                Vec::new()
            } else {
                let mut candidates: Vec<String> = filter
                    .names_ci
                    .iter()
                    .map(|name| name.to_ascii_lowercase())
                    .collect();
                candidates.sort_unstable();
                candidates.dedup();
                candidates
                    .into_iter()
                    .map(|candidate| {
                        data_params.push(Box::new(candidate));
                        data_params.len()
                    })
                    .collect()
            };

            // #818: when a name_prefix filter is active, an exact
            // ASCII-case-insensitive match must never be pushed out of the page by
            // pattern candidates that merely share the prefix. Rank exact
            // matches first (deterministic tiebreak via created_at) so page
            // truncation can never hide the record a caller resolved by name.
            let order_by = if let Some(ref prefix) = filter.name_prefix {
                data_params.push(Box::new(prefix.to_ascii_lowercase()));
                format!(
                    "CASE WHEN LOWER(name) = ?{} THEN 0 ELSE 1 END, created_at DESC, id DESC",
                    data_params.len()
                )
            } else {
                // #1671: append `id` as the final tiebreak in the primary
                // key's direction so equal-`created_at` rows keep a fixed
                // order across page boundaries. The deterministic total order
                // removes tie-order instability only — offset paging can still
                // duplicate or skip rows under concurrent inserts/deletes or
                // sort-key updates (that would need snapshot isolation or
                // keyset pagination).
                "created_at DESC, id DESC".to_string()
            };

            data_params.push(Box::new(limit_i64));
            data_params.push(Box::new(offset_i64));

            let limit_idx = data_params.len() - 1;
            let offset_idx = data_params.len();

            let columns = ENTITY_SELECT_COLUMNS;
            let data_sql = if streaming {
                build_entity_count_free_page_query(
                    columns,
                    effective_filter,
                    &where_sql,
                    &order_by,
                    limit_idx,
                    offset_idx,
                )
            } else if filter.names_ci.is_empty() {
                build_entity_page_query(
                    columns,
                    effective_filter,
                    &where_sql,
                    &order_by,
                    limit_idx,
                    offset_idx,
                )
            } else {
                build_candidate_entity_query(
                    columns,
                    effective_filter,
                    &where_sql,
                    &candidate_param_indices,
                    &order_by,
                    limit_idx,
                    offset_idx,
                )
            };

            let data_sql = if streaming {
                entity_count_free_query(effective_filter, data_sql, force_index)
            } else {
                entity_list_query(effective_filter, data_sql, force_index)
            };
            let mut stmt = conn.prepare(&data_sql)?;
            let param_refs: Vec<&dyn rusqlite::types::ToSql> =
                data_params.iter().map(|p| p.as_ref()).collect();
            let rows = stmt.query_map(param_refs.as_slice(), read_entity)?;

            let mut items = Vec::new();
            for row in rows {
                items.push(row?);
            }

            Ok(Page { items, total })
        };
        self.with_list_reader(operation, index, read).await
    }
}

// =============================================================================
// Helpers
// =============================================================================

fn read_entity(row: &rusqlite::Row<'_>) -> Result<Entity, rusqlite::Error> {
    let id_str: String = row.get(0)?;
    let namespace: String = row.get(1)?;
    let kind: String = row.get(2)?;
    let entity_type: Option<String> = row.get(3)?;
    let name: String = row.get(4)?;
    let description: Option<String> = row.get(5)?;
    let properties_str: Option<String> = row.get(6)?;
    let tags_str: String = row.get(7)?;
    let created_at: i64 = row.get(8)?;
    let updated_at: i64 = row.get(9)?;
    let deleted_at: Option<i64> = row.get(10)?;
    let merged_into_str: Option<String> = row.get(11)?;
    let merge_event_id_str: Option<String> = row.get(12)?;
    let content_ref: Option<String> = row.get(13)?;
    let version: i64 = row.get(14)?;
    let aliases_str: String = row.get(15)?;

    let id = parse_uuid(&id_str)?;

    let properties = properties_str
        .map(|s| {
            serde_json::from_str(&s).map_err(|e| {
                rusqlite::Error::FromSqlConversionFailure(
                    6,
                    rusqlite::types::Type::Text,
                    Box::new(e),
                )
            })
        })
        .transpose()?;

    let tags: Vec<String> = serde_json::from_str(&tags_str).map_err(|e| {
        rusqlite::Error::FromSqlConversionFailure(7, rusqlite::types::Type::Text, Box::new(e))
    })?;

    let merged_into = merged_into_str
        .as_deref()
        .map(Uuid::parse_str)
        .transpose()
        .map_err(|e| {
            rusqlite::Error::FromSqlConversionFailure(10, rusqlite::types::Type::Text, Box::new(e))
        })?;

    let merge_event_id = merge_event_id_str
        .as_deref()
        .map(Uuid::parse_str)
        .transpose()
        .map_err(|e| {
            rusqlite::Error::FromSqlConversionFailure(11, rusqlite::types::Type::Text, Box::new(e))
        })?;

    let aliases = read_entity_aliases(&aliases_str)?;

    Ok(Entity {
        id,
        namespace,
        kind,
        entity_type,
        name,
        description,
        properties,
        tags,
        created_at,
        updated_at,
        version,
        deleted_at,
        merged_into,
        merge_event_id,
        content_ref,
        aliases,
    })
}

fn read_entity_aliases(text: &str) -> Result<Vec<EntityAlias>, rusqlite::Error> {
    parse_entity_aliases(text).map_err(|error| {
        rusqlite::Error::FromSqlConversionFailure(15, rusqlite::types::Type::Text, error.into())
    })
}

/// Parse a value of [`ENTITY_ALIASES_COLUMN`]: a JSON array of
/// `[alias, origin]` pairs, returned sorted by alias. An origin other than
/// `caller`, `rename` or `merge` is an error.
pub fn parse_entity_aliases(text: &str) -> Result<Vec<EntityAlias>, String> {
    let pairs: Vec<(String, String)> =
        serde_json::from_str(text).map_err(|error| format!("entity aliases: {error}"))?;
    let mut aliases = pairs
        .into_iter()
        .map(|(alias, origin)| {
            EntityAliasOrigin::parse(&origin)
                .map(|origin| EntityAlias { alias, origin })
                .ok_or_else(|| format!("unknown entity alias origin {origin:?}"))
        })
        .collect::<Result<Vec<_>, _>>()?;
    aliases.sort();
    Ok(aliases)
}

/// DML-only batch upsert loop shared by both the legacy (flag-off) and
/// WriterTask-routed (flag-on) `upsert_entities` paths (ADR-067 slice 1).
///
/// Issues no `BEGIN` / `COMMIT` / `ROLLBACK` itself — the caller owns the
/// enclosing transaction. Per-row failures are captured into
/// `BatchWriteSummary::failed`/`first_error` rather than aborting the loop,
/// matching the existing partial-success contract: this function's own
/// `Result` is `Ok` unless a caller bug is present, since no branch here
/// returns `Err`.
fn batch_upsert_entities(
    conn: &rusqlite::Connection,
    entities: &[Entity],
    attempted: u64,
) -> Result<BatchWriteSummary, rusqlite::Error> {
    let mut summary = BatchWriteSummary {
        attempted,
        ..BatchWriteSummary::default()
    };

    for (index, entity) in entities.iter().enumerate() {
        let id_str = entity.id.to_string();
        let statement = entity_upsert_statement(entity);
        let result = (|| {
            let mut prepared = conn.prepare(&statement.sql)?;
            bind_params(&mut prepared, &statement.params)?;
            prepared.raw_execute()
        })();
        match result {
            Ok(_) => summary.affected = summary.affected.saturating_add(1),
            Err(e) => {
                let (class, retryability) = super::classify_batch_sqlite_error(&e);
                summary.record_failure(index, Some(id_str), class, retryability, e.to_string());
            }
        }
    }

    Ok(summary)
}

fn parse_uuid(s: &str) -> Result<Uuid, rusqlite::Error> {
    Uuid::parse_str(s).map_err(|e| {
        rusqlite::Error::FromSqlConversionFailure(0, rusqlite::types::Type::Text, Box::new(e))
    })
}

fn build_entity_where(
    namespace: &str,
    filter: &EntityFilter,
) -> (String, Vec<Box<dyn rusqlite::types::ToSql>>) {
    build_entity_where_with_mode(namespace, filter, false)
}

/// Evaluate legacy type membership on the current row instead of first
/// materializing every matching entity ID. Deduplication also makes each
/// single-value ordered-index prefix a single SQL bound value.
fn build_entity_streaming_where(
    namespace: &str,
    filter: &EntityFilter,
) -> (String, Vec<Box<dyn rusqlite::types::ToSql>>) {
    let mut filter = filter.clone();
    for values in [
        &mut filter.namespaces,
        &mut filter.kinds,
        &mut filter.entity_types,
    ] {
        values.sort_unstable();
        values.dedup();
    }
    for values in filter.entity_types_by_kind.values_mut() {
        values.sort_unstable();
        values.dedup();
    }
    build_entity_where_with_mode(namespace, &filter, true)
}

fn build_entity_where_with_mode(
    namespace: &str,
    filter: &EntityFilter,
    row_local: bool,
) -> (String, Vec<Box<dyn rusqlite::types::ToSql>>) {
    // When filter.namespaces is non-empty use `namespace IN (...)` so that
    // multi-namespace read visibility works.  Otherwise fall back to the
    // single-namespace equality check for backward compatibility.
    let (ns_condition, ns_params): (String, Vec<Box<dyn rusqlite::types::ToSql>>) =
        if !filter.namespaces.is_empty() {
            let placeholders: Vec<String> = (1..=filter.namespaces.len())
                .map(|i| format!("?{i}"))
                .collect();
            let params: Vec<Box<dyn rusqlite::types::ToSql>> = filter
                .namespaces
                .iter()
                .map(|ns| -> Box<dyn rusqlite::types::ToSql> { Box::new(ns.clone()) })
                .collect();
            (
                format!("namespace IN ({})", placeholders.join(", ")),
                params,
            )
        } else {
            (
                "namespace = ?1".to_string(),
                vec![Box::new(namespace.to_string())],
            )
        };
    // The namespace parameters are ?1..?N, in the order of `ns_params`.
    let namespace_placeholders = (1..=ns_params.len())
        .map(|i| format!("?{i}"))
        .collect::<Vec<_>>()
        .join(", ");

    let mut conditions: Vec<String> = vec![ns_condition];
    match filter.tombstones {
        EntityTombstones::Live => conditions.push("deleted_at IS NULL".into()),
        EntityTombstones::All => {}
        EntityTombstones::Only => conditions.push("deleted_at IS NOT NULL".into()),
    }
    let mut params: Vec<Box<dyn rusqlite::types::ToSql>> = ns_params;

    if !filter.ids.is_empty() {
        let placeholders: Vec<String> = filter
            .ids
            .iter()
            .map(|id| {
                params.push(Box::new(id.to_string()));
                format!("?{}", params.len())
            })
            .collect();
        conditions.push(format!("id IN ({})", placeholders.join(", ")));
    }

    if !filter.kinds.is_empty() {
        let placeholders: Vec<String> = filter
            .kinds
            .iter()
            .map(|k| {
                params.push(Box::new(k.clone()));
                format!("?{}", params.len())
            })
            .collect();
        conditions.push(format!("kind IN ({})", placeholders.join(", ")));
    }

    let type_scope = conditions.join(" AND ");
    let type_predicate = |scope: &str, placeholders: &str| {
        if filter.legacy_entity_type_fallback && row_local {
            // CASE is lazy: malformed JSON never reaches json_type/extract.
            // A present canonical type always wins over legacy properties.
            format!(
                "CASE WHEN entity_type IS NOT NULL THEN entity_type IN ({placeholders}) \
                 WHEN json_valid(properties) THEN \
                     CASE WHEN json_type(properties, '$.type') = 'text' \
                          THEN json_extract(properties, '$.type') IN ({placeholders}) \
                          ELSE 0 END \
                 ELSE 0 END"
            )
        } else if filter.legacy_entity_type_fallback {
            // Legacy properties can contain invalid JSON. Exclude those rows
            // from type fallback without rewriting them. Keep json_valid as
            // an explicit term matching the partial legacy-type index;
            // json_type alone does not imply its validity predicate to SQLite.
            format!(
                "id IN (SELECT id FROM entities WHERE {scope} \
                 AND entity_type IN ({placeholders}) \
                 UNION ALL SELECT id FROM entities WHERE {scope} \
                 AND entity_type IS NULL AND json_valid(properties) \
                 AND json_type(properties, '$.type') = 'text' \
                 AND json_extract(properties, '$.type') IN ({placeholders}))"
            )
        } else {
            format!("entity_type IN ({placeholders})")
        }
    };
    if !filter.entity_types.is_empty() {
        let placeholders: Vec<String> = filter
            .entity_types
            .iter()
            .map(|t| {
                params.push(Box::new(t.clone()));
                format!("?{}", params.len())
            })
            .collect();
        conditions.push(type_predicate(&type_scope, &placeholders.join(", ")));
    }

    if !filter.entity_types_by_kind.is_empty() {
        let mut groups = Vec::new();
        for (kind, types) in &filter.entity_types_by_kind {
            if types.is_empty() {
                continue;
            }
            params.push(Box::new(kind.clone()));
            let kind_param = params.len();
            let placeholders = types
                .iter()
                .map(|value| {
                    params.push(Box::new(value.clone()));
                    format!("?{}", params.len())
                })
                .collect::<Vec<_>>()
                .join(", ");
            let scope = format!("{type_scope} AND kind = ?{kind_param}");
            let predicate = type_predicate(&scope, &placeholders);
            groups.push(format!("(kind = ?{kind_param} AND {predicate})"));
        }
        conditions.push(if groups.is_empty() {
            "0".to_string()
        } else {
            format!("({})", groups.join(" OR "))
        });
    }

    if let Some(ref prefix) = filter.name_prefix {
        params.push(Box::new(format!(
            "{}%",
            khive_types::escape_like_literal(prefix)
        )));
        conditions.push(format!("name LIKE ?{} ESCAPE '\\'", params.len()));
    }

    if let Some(ref exact) = filter.name_exact {
        params.push(Box::new(exact.clone()));
        // `entities.name` has no `COLLATE NOCASE` (see sql/schema.sql), so
        // `=` is already SQLite's default case-sensitive BINARY comparison.
        // `COLLATE BINARY` is spelled out here so this predicate stays
        // correct even if the column's default collation ever changes.
        conditions.push(format!("name = ?{} COLLATE BINARY", params.len()));
    }

    if let Some(ref exact) = filter.name_or_alias_exact {
        params.push(Box::new(exact.clone()));
        let index = params.len();
        // An id list from two index seeks, names from idx_entities_name and
        // aliases from idx_entity_aliases_alias, each bound to the filter's
        // namespaces. `entity_read_source` pins the primary key so the list
        // drives the read. Without statistics SQLite reads an OR of the two
        // terms, or a subquery that refers to the outer row, by walking the
        // whole namespace.
        conditions.push(format!(
            "id IN (SELECT named.id FROM entities AS named \
             WHERE named.namespace IN ({namespace_placeholders}) \
             AND named.name = ?{index} COLLATE BINARY \
             UNION ALL SELECT entity_alias.entity_id \
             FROM entity_aliases AS entity_alias \
             WHERE entity_alias.namespace IN ({namespace_placeholders}) \
             AND entity_alias.alias = ?{index} COLLATE BINARY)"
        ));
    }

    if !filter.names_ci.is_empty() {
        // ADR-104 Stage C, R1: one batched `LOWER(name) IN (...)` predicate,
        // served by `idx_entities_namespace_name_ci (namespace, LOWER(name))`.
        let placeholders: Vec<String> = filter
            .names_ci
            .iter()
            .map(|n| {
                params.push(Box::new(n.to_ascii_lowercase()));
                format!("?{}", params.len())
            })
            .collect();
        conditions.push(format!("LOWER(name) IN ({})", placeholders.join(", ")));
    }

    if !filter.tags_any.is_empty() {
        let placeholders: Vec<String> = filter
            .tags_any
            .iter()
            .map(|t| {
                // Normalise to lowercase so the comparison is case-insensitive
                // domain filter must be case-insensitive.
                params.push(Box::new(t.to_lowercase()));
                format!("?{}", params.len())
            })
            .collect();
        conditions.push(format!(
            "EXISTS (SELECT 1 FROM json_each(tags) WHERE LOWER(json_each.value) IN ({}))",
            placeholders.join(", ")
        ));
    }

    super::append_json_equalities(
        &mut conditions,
        &mut params,
        "properties",
        &filter.property_equalities,
    );
    super::append_json_prefixes(
        &mut conditions,
        &mut params,
        "properties",
        &filter.property_prefixes,
    );
    let clause = format!(" WHERE {}", conditions.join(" AND "));
    (clause, params)
}

/// An ID-filtered read is bounded by the caller's IDs, even on a fresh
/// database without sqlite_stat1. The other predicates can match a large
/// namespace; letting one of their indexes drive turns a bounded lookup into
/// a scan of every row in that namespace. An exact name-or-alias lookup is
/// bounded the same way, by the id list its predicate seeks.
fn entity_read_source(filter: &EntityFilter) -> &'static str {
    if reads_by_id_list(filter) {
        "entities INDEXED BY sqlite_autoindex_entities_1"
    } else {
        "entities"
    }
}

fn reads_by_id_list(filter: &EntityFilter) -> bool {
    !filter.ids.is_empty() || filter.name_or_alias_exact.is_some()
}

fn build_entity_count_query(filter: &EntityFilter, where_sql: &str) -> String {
    let source = entity_list_source(filter);
    format!("SELECT COUNT(*) FROM {source}{where_sql}")
}

fn build_entity_page_query(
    columns: &str,
    filter: &EntityFilter,
    where_sql: &str,
    order_by: &str,
    limit_idx: usize,
    offset_idx: usize,
) -> String {
    let source = entity_list_source(filter);
    build_entity_page_query_from_source(columns, source, where_sql, order_by, limit_idx, offset_idx)
}

fn build_entity_count_free_page_query(
    columns: &str,
    filter: &EntityFilter,
    where_sql: &str,
    order_by: &str,
    limit_idx: usize,
    offset_idx: usize,
) -> String {
    let source = entity_count_free_source(filter);
    build_entity_page_query_from_source(columns, source, where_sql, order_by, limit_idx, offset_idx)
}

fn build_entity_page_query_from_source(
    columns: &str,
    source: &str,
    where_sql: &str,
    order_by: &str,
    limit_idx: usize,
    offset_idx: usize,
) -> String {
    format!(
        "SELECT {columns} FROM {source}{where_sql} \
         ORDER BY {order_by} LIMIT ?{limit_idx} OFFSET ?{offset_idx}"
    )
}

/// Match only ordinary list shapes whose leading predicates fit these indexes.
/// Keep selective names/kinds/tags and legacy JSON paths free to choose their
/// own access paths. Explicit IDs always keep the bounded primary-key plan.
fn entity_list_source(filter: &EntityFilter) -> &'static str {
    if filter.tombstones != EntityTombstones::Live
        || !filter.property_equalities.is_empty()
        || !filter.property_prefixes.is_empty()
        || !filter.ids.is_empty()
        || !filter.kinds.is_empty()
        || !filter.entity_types_by_kind.is_empty()
        || filter.legacy_entity_type_fallback
        || filter.name_prefix.is_some()
        || filter.name_exact.is_some()
        || filter.name_or_alias_exact.is_some()
        || !filter.names_ci.is_empty()
        || !filter.tags_any.is_empty()
    {
        return entity_read_source(filter);
    }
    if !filter.entity_types.is_empty() {
        "entities INDEXED BY idx_entities_live_namespace_type_order"
    } else if filter.namespaces.len() <= 1 {
        "entities INDEXED BY idx_entities_live_namespace_order"
    } else {
        "entities"
    }
}

fn entity_list_index(filter: &EntityFilter) -> Option<&'static str> {
    if reads_by_id_list(filter) {
        return None;
    }
    entity_list_source(filter).strip_prefix("entities INDEXED BY ")
}

fn is_entity_streaming_page(filter: &EntityFilter) -> bool {
    filter.ids.is_empty()
        && filter.name_prefix.is_none()
        && filter.name_exact.is_none()
        && filter.name_or_alias_exact.is_none()
        && filter.names_ci.is_empty()
}

fn has_one_distinct_value(values: &[String]) -> bool {
    values
        .first()
        .is_some_and(|first| values.iter().all(|value| value == first))
}

/// Pin creation-order walks only when every leading index column is fixed.
/// Other predicates remain row-local residual filters, so the page can stop
/// after its limit without materializing the complete matching ID set.
fn entity_count_free_source(filter: &EntityFilter) -> &'static str {
    if filter.tombstones != EntityTombstones::Live {
        return entity_read_source(filter);
    }
    if !is_entity_streaming_page(filter) {
        return entity_list_source(filter);
    }
    if !filter.namespaces.is_empty() && !has_one_distinct_value(&filter.namespaces) {
        return "entities";
    }
    // A grouped-type map whose groups are all empty matches nothing and becomes
    // a constant-false predicate. SQLite folds it into the WHERE clause and can
    // then no longer prove the `deleted_at IS NULL` term of a partial order
    // index, so forcing one fails with "no query solution".
    if !filter.entity_types_by_kind.is_empty()
        && filter.entity_types_by_kind.values().all(Vec::is_empty)
    {
        return "entities";
    }

    let mut kind_groups = filter
        .entity_types_by_kind
        .iter()
        .filter(|(_, types)| !types.is_empty());
    let one_kind_group = kind_groups.next().is_some() && kind_groups.next().is_none();
    if has_one_distinct_value(&filter.kinds) || one_kind_group {
        "entities INDEXED BY idx_entities_live_namespace_kind_order"
    } else if !filter.legacy_entity_type_fallback && has_one_distinct_value(&filter.entity_types) {
        // Multiple distinct types give multiple ordered runs, not one global
        // creation order. Use the namespace index for that residual predicate.
        "entities INDEXED BY idx_entities_live_namespace_type_order"
    } else {
        "entities INDEXED BY idx_entities_live_namespace_order"
    }
}

fn entity_count_free_index(filter: &EntityFilter) -> Option<&'static str> {
    if reads_by_id_list(filter) {
        return None;
    }
    entity_count_free_source(filter).strip_prefix("entities INDEXED BY ")
}

fn missing_list_index(error: &rusqlite::Error, index: &str) -> bool {
    if error
        .sqlite_error()
        .is_none_or(|detail| detail.extended_code != rusqlite::ffi::SQLITE_ERROR)
    {
        return false;
    }
    let message = match error {
        rusqlite::Error::SqliteFailure(_, Some(message)) => message.as_str(),
        rusqlite::Error::SqlInputError { msg, .. } => msg.as_str(),
        _ => return false,
    };
    message.strip_prefix("no such index: ") == Some(index)
}

fn entity_list_query(filter: &EntityFilter, sql: String, force_index: bool) -> String {
    entity_query_with_index(
        sql,
        entity_list_source(filter),
        entity_list_index(filter),
        force_index,
    )
}

fn entity_count_free_query(filter: &EntityFilter, sql: String, force_index: bool) -> String {
    entity_query_with_index(
        sql,
        entity_count_free_source(filter),
        entity_count_free_index(filter),
        force_index,
    )
}

fn entity_query_with_index(
    sql: String,
    source: &str,
    index: Option<&str>,
    force_index: bool,
) -> String {
    if force_index || index.is_none() {
        sql
    } else {
        sql.replacen(source, "entities", 1)
    }
}

fn build_candidate_entity_query(
    columns: &str,
    filter: &EntityFilter,
    where_sql: &str,
    candidate_param_indices: &[usize],
    order_by: &str,
    limit_idx: usize,
    offset_idx: usize,
) -> String {
    let source = entity_read_source(filter);
    let candidate_rows = candidate_param_indices
        .iter()
        .map(|idx| format!("(?{idx})"))
        .collect::<Vec<_>>()
        .join(", ");

    format!(
        "WITH candidates(folded_name) AS (VALUES {candidate_rows}), \
         matched_entities(entity_id) AS (\
             SELECT (\
                 SELECT id FROM {source}{where_sql} \
                 AND LOWER(name) = candidates.folded_name LIMIT 1\
             ) FROM candidates\
         ) \
         SELECT {columns} FROM entities \
         JOIN matched_entities ON entities.id = matched_entities.entity_id \
         ORDER BY {order_by} LIMIT ?{limit_idx} OFFSET ?{offset_idx}"
    )
}

fn build_entity_cursor_query(
    columns: &str,
    filter: &EntityFilter,
    where_sql: &str,
    limit_idx: usize,
) -> String {
    // CROSS JOIN fixes the loop order. An explicit ID set drives entities by
    // primary key, then looks up each sequence. Every non-ID walk drives
    // the sequence range first and checks the entity through its primary key;
    // kind/type predicates must not force a full matching-set sort.
    let source = entity_read_source(filter);
    let from_clause = if !filter.ids.is_empty() {
        format!("{source} CROSS JOIN entities_seq ON entities.id = entities_seq.entity_id")
    } else {
        "entities_seq CROSS JOIN entities INDEXED BY sqlite_autoindex_entities_1 \
         ON entities.id = entities_seq.entity_id"
            .to_string()
    };
    format!(
        "SELECT {columns}, entities_seq.seq FROM {from_clause}{where_sql} \
         ORDER BY entities_seq.seq ASC LIMIT ?{limit_idx}"
    )
}

fn is_complete_id_lookup(filter: &EntityFilter, page: &PageRequest) -> bool {
    !filter.ids.is_empty()
        && filter.property_equalities.is_empty()
        && filter.property_prefixes.is_empty()
        && filter.kinds.is_empty()
        && filter.entity_types.is_empty()
        && filter.entity_types_by_kind.is_empty()
        && filter.name_prefix.is_none()
        && filter.name_exact.is_none()
        && filter.name_or_alias_exact.is_none()
        && filter.tags_any.is_empty()
        && filter.names_ci.is_empty()
        && page.offset == 0
        && usize::try_from(page.limit).ok() == Some(filter.ids.len())
}

// =============================================================================
// EntityStore implementation
// =============================================================================

#[async_trait]
impl EntityStore for SqlEntityStore {
    async fn upsert_entity(&self, entity: Entity) -> Result<(), StorageError> {
        let statement = entity_upsert_statement(&entity);
        self.with_writer("upsert_entity", move |conn| {
            let mut stmt = conn.prepare(&statement.sql)?;
            bind_params(&mut stmt, &statement.params)?;
            stmt.raw_execute()?;
            Ok(())
        })
        .await
    }

    async fn insert_entity_if_absent(&self, entity: Entity) -> Result<bool, StorageError> {
        let statement = entity_insert_if_absent_statement(&entity);
        self.with_writer("insert_entity_if_absent", move |conn| {
            let mut stmt = conn.prepare(&statement.sql)?;
            bind_params(&mut stmt, &statement.params)?;
            Ok(stmt.raw_execute()? > 0)
        })
        .await
    }

    async fn upsert_entity_with_attachments(
        &self,
        entity: Entity,
        attachments: Vec<Attachment>,
    ) -> Result<(), StorageError> {
        let entity_id = entity.id;
        let entity_statement = entity_upsert_statement(&entity);
        let mut attachment_statements = Vec::with_capacity(attachments.len());
        for attachment in attachments {
            attachment.validate()?;
            if attachment.record_uuid != entity_id
                || attachment.substrate != AttachmentSubstrate::Entity
            {
                return Err(StorageError::InvalidInput {
                    capability: StorageCapability::Attachments,
                    operation: "upsert_entity_with_attachments".into(),
                    message: format!(
                        "attachment {} must target entity {entity_id}",
                        attachment.role
                    ),
                });
            }
            attachment_statements.push(attachment_upsert_statement(&attachment)?);
        }

        self.with_writer_tx("upsert_entity_with_attachments", move |conn| {
            let mut entity_stmt = conn.prepare(&entity_statement.sql)?;
            bind_params(&mut entity_stmt, &entity_statement.params)?;
            entity_stmt.raw_execute()?;
            drop(entity_stmt);

            for statement in attachment_statements {
                let mut stmt = conn.prepare(&statement.sql)?;
                bind_params(&mut stmt, &statement.params)?;
                stmt.raw_execute()?;
            }
            Ok(())
        })
        .await
    }

    async fn upsert_entities(
        &self,
        entities: Vec<Entity>,
    ) -> Result<BatchWriteSummary, StorageError> {
        let attempted = entities.len() as u64;

        // ADR-067 slice 1: when the write queue is enabled, route through
        // the WriterTask channel. The closure is DML-only — no BEGIN
        // IMMEDIATE/COMMIT/ROLLBACK here, since the WriterTask's run loop
        // owns the transaction and `WriteRequest::execute_and_reply` owns
        // the commit/rollback decision (a bare BEGIN IMMEDIATE inside this
        // closure would violate SQLite's nested-transaction rule).
        if let Some(writer_task) = self.current_writer_task("upsert_entities")? {
            return writer_task
                .send_bounded_at(
                    move |conn| {
                        batch_upsert_entities(conn, &entities, attempted)
                            .map_err(|e| map_err(e, "upsert_entities"))
                    },
                    "upsert_entities",
                )
                .await;
        }

        // Explicitly disabled or degraded fallback path: byte-for-byte unchanged from pre-ADR-067
        // behavior — the closure owns its own BEGIN IMMEDIATE/COMMIT/ROLLBACK
        // via the pool-mutex writer.
        let origin = self.pool.origin();
        self.with_writer("upsert_entities", move |conn| {
            conn.execute_batch("BEGIN IMMEDIATE")?;
            let _tx_handle = khive_storage::tx_registry::register_scoped(
                Some("entity_upsert_batch".to_string()),
                origin,
            );

            let summary = batch_upsert_entities(conn, &entities, attempted)?;

            if let Err(e) = conn.execute_batch("COMMIT") {
                let _ = conn.execute_batch("ROLLBACK");
                return Err(e);
            }
            Ok(summary)
        })
        .await
    }

    async fn replace_entity_if_unchanged(
        &self,
        entity: Entity,
        expected_updated_at: i64,
        expected_deleted_at: Option<i64>,
    ) -> Result<bool, StorageError> {
        let statement = entity_replace_if_unchanged_statement(
            &entity,
            expected_updated_at,
            expected_deleted_at,
        );
        self.with_writer("replace_entity_if_unchanged", move |conn| {
            let mut stmt = conn.prepare(&statement.sql)?;
            bind_params(&mut stmt, &statement.params)?;
            Ok(stmt.raw_execute()? > 0)
        })
        .await
    }

    async fn get_entity(&self, id: Uuid) -> Result<Option<Entity>, StorageError> {
        let id_str = id.to_string();

        self.with_reader("get_entity", move |conn| {
            let sql = format!(
                "SELECT {ENTITY_SELECT_COLUMNS} FROM entities \
                 WHERE entities.id = ?1 AND entities.deleted_at IS NULL"
            );
            let mut stmt = conn.prepare(&sql)?;
            let mut rows = stmt.query(rusqlite::params![id_str])?;
            match rows.next()? {
                Some(row) => Ok(Some(read_entity(row)?)),
                None => Ok(None),
            }
        })
        .await
    }

    async fn entity_sequence(&self, id: Uuid) -> Result<Option<i64>, StorageError> {
        let id = id.to_string();
        self.with_reader("entity_sequence", move |conn| {
            conn.query_row(
                "SELECT seq FROM entities_seq WHERE entity_id = ?1",
                rusqlite::params![id],
                |row| row.get(0),
            )
            .optional()
        })
        .await
    }

    async fn delete_entity(&self, id: Uuid, mode: DeleteMode) -> Result<bool, StorageError> {
        match mode {
            DeleteMode::Soft => {
                let now = chrono::Utc::now().timestamp_micros();
                let statement = entity_soft_delete_statement(id, now);
                self.with_writer("delete_entity_soft", move |conn| {
                    let mut stmt = conn.prepare(&statement.sql)?;
                    bind_params(&mut stmt, &statement.params)?;
                    Ok(stmt.raw_execute()? > 0)
                })
                .await
            }
            DeleteMode::Hard => {
                let entity_statement = entity_hard_delete_statement(id);
                let attachment_statement =
                    delete_record_attachments_statement(id, AttachmentSubstrate::Entity);
                self.with_writer_tx("delete_entity_hard", move |conn| {
                    let mut entity_stmt = conn.prepare(&entity_statement.sql)?;
                    bind_params(&mut entity_stmt, &entity_statement.params)?;
                    let deleted = entity_stmt.raw_execute()? > 0;
                    drop(entity_stmt);
                    if deleted {
                        let mut attachment_stmt = conn.prepare(&attachment_statement.sql)?;
                        bind_params(&mut attachment_stmt, &attachment_statement.params)?;
                        attachment_stmt.raw_execute()?;
                    }
                    Ok(deleted)
                })
                .await
            }
        }
    }

    async fn query_entities(
        &self,
        namespace: &str,
        filter: EntityFilter,
        page: PageRequest,
    ) -> Result<Page<Entity>, StorageError> {
        self.query_entities_page(namespace, filter, page, EntityPageMode::ExactTotal)
            .await
    }

    async fn query_entities_count_free(
        &self,
        namespace: &str,
        filter: EntityFilter,
        page: PageRequest,
    ) -> Result<Page<Entity>, StorageError> {
        self.query_entities_page(namespace, filter, page, EntityPageMode::CountFree)
            .await
    }

    async fn query_entities_after(
        &self,
        namespace: &str,
        filter: EntityFilter,
        after: Option<SeekCursor>,
        limit: u32,
    ) -> Result<SeekPage<Entity>, StorageError> {
        super::validate_json_equality_paths(
            &filter.property_equalities,
            StorageCapability::Entities,
            "query_entities_after",
        )?;
        super::validate_json_prefix_paths(
            &filter.property_prefixes,
            StorageCapability::Entities,
            "query_entities_after",
        )?;
        if limit == 0 {
            return Ok(SeekPage::default());
        }
        if !filter.names_ci.is_empty() {
            return Err(StorageError::InvalidInput {
                capability: StorageCapability::Entities,
                operation: "query_entities_after".into(),
                message: "names_ci candidate folding is not compatible with seek pagination".into(),
            });
        }

        let namespace = namespace.to_string();
        let limit_usize = limit as usize;
        let probe_limit_i64 = i64::from(limit) + 1;
        self.with_reader("query_entities_after", move |conn| {
            let (mut where_sql, mut params) = if filter.ids.is_empty() {
                build_entity_streaming_where(&namespace, &filter)
            } else {
                build_entity_where(&namespace, &filter)
            };
            if let Some(cursor) = after {
                params.push(Box::new(cursor.sequence));
                where_sql.push_str(&format!(" AND entities_seq.seq > ?{}", params.len()));
            }
            params.push(Box::new(probe_limit_i64));
            let limit_idx = params.len();

            let columns = ENTITY_SELECT_COLUMNS;
            let sql = build_entity_cursor_query(columns, &filter, &where_sql, limit_idx);
            let mut stmt = conn.prepare(&sql)?;
            let param_refs: Vec<&dyn rusqlite::types::ToSql> =
                params.iter().map(|param| param.as_ref()).collect();
            let rows = stmt.query_map(param_refs.as_slice(), |row| {
                Ok((read_entity(row)?, row.get::<_, i64>(16)?))
            })?;
            let mut entries = rows.collect::<Result<Vec<_>, _>>()?;
            let has_more = entries.len() > limit_usize;
            if has_more {
                entries.truncate(limit_usize);
            }
            let next_after = if has_more {
                entries.last().map(|(entity, sequence)| SeekCursor {
                    sequence: *sequence,
                    id: entity.id,
                })
            } else {
                None
            };
            let items = entries.into_iter().map(|(entity, _)| entity).collect();
            Ok(SeekPage { items, next_after })
        })
        .await
    }

    async fn get_entity_including_deleted(&self, id: Uuid) -> Result<Option<Entity>, StorageError> {
        let id_str = id.to_string();

        self.with_reader("get_entity_including_deleted", move |conn| {
            let sql =
                format!("SELECT {ENTITY_SELECT_COLUMNS} FROM entities WHERE entities.id = ?1");
            let mut stmt = conn.prepare(&sql)?;
            let mut rows = stmt.query(rusqlite::params![id_str])?;
            match rows.next()? {
                Some(row) => Ok(Some(read_entity(row)?)),
                None => Ok(None),
            }
        })
        .await
    }

    async fn get_entity_by_key(
        &self,
        namespace: &str,
        kind: &str,
        key: &str,
    ) -> Result<Option<Entity>, StorageError> {
        let namespace = namespace.to_string();
        let kind = kind.to_string();
        let key = key.to_string();
        self.with_reader("get_entity_by_key", move |conn| {
            let sql = format!(
                "SELECT {ENTITY_SELECT_COLUMNS} FROM entity_keys \
                 JOIN entities ON entities.id = entity_keys.entity_id \
                 WHERE entity_keys.namespace = ?1 AND entity_keys.kind = ?2 \
                   AND entity_keys.key = ?3 AND entity_keys.released_at IS NULL \
                   AND entities.deleted_at IS NULL"
            );
            let mut stmt = conn.prepare(&sql)?;
            let mut rows = stmt.query(rusqlite::params![namespace, kind, key])?;
            match rows.next()? {
                Some(row) => Ok(Some(read_entity(row)?)),
                None => Ok(None),
            }
        })
        .await
    }

    async fn taken_entity_keys(&self, id: Uuid) -> Result<Vec<EntityKeyHolder>, StorageError> {
        let id_str = id.to_string();
        self.with_reader("taken_entity_keys", move |conn| {
            let mut stmt = conn.prepare(
                "SELECT mine.kind, mine.key, held.entity_id FROM entity_keys AS mine \
                 JOIN entity_keys AS held \
                   ON held.namespace = mine.namespace AND held.kind = mine.kind \
                  AND held.key = mine.key AND held.released_at IS NULL \
                  AND held.entity_id <> mine.entity_id \
                 WHERE mine.entity_id = ?1 AND mine.released_at IS NOT NULL \
                 ORDER BY mine.kind, mine.key",
            )?;
            let rows = stmt.query_map(rusqlite::params![id_str], |row| {
                let holder: String = row.get(2)?;
                let holder_id = Uuid::parse_str(&holder).map_err(|error| {
                    rusqlite::Error::FromSqlConversionFailure(
                        2,
                        rusqlite::types::Type::Text,
                        Box::new(error),
                    )
                })?;
                Ok(EntityKeyHolder {
                    kind: row.get(0)?,
                    key: row.get(1)?,
                    holder_id,
                })
            })?;
            rows.collect()
        })
        .await
    }

    async fn count_entities_by_type(
        &self,
        namespaces: &[String],
    ) -> Result<Option<EntityTypeCounts>, StorageError> {
        let namespaces =
            serde_json::to_string(namespaces).map_err(|error| StorageError::Serialization {
                capability: StorageCapability::Entities,
                message: error.to_string(),
            })?;
        self.with_reader("count_entities_by_type", move |conn| {
            let mut statement = conn.prepare(ENTITIES_COUNT_BY_TYPE_SQL)?;
            let rows = statement.query_map(rusqlite::params![namespaces], |row| {
                let count: i64 = row.get(1)?;
                let count = u64::try_from(count).map_err(|error| {
                    rusqlite::Error::FromSqlConversionFailure(
                        1,
                        rusqlite::types::Type::Integer,
                        Box::new(error),
                    )
                })?;
                Ok((row.get::<_, Option<String>>(0)?, count))
            })?;
            rows.collect::<Result<Vec<_>, _>>().map(Some)
        })
        .await
    }

    async fn count_entities(
        &self,
        namespace: &str,
        filter: EntityFilter,
    ) -> Result<u64, StorageError> {
        super::validate_json_equality_paths(
            &filter.property_equalities,
            StorageCapability::Entities,
            "count_entities",
        )?;
        super::validate_json_prefix_paths(
            &filter.property_prefixes,
            StorageCapability::Entities,
            "count_entities",
        )?;
        let namespace = namespace.to_string();

        let index = entity_list_index(&filter);
        self.with_list_reader("count_entities", index, move |conn, force_index| {
            if filter.namespaces.is_empty() {
                let (where_sql, params) = build_entity_where(&namespace, &filter);
                let sql = entity_list_query(
                    &filter,
                    build_entity_count_query(&filter, &where_sql),
                    force_index,
                );
                let mut stmt = conn.prepare(&sql)?;
                let param_refs: Vec<&dyn rusqlite::types::ToSql> =
                    params.iter().map(|p| p.as_ref()).collect();
                let count: i64 = stmt.query_row(param_refs.as_slice(), |row| row.get(0))?;
                return Ok(count as u64);
            }

            let deduped_namespaces: Vec<String> = filter
                .namespaces
                .iter()
                .cloned()
                .collect::<HashSet<_>>()
                .into_iter()
                .collect();

            let mut total = 0;
            for chunk in deduped_namespaces.chunks(NAMESPACE_COUNT_CHUNK_SIZE) {
                let chunk_filter = EntityFilter {
                    namespaces: chunk.to_vec(),
                    ..filter.clone()
                };
                let (where_sql, params) = build_entity_where(&namespace, &chunk_filter);
                let sql = entity_list_query(
                    &chunk_filter,
                    build_entity_count_query(&chunk_filter, &where_sql),
                    force_index && index.is_some(),
                );
                let mut stmt = conn.prepare(&sql)?;
                let param_refs: Vec<&dyn rusqlite::types::ToSql> =
                    params.iter().map(|p| p.as_ref()).collect();
                let count: i64 = stmt.query_row(param_refs.as_slice(), |row| row.get(0))?;
                total += count as u64;
            }
            Ok(total)
        })
        .await
    }
}

// =============================================================================
// DDL
// =============================================================================

const ENTITIES_DDL: &str = include_str!("../../sql/entities-ddl.sql");

pub(crate) fn ensure_entities_schema(conn: &rusqlite::Connection) -> Result<(), rusqlite::Error> {
    conn.execute_batch(ENTITIES_DDL)?;
    conn.execute_batch(crate::migrations::ENTITY_KEYS_DDL)?;
    conn.execute_batch(crate::migrations::ENTITY_KEY_KIND_GUARD_DDL)?;
    conn.execute_batch(crate::migrations::ENTITY_ALIASES_DDL)
}

#[cfg(test)]
#[path = "entity_key_kind_guard_tests.rs"]
mod entity_key_kind_guard_tests;

#[cfg(test)]
#[path = "entity_tests.rs"]
mod tests;

#[cfg(test)]
#[path = "entity_type_counts_tests.rs"]
mod entity_type_counts_tests;

#[cfg(test)]
#[path = "entity_busy_tests.rs"]
mod direct_busy_tests;

#[cfg(test)]
#[path = "entity_list_plan_tests.rs"]
mod entity_list_plan_tests;

#[cfg(test)]
#[path = "entity_merge_tombstone_tests.rs"]
mod entity_merge_tombstone_tests;