khive-db 0.14.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
use super::*;

#[async_trait]
impl GraphStore for SqlGraphStore {
    async fn update_symmetric_edge_if_unchanged(
        &self,
        request: SymmetricEdgeUpdateRequest,
    ) -> StorageResult<SymmetricEdgeUpdateOutcome> {
        self.update_symmetric_edge(request).await
    }

    async fn latest_annotating_note(
        &self,
        node_id: Uuid,
        kind: &str,
        tag: &str,
    ) -> Result<Option<(Uuid, i64)>, StorageError> {
        let namespace = self.namespace.clone();
        let node_id = node_id.to_string();
        let kind = kind.to_owned();
        let tag = tag.to_owned();
        self.with_indexed_reader("latest_annotating_note", move |conn| {
            conn.query_row(
                LATEST_ANNOTATING_NOTE_SQL,
                rusqlite::params![namespace, node_id, kind, tag],
                |row| {
                    let id: String = row.get(0)?;
                    Ok((parse_uuid(&id)?, row.get(1)?))
                },
            )
            .optional()
        })
        .await
    }

    async fn latest_annotating_note_with_property(
        &self,
        node_id: Uuid,
        kind: &str,
        tag: &str,
        property_key: &str,
        property_value: &str,
    ) -> Result<Option<(Uuid, i64)>, StorageError> {
        let namespace = self.namespace.clone();
        let node_id = node_id.to_string();
        let kind = kind.to_owned();
        let tag = tag.to_owned();
        let property_key = property_key.to_owned();
        let property_value = property_value.to_owned();
        self.with_indexed_reader("latest_annotating_note_with_property", move |conn| {
            conn.query_row(
                LATEST_ANNOTATING_NOTE_WITH_PROPERTY_SQL,
                rusqlite::params![namespace, node_id, kind, tag, property_key, property_value],
                |row| {
                    let id: String = row.get(0)?;
                    Ok((parse_uuid(&id)?, row.get(1)?))
                },
            )
            .optional()
        })
        .await
    }

    async fn upsert_edge(&self, edge: Edge) -> Result<(), StorageError> {
        self.upsert_edge_observed(EdgeUpsertRequest {
            edge,
            resurrect: false,
        })
        .await
        .map(|_| ())
    }

    async fn upsert_edge_observed(
        &self,
        request: EdgeUpsertRequest,
    ) -> Result<EdgeUpsertResult, StorageError> {
        match self
            .observed_edge_write("upsert_edge_observed", request, false)
            .await?
        {
            GuardedEdgeUpsertOutcome::Written(result) => Ok(result),
            GuardedEdgeUpsertOutcome::Refused(EdgeUpsertRefusal::ResurrectionRequired { edge }) => {
                Err(resurrection_required_error("upsert_edge_observed", &edge))
            }
            GuardedEdgeUpsertOutcome::Refused(EdgeUpsertRefusal::MissingEndpoints(_)) => {
                Err(StorageError::Conflict {
                    capability: StorageCapability::Graph,
                    operation: "upsert_edge_observed".into(),
                    message: "unguarded edge upsert reported a missing-endpoint refusal".into(),
                })
            }
        }
    }

    async fn insert_edge_if_absent(&self, edge: Edge) -> Result<bool, StorageError> {
        let statement = edge_insert_if_absent_statement(&edge);
        self.with_writer("insert_edge_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 insert_commit_annotation_if_absent(
        &self,
        edge: Edge,
        guard: CommitAnnotationGuard,
    ) -> Result<CommitAnnotationInsertOutcome, StorageError> {
        const OP: &str = "insert_commit_annotation_if_absent";
        if edge.relation != EdgeRelation::Annotates || edge.deleted_at.is_some() {
            return Err(StorageError::InvalidInput {
                capability: StorageCapability::Graph,
                operation: OP.into(),
                message: "expected a live annotates edge".into(),
            });
        }
        if let Some(writer_task) = self.current_writer_task(OP)? {
            return writer_task
                .send_bounded_at(
                    move |conn| {
                        conditional_commit_annotation_insert(conn, edge, &guard)
                            .map_err(|error| map_err(error, OP))
                    },
                    OP,
                )
                .await;
        }
        let origin = self.pool.origin();
        self.with_writer(OP, move |conn| {
            conn.execute_batch("BEGIN IMMEDIATE")?;
            let _tx_handle =
                khive_storage::tx_registry::register_scoped(Some(OP.to_string()), origin);
            let outcome = match conditional_commit_annotation_insert(conn, edge, &guard) {
                Ok(outcome) => outcome,
                Err(error) => {
                    let _ = conn.execute_batch("ROLLBACK");
                    return Err(error);
                }
            };
            if let Err(error) = conn.execute_batch("COMMIT") {
                let _ = conn.execute_batch("ROLLBACK");
                return Err(error);
            }
            Ok(outcome)
        })
        .await
    }

    async fn replace_edge_if_unchanged(
        &self,
        edge: Edge,
        expected_updated_at: DateTime<Utc>,
        expected_deleted_at: Option<DateTime<Utc>>,
    ) -> Result<bool, StorageError> {
        let statement =
            edge_replace_if_unchanged_statement(&edge, expected_updated_at, expected_deleted_at);
        self.with_writer("replace_edge_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 upsert_edges(&self, edges: Vec<Edge>) -> Result<BatchWriteSummary, StorageError> {
        let attempted = edges.len() as u64;
        let requests = edges
            .into_iter()
            .map(|edge| EdgeUpsertRequest {
                edge,
                resurrect: false,
            })
            .collect();
        let outcome = self
            .observed_edge_batch_write("upsert_edges", requests, false)
            .await?;
        if let Some(refusal) = outcome.refusal {
            return match refusal.reason {
                EdgeUpsertRefusal::ResurrectionRequired { edge } => {
                    Err(resurrection_required_error("upsert_edges", &edge))
                }
                EdgeUpsertRefusal::MissingEndpoints(_) => Err(StorageError::Conflict {
                    capability: StorageCapability::Graph,
                    operation: "upsert_edges".into(),
                    message: "unguarded edge batch reported a missing-endpoint refusal".into(),
                }),
            };
        }
        Ok(BatchWriteSummary {
            attempted,
            affected: outcome.rows.len() as u64,
            ..BatchWriteSummary::default()
        })
    }

    async fn upsert_edge_guarded(&self, edge: Edge) -> Result<GuardedWriteOutcome, StorageError> {
        match self
            .upsert_edge_guarded_observed(EdgeUpsertRequest {
                edge,
                resurrect: false,
            })
            .await?
        {
            GuardedEdgeUpsertOutcome::Written(_) => Ok(GuardedWriteOutcome::Written),
            GuardedEdgeUpsertOutcome::Refused(EdgeUpsertRefusal::MissingEndpoints(missing)) => {
                Ok(GuardedWriteOutcome::Refused(missing))
            }
            GuardedEdgeUpsertOutcome::Refused(EdgeUpsertRefusal::ResurrectionRequired { edge }) => {
                Err(resurrection_required_error("upsert_edge_guarded", &edge))
            }
        }
    }

    async fn upsert_edge_guarded_observed(
        &self,
        request: EdgeUpsertRequest,
    ) -> Result<GuardedEdgeUpsertOutcome, StorageError> {
        self.observed_edge_write("upsert_edge_guarded_observed", request, true)
            .await
    }

    async fn upsert_edges_guarded(
        &self,
        edges: Vec<Edge>,
    ) -> Result<GuardedBatchOutcome, StorageError> {
        let attempted = edges.len() as u64;
        let requests = edges
            .iter()
            .cloned()
            .map(|edge| EdgeUpsertRequest {
                edge,
                resurrect: false,
            })
            .collect();
        let outcome = self.upsert_edges_guarded_observed(requests).await?;
        match outcome.refusal {
            None => Ok(GuardedBatchOutcome {
                summary: BatchWriteSummary {
                    attempted,
                    affected: outcome.rows.len() as u64,
                    ..BatchWriteSummary::default()
                },
                refused: None,
            }),
            Some(refusal) => match refusal.reason {
                EdgeUpsertRefusal::MissingEndpoints(missing) => {
                    let index = refusal.entry_index;
                    let edge = &edges[index];
                    let (source_id, target_id) =
                        canonical_edge_endpoints(edge.relation, edge.source_id, edge.target_id);
                    let message = format!(
                        "batch entry {index}: edge endpoint no longer exists at write time: source \
                         {source_id} or target {target_id}"
                    );
                    let mut summary = BatchWriteSummary {
                        attempted,
                        ..BatchWriteSummary::default()
                    };
                    // Keep the culprit's legacy first_error while recording
                    // per-input error classes and retryability in input order.
                    summary.first_error = message.clone();
                    let refusal = GuardedBatchRefusal {
                        entry_index: index,
                        missing,
                    };
                    for (failed_index, failed_edge) in edges.iter().enumerate() {
                        refusal.record_failure(&mut summary, failed_index, failed_edge, &message);
                    }
                    Ok(GuardedBatchOutcome {
                        summary,
                        refused: Some(refusal),
                    })
                }
                EdgeUpsertRefusal::ResurrectionRequired { edge } => {
                    Err(resurrection_required_error("upsert_edges_guarded", &edge))
                }
            },
        }
    }

    async fn upsert_edges_guarded_observed(
        &self,
        requests: Vec<EdgeUpsertRequest>,
    ) -> Result<GuardedEdgeBatchUpsertOutcome, StorageError> {
        self.observed_edge_batch_write("upsert_edges_guarded_observed", requests, true)
            .await
    }

    async fn get_edge(&self, id: LinkId) -> Result<Option<Edge>, StorageError> {
        let id_str = Uuid::from(id).to_string();

        self.with_reader("get_edge", move |conn| {
            let mut stmt = conn.prepare(
                "SELECT namespace, id, source_id, target_id, relation, weight, \
                        created_at, updated_at, deleted_at, metadata, target_backend \
                 FROM graph_edges WHERE id = ?1 AND deleted_at IS NULL",
            )?;
            let mut rows = stmt.query(rusqlite::params![id_str])?;
            match rows.next()? {
                Some(row) => Ok(Some(read_edge(row)?)),
                None => Ok(None),
            }
        })
        .await
    }

    async fn get_edge_including_deleted(&self, id: LinkId) -> Result<Option<Edge>, StorageError> {
        let id_str = Uuid::from(id).to_string();

        self.with_reader("get_edge_including_deleted", move |conn| {
            let mut stmt = conn.prepare(
                "SELECT namespace, id, source_id, target_id, relation, weight, \
                        created_at, updated_at, deleted_at, metadata, target_backend \
                 FROM graph_edges WHERE id = ?1",
            )?;
            let mut rows = stmt.query(rusqlite::params![id_str])?;
            match rows.next()? {
                Some(row) => Ok(Some(read_edge(row)?)),
                None => Ok(None),
            }
        })
        .await
    }

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

    async fn edge_sequences(&self, ids: &[Uuid]) -> Result<Vec<(Uuid, i64)>, StorageError> {
        if ids.is_empty() {
            return Ok(Vec::new());
        }
        let ids = ids.to_vec();
        self.with_reader("edge_sequences", move |conn| {
            const CHUNK: usize = 900;
            let mut resolved = Vec::with_capacity(ids.len());
            for chunk in ids.chunks(CHUNK) {
                let placeholders = (1..=chunk.len())
                    .map(|index| format!("?{index}"))
                    .collect::<Vec<_>>()
                    .join(", ");
                let sql = format!(
                    "SELECT edge_id, seq FROM graph_edges_seq WHERE edge_id IN ({placeholders})"
                );
                let strings = chunk.iter().map(Uuid::to_string).collect::<Vec<_>>();
                let params = strings
                    .iter()
                    .map(|id| id as &dyn rusqlite::types::ToSql)
                    .collect::<Vec<_>>();
                let mut stmt = conn.prepare(&sql)?;
                let rows = stmt.query_map(params.as_slice(), |row| {
                    let id: String = row.get(0)?;
                    Ok((parse_uuid(&id)?, row.get::<_, i64>(1)?))
                })?;
                resolved.extend(rows.collect::<Result<Vec<_>, _>>()?);
            }
            Ok(resolved)
        })
        .await
    }

    async fn get_edge_by_natural_key_including_deleted(
        &self,
        namespace: &str,
        source_id: Uuid,
        target_id: Uuid,
        relation: EdgeRelation,
    ) -> Result<Option<Edge>, StorageError> {
        let namespace = namespace.to_string();
        let source_str = source_id.to_string();
        let target_str = target_id.to_string();
        let relation_str = relation.to_string();

        self.with_reader("get_edge_by_natural_key_including_deleted", move |conn| {
            let mut stmt = conn.prepare(
                "SELECT namespace, id, source_id, target_id, relation, weight, \
                        created_at, updated_at, deleted_at, metadata, target_backend \
                 FROM graph_edges \
                 WHERE namespace = ?1 AND source_id = ?2 AND target_id = ?3 AND relation = ?4",
            )?;
            let mut rows = stmt.query(rusqlite::params![
                namespace,
                source_str,
                target_str,
                relation_str
            ])?;
            match rows.next()? {
                Some(row) => Ok(Some(read_edge(row)?)),
                None => Ok(None),
            }
        })
        .await
    }

    async fn get_edges(&self, ids: &[LinkId]) -> Result<Vec<Edge>, StorageError> {
        if ids.is_empty() {
            return Ok(Vec::new());
        }
        // SQLite SQLITE_MAX_VARIABLE_NUMBER defaults to 999; chunk at 900 to stay safe.
        const CHUNK: usize = 900;
        let id_strs: Vec<String> = ids.iter().map(|id| Uuid::from(*id).to_string()).collect();

        let mut result: Vec<Edge> = Vec::with_capacity(ids.len());
        for chunk in id_strs.chunks(CHUNK) {
            let chunk_owned: Vec<String> = chunk.to_vec();
            let edges = self
                .with_reader("get_edges", move |conn| {
                    let placeholders: Vec<String> =
                        (1..=chunk_owned.len()).map(|i| format!("?{}", i)).collect();
                    let sql = format!(
                        "SELECT namespace, id, source_id, target_id, relation, weight, \
                                created_at, updated_at, deleted_at, metadata, target_backend \
                         FROM graph_edges WHERE id IN ({}) AND deleted_at IS NULL",
                        placeholders.join(",")
                    );
                    let mut stmt = conn.prepare(&sql)?;
                    let params: Vec<&dyn rusqlite::types::ToSql> = chunk_owned
                        .iter()
                        .map(|s| s as &dyn rusqlite::types::ToSql)
                        .collect();
                    let rows = stmt.query_map(params.as_slice(), read_edge)?;
                    let mut edges = Vec::new();
                    for row in rows {
                        edges.push(row?);
                    }
                    Ok(edges)
                })
                .await?;
            result.extend(edges);
        }
        Ok(result)
    }

    async fn get_edge_read_outcomes(
        &self,
        ids: &[LinkId],
    ) -> Result<Vec<Result<Option<Edge>, StorageError>>, StorageError> {
        const CHUNK: usize = 900;
        let mut outcomes = Vec::with_capacity(ids.len());
        for chunk in ids.chunks(CHUNK) {
            let requested: Vec<String> =
                chunk.iter().map(|id| Uuid::from(*id).to_string()).collect();
            let expected = requested.len();
            let rows = self
                .with_reader("get_edge_read_outcomes", move |conn| {
                    let requested_json = serde_json::to_string(&requested)
                        .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;
                    let mut stmt = conn.prepare(
                        "SELECT e.namespace, e.id, e.source_id, e.target_id, e.relation, e.weight, \
                                e.created_at, e.updated_at, e.deleted_at, e.metadata, e.target_backend, \
                                requested.key \
                         FROM json_each(?1) AS requested \
                         LEFT JOIN graph_edges AS e \
                           ON e.id = requested.value AND e.deleted_at IS NULL \
                         ORDER BY CAST(requested.key AS INTEGER) ASC",
                    )?;
                    let mut rows = stmt.query([requested_json])?;
                    let mut outcomes = Vec::with_capacity(expected);
                    while let Some(row) = rows.next()? {
                        let ordinal: i64 = row.get(11)?;
                        let ordinal =
                            usize::try_from(ordinal).map_err(|_| rusqlite::Error::InvalidQuery)?;
                        if ordinal != outcomes.len() {
                            return Err(rusqlite::Error::InvalidQuery);
                        }
                        let outcome = match row.get_ref(1)? {
                            rusqlite::types::ValueRef::Null => Ok(None),
                            _ => read_edge(row).map(Some).map_err(|e| map_err(e, "get_edge")),
                        };
                        outcomes.push(outcome);
                    }
                    if outcomes.len() != expected {
                        return Err(rusqlite::Error::InvalidQuery);
                    }
                    Ok(outcomes)
                })
                .await?;
            outcomes.extend(rows);
        }
        Ok(outcomes)
    }

    async fn batch_neighbors(
        &self,
        sources: &[Uuid],
        query: NeighborQuery,
    ) -> Result<Vec<(Uuid, NeighborHit)>, StorageError> {
        use khive_storage::types::Direction;

        if sources.is_empty() {
            return Ok(Vec::new());
        }
        let mut seen_sources = HashSet::with_capacity(sources.len());
        let unique_sources: Vec<Uuid> = sources
            .iter()
            .copied()
            .filter(|source| seen_sources.insert(*source))
            .collect();
        const CHUNK_SIZE: usize = 880;

        let namespace = self.namespace.clone();
        let mut result: Vec<(Uuid, NeighborHit)> = Vec::new();
        // Declared across the whole chunk loop, not per chunk: a failure in a
        // later chunk must not erase what the earlier chunks already did.
        let counted_queries = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let counted_rows = Arc::new(std::sync::atomic::AtomicU64::new(0));

        for chunk in unique_sources.chunks(CHUNK_SIZE) {
            let chunk_owned: Vec<Uuid> = chunk.to_vec();
            let query_clone = query.clone();
            let ns = namespace.clone();
            let closure_queries = Arc::clone(&counted_queries);
            let closure_rows = Arc::clone(&counted_rows);

            let chunk_result = self
                .with_reader("batch_neighbors", move |conn| {
                    let src_strs: Vec<String> = chunk_owned.iter().map(|u| u.to_string()).collect();

                    let sources_json = serde_json::to_string(&src_strs).map_err(|error| {
                        rusqlite::Error::ToSqlConversionFailure(Box::new(error))
                    })?;

                    let build_inner_sql =
                        |direction_out: bool,
                         q: &NeighborQuery|
                         -> (String, Vec<String>, Option<f64>) {
                            let (filter_col, node_col) = if direction_out {
                                ("source_id", "target_id")
                            } else {
                                ("target_id", "source_id")
                            };

                            let mut rel_params: Vec<String> = Vec::new();
                            let mut conditions: Vec<String> = Vec::new();
                            let mut param_idx = 3;

                            if let Some(ref rels) = q.relations {
                                if !rels.is_empty() {
                                    let ps: Vec<String> = rels
                                        .iter()
                                        .map(|r| {
                                            rel_params.push(r.to_string());
                                            let p = format!("?{param_idx}");
                                            param_idx += 1;
                                            p
                                        })
                                        .collect();
                                    conditions
                                        .push(format!("edges.relation IN ({})", ps.join(",")));
                                }
                            }

                            // min_weight is returned separately so it can be added to
                            // all_params AFTER the rel_params block, at the right index.
                            let min_weight_val = if let Some(min_w) = q.min_weight {
                                conditions.push(format!("edges.weight >= ?{param_idx}"));
                                Some(min_w)
                            } else {
                                None
                            };

                            let where_extra = if conditions.is_empty() {
                                String::new()
                            } else {
                                format!(" AND {}", conditions.join(" AND "))
                            };

                            let sql = format!(
                                "SELECT requested.origin_id, edges.{node_col} AS node_id, \
                                 edges.id AS edge_id, edges.relation, edges.weight \
                                 FROM requested CROSS JOIN graph_edges AS edges \
                                   ON edges.{filter_col} = requested.origin_id \
                                 WHERE edges.namespace = ?1 \
                                   AND edges.deleted_at IS NULL{where_extra}",
                            );
                            (sql, rel_params, min_weight_val)
                        };

                    let mut all_params: Vec<Box<dyn rusqlite::types::ToSql>> = Vec::new();
                    all_params.push(Box::new(ns.to_string()));
                    all_params.push(Box::new(sources_json));

                    let (combined_inner, rel_params, min_weight_val) = match query_clone.direction {
                        Direction::Out => build_inner_sql(true, &query_clone),
                        Direction::In => build_inner_sql(false, &query_clone),
                        Direction::Both => {
                            let (out_sql, rel_params, min_weight_val) =
                                build_inner_sql(true, &query_clone);
                            let (in_sql, _, _) = build_inner_sql(false, &query_clone);
                            (
                                format!("{out_sql} UNION ALL {in_sql}"),
                                rel_params,
                                min_weight_val,
                            )
                        }
                    };

                    for relation in rel_params {
                        all_params.push(Box::new(relation));
                    }
                    if let Some(min_weight) = min_weight_val {
                        all_params.push(Box::new(min_weight));
                    }
                    let limit_param_idx = all_params.len() + 1;

                    // Wrap combined inner with per-source ROW_NUMBER limit if needed.
                    //
                    // Deterministic weight-descending order, tie-broken by node_id
                    // ascending, applied INSIDE the window's ORDER BY — otherwise a
                    // per-origin cap can silently drop high-weight neighbors in favor
                    // of arbitrary SQLite row order (mirrors neighbors(), ADR-089
                    // context-verb review; issue #589).
                    let full_sql = if let Some(lim) = query_clone.limit {
                        all_params.push(Box::new(lim as i64));
                        format!(
                            "WITH requested(origin_id) AS (\
                               SELECT value FROM json_each(?2)\
                             ) SELECT origin_id, node_id, edge_id, relation, weight \
                             FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY origin_id \
                                   ORDER BY weight DESC, node_id ASC) AS rn \
                                   FROM ({combined_inner})) WHERE rn <= ?{limit_param_idx}",
                        )
                    } else {
                        format!(
                            "WITH requested(origin_id) AS (\
                               SELECT value FROM json_each(?2)\
                             ) SELECT origin_id, node_id, edge_id, relation, weight \
                             FROM ({combined_inner})",
                        )
                    };

                    let param_refs: Vec<&dyn rusqlite::types::ToSql> =
                        all_params.iter().map(|p| p.as_ref()).collect();

                    let mut stmt = conn.prepare(&full_sql)?;
                    closure_queries.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                    let rows = stmt.query_map(param_refs.as_slice(), |row| {
                        let origin_str: String = row.get(0)?;
                        let nid_str: String = row.get(1)?;
                        let eid_str: String = row.get(2)?;
                        let relation_str: String = row.get(3)?;
                        let weight: f64 = row.get(4)?;
                        Ok((origin_str, nid_str, eid_str, relation_str, weight))
                    })?;

                    let mut pairs = Vec::new();
                    for row in rows {
                        let (origin_str, nid_str, eid_str, relation_str, weight) = row?;
                        closure_rows.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                        let origin = parse_uuid(&origin_str)?;
                        let node_id = parse_uuid(&nid_str)?;
                        let edge_id = parse_uuid(&eid_str)?;
                        let relation = relation_str.parse::<EdgeRelation>().map_err(|e| {
                            rusqlite::Error::FromSqlConversionFailure(
                                3,
                                rusqlite::types::Type::Text,
                                Box::new(e),
                            )
                        })?;
                        pairs.push((
                            origin,
                            NeighborHit {
                                node_id,
                                edge_id,
                                relation,
                                weight,
                                name: None,
                                kind: None,
                                entity_type: None,
                            },
                        ));
                    }
                    Ok(pairs)
                })
                .await;
            let pairs = match chunk_result {
                Ok(pairs) => pairs,
                Err(e) => {
                    report_graph_usage(&counted_queries, &counted_rows);
                    return Err(e);
                }
            };
            result.extend(pairs);
        }
        report_graph_usage(&counted_queries, &counted_rows);

        let requested: HashSet<Uuid> = unique_sources.iter().copied().collect();
        let mut grouped: HashMap<Uuid, Vec<NeighborHit>> =
            HashMap::with_capacity(unique_sources.len());
        for (origin, hit) in result {
            if !requested.contains(&origin) {
                return Err(StorageError::Internal(format!(
                    "batch_neighbors returned unrequested origin {origin}"
                )));
            }
            grouped.entry(origin).or_default().push(hit);
        }

        for hits in grouped.values_mut() {
            hits.sort_by(|a, b| {
                b.weight
                    .partial_cmp(&a.weight)
                    .unwrap_or(std::cmp::Ordering::Equal)
                    .then(a.node_id.cmp(&b.node_id))
                    .then(a.edge_id.cmp(&b.edge_id))
            });
        }

        let mut ordered = Vec::new();
        for &source in sources {
            if let Some(hits) = grouped.get(&source) {
                ordered.extend(hits.iter().cloned().map(|hit| (source, hit)));
            }
        }
        Ok(ordered)
    }

    async fn delete_edge(&self, id: LinkId, mode: DeleteMode) -> Result<bool, StorageError> {
        let id = Uuid::from(id);
        let statement = match mode {
            DeleteMode::Soft => {
                edge_soft_delete_statement(id, chrono::Utc::now().timestamp_micros())
            }
            DeleteMode::Hard => edge_hard_delete_statement(id),
        };
        self.with_writer("delete_edge", move |conn| {
            let mut stmt = conn.prepare(&statement.sql)?;
            bind_params(&mut stmt, &statement.params)?;
            Ok(stmt.raw_execute()? > 0)
        })
        .await
    }

    async fn query_edges(
        &self,
        filter: EdgeFilter,
        sort: Vec<SortOrder<EdgeSortField>>,
        page: PageRequest,
    ) -> Result<Page<Edge>, StorageError> {
        let namespace = self.namespace.clone();
        let limit_i64 = i64::from(page.limit);
        let offset_i64 = i64::try_from(page.offset).map_err(|_| StorageError::InvalidInput {
            capability: StorageCapability::Graph,
            operation: "query_edges".into(),
            message: format!(
                "PageRequest: offset must be <= i64::MAX, got {}",
                page.offset
            ),
        })?;
        self.with_reader("query_edges", move |conn| {
            let (where_clause, mut all_params) = build_edge_filter_sql(&namespace, &filter);
            let order_clause = edge_order_clause(&sort);
            all_params.push(Box::new(limit_i64));
            all_params.push(Box::new(offset_i64));

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

            let data_sql = format!(
                "SELECT namespace, id, source_id, target_id, relation, weight, \
                        created_at, updated_at, deleted_at, metadata, target_backend \
                 FROM graph_edges{}{} LIMIT ?{} OFFSET ?{}",
                where_clause, order_clause, limit_idx, offset_idx,
            );

            let mut stmt = conn.prepare(&data_sql)?;
            let param_refs: Vec<&dyn rusqlite::types::ToSql> =
                all_params.iter().map(|p| p.as_ref()).collect();
            let rows = stmt.query_map(param_refs.as_slice(), read_edge)?;

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

            Ok(Page { items, total: None })
        })
        .await
    }

    async fn count_edges(&self, filter: EdgeFilter) -> Result<u64, StorageError> {
        let namespace = self.namespace.clone();
        self.with_reader("count_edges", move |conn| {
            let (where_clause, params) = build_edge_filter_sql(&namespace, &filter);
            let sql = format!(
                "SELECT COUNT(*) FROM graph_edges{}",
                with_live_endpoints(&where_clause)
            );
            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))?;
            Ok(count as u64)
        })
        .await
    }

    async fn count_edges_in_namespaces(
        &self,
        namespaces: &[String],
        filter: EdgeFilter,
    ) -> Result<u64, StorageError> {
        let namespaces: Vec<String> = namespaces
            .iter()
            .cloned()
            .collect::<HashSet<_>>()
            .into_iter()
            .collect();
        self.with_reader("count_edges_in_namespaces", move |conn| {
            let mut total = 0;
            for chunk in namespaces.chunks(NAMESPACE_COUNT_CHUNK_SIZE) {
                let (where_clause, params) = build_edge_filter_sql_for_namespaces(chunk, &filter);
                let sql = format!(
                    "SELECT COUNT(*) FROM graph_edges{}",
                    with_live_endpoints(&where_clause)
                );
                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
    }

    async fn query_edges_in_namespaces(
        &self,
        namespaces: &[String],
        filter: EdgeFilter,
        sort: Vec<SortOrder<EdgeSortField>>,
        page: PageRequest,
    ) -> Result<Page<Edge>, StorageError> {
        // One statement with `namespace IN (...)` and real SQL paging: a
        // per-namespace prefix fetch merged and re-sliced client-side floats
        // the offset window between calls, silently duplicating and skipping
        // rows during enumeration (#2088).
        //
        // The namespace set is bound as a single JSON-array parameter (see
        // `build_edge_filter_sql_for_namespaces_json`), not one `?N` per
        // namespace: a caller visible in hundreds-to-thousands of namespaces
        // would otherwise blow past `SQLITE_LIMIT_VARIABLE_NUMBER` before any
        // filter parameter is even added, and chunking the namespace set (as
        // the count-only aggregate methods below do) is not an option here —
        // it would reintroduce exactly the floating-offset bug this method
        // exists to close, since a per-chunk LIMIT/OFFSET cannot be
        // re-sliced into one globally exact page.
        let namespaces: Vec<String> = {
            let mut seen = HashSet::new();
            namespaces
                .iter()
                .filter(|ns| seen.insert((*ns).clone()))
                .cloned()
                .collect()
        };
        let limit_i64 = i64::from(page.limit);
        let offset_i64 = i64::try_from(page.offset).map_err(|_| StorageError::InvalidInput {
            capability: StorageCapability::Graph,
            operation: "query_edges_in_namespaces".into(),
            message: format!(
                "PageRequest: offset must be <= i64::MAX, got {}",
                page.offset
            ),
        })?;
        self.with_reader("query_edges_in_namespaces", move |conn| {
            let namespaces_json = serde_json::to_string(&namespaces)
                .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;

            let (where_clause, mut all_params) =
                build_edge_filter_sql_for_namespaces_json(&namespaces_json, &filter);
            let order_clause = edge_order_clause(&sort);
            all_params.push(Box::new(limit_i64));
            all_params.push(Box::new(offset_i64));

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

            let data_sql = format!(
                "SELECT namespace, id, source_id, target_id, relation, weight, \
                        created_at, updated_at, deleted_at, metadata, target_backend \
                 FROM graph_edges{}{} LIMIT ?{} OFFSET ?{}",
                where_clause, order_clause, limit_idx, offset_idx,
            );

            let mut stmt = conn.prepare(&data_sql)?;
            let param_refs: Vec<&dyn rusqlite::types::ToSql> =
                all_params.iter().map(|p| p.as_ref()).collect();
            let rows = stmt.query_map(param_refs.as_slice(), read_edge)?;

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

            Ok(Page { items, total: None })
        })
        .await
    }

    async fn count_edges_by_relation(&self) -> Result<Vec<(EdgeRelation, u64)>, StorageError> {
        let namespace = self.namespace.clone();
        self.with_reader("count_edges_by_relation", move |conn| {
            let sql = format!(
                "SELECT relation, COUNT(*) FROM graph_edges \
                 WHERE namespace = ?1 AND deleted_at IS NULL AND {LIVE_ENDPOINTS_CONDITION} \
                 GROUP BY relation"
            );
            let mut stmt = conn.prepare(&sql)?;
            let rows = stmt.query_map([&namespace], |row| {
                let relation_str: String = row.get(0)?;
                let count: i64 = row.get(1)?;
                Ok((relation_str, count))
            })?;
            let mut out = Vec::new();
            for row in rows {
                let (relation_str, count) = row?;
                let relation = relation_str.parse::<EdgeRelation>().map_err(|e| {
                    rusqlite::Error::FromSqlConversionFailure(
                        0,
                        rusqlite::types::Type::Text,
                        Box::new(e),
                    )
                })?;
                out.push((relation, count as u64));
            }
            Ok(out)
        })
        .await
    }

    async fn count_edges_by_relation_in_namespaces(
        &self,
        namespaces: &[String],
    ) -> Result<Vec<(EdgeRelation, u64)>, StorageError> {
        let namespaces: Vec<String> = namespaces
            .iter()
            .cloned()
            .collect::<HashSet<_>>()
            .into_iter()
            .collect();
        self.with_reader("count_edges_by_relation_in_namespaces", move |conn| {
            let mut totals = HashMap::new();
            for chunk in namespaces.chunks(NAMESPACE_COUNT_CHUNK_SIZE) {
                let (where_clause, params) =
                    build_edge_filter_sql_for_namespaces(chunk, &EdgeFilter::default());
                let sql = format!(
                    "SELECT relation, COUNT(*) FROM graph_edges{} GROUP BY relation",
                    with_live_endpoints(&where_clause)
                );
                let mut stmt = conn.prepare(&sql)?;
                let param_refs: Vec<&dyn rusqlite::types::ToSql> =
                    params.iter().map(|p| p.as_ref()).collect();
                let rows = stmt.query_map(param_refs.as_slice(), |row| {
                    let relation_str: String = row.get(0)?;
                    let count: i64 = row.get(1)?;
                    Ok((relation_str, count))
                })?;
                for row in rows {
                    let (relation_str, count) = row?;
                    let relation = relation_str.parse::<EdgeRelation>().map_err(|e| {
                        rusqlite::Error::FromSqlConversionFailure(
                            0,
                            rusqlite::types::Type::Text,
                            Box::new(e),
                        )
                    })?;
                    *totals.entry(relation).or_insert(0) += count as u64;
                }
            }
            Ok(totals.into_iter().collect())
        })
        .await
    }

    async fn count_edges_by_endpoint_base(&self) -> Result<EdgeEndpointBaseCounts, StorageError> {
        let namespace = self.namespace.clone();
        self.with_reader("count_edges_by_endpoint_base", move |conn| {
            let source_case = endpoint_base_case("source_id");
            let target_case = endpoint_base_case("target_id");
            let sql = format!(
                "SELECT {source_case} AS source_base, {target_case} AS target_base, COUNT(*) \
                 FROM graph_edges \
                 WHERE namespace = ?1 AND deleted_at IS NULL AND {LIVE_ENDPOINTS_CONDITION} \
                 GROUP BY source_base, target_base"
            );
            let mut stmt = conn.prepare(&sql)?;
            let rows = stmt.query_map([&namespace], |row| {
                let source: String = row.get(0)?;
                let target: String = row.get(1)?;
                let count: i64 = row.get(2)?;
                Ok((source, target, count))
            })?;
            let mut counts = EdgeEndpointBaseCounts::default();
            for row in rows {
                let (source, target, count) = row?;
                fold_endpoint_base_row(&mut counts, &source, &target, count as u64);
            }
            Ok(counts)
        })
        .await
    }

    async fn count_edges_by_endpoint_base_in_namespaces(
        &self,
        namespaces: &[String],
    ) -> Result<EdgeEndpointBaseCounts, StorageError> {
        let namespaces: Vec<String> = namespaces
            .iter()
            .cloned()
            .collect::<HashSet<_>>()
            .into_iter()
            .collect();
        self.with_reader("count_edges_by_endpoint_base_in_namespaces", move |conn| {
            let source_case = endpoint_base_case("source_id");
            let target_case = endpoint_base_case("target_id");
            let mut counts = EdgeEndpointBaseCounts::default();
            for chunk in namespaces.chunks(NAMESPACE_COUNT_CHUNK_SIZE) {
                let (where_clause, params) =
                    build_edge_filter_sql_for_namespaces(chunk, &EdgeFilter::default());
                let sql = format!(
                    "SELECT {source_case} AS source_base, {target_case} AS target_base, COUNT(*) \
                     FROM graph_edges{} GROUP BY source_base, target_base",
                    with_live_endpoints(&where_clause)
                );
                let mut stmt = conn.prepare(&sql)?;
                let param_refs: Vec<&dyn rusqlite::types::ToSql> =
                    params.iter().map(|p| p.as_ref()).collect();
                let rows = stmt.query_map(param_refs.as_slice(), |row| {
                    let source: String = row.get(0)?;
                    let target: String = row.get(1)?;
                    let count: i64 = row.get(2)?;
                    Ok((source, target, count))
                })?;
                for row in rows {
                    let (source, target, count) = row?;
                    fold_endpoint_base_row(&mut counts, &source, &target, count as u64);
                }
            }
            Ok(counts)
        })
        .await
    }

    async fn count_edges_by_relation_and_endpoint_base_in_namespaces(
        &self,
        namespaces: &[String],
    ) -> Result<Vec<(EdgeRelation, EdgeEndpointBaseCounts)>, StorageError> {
        let namespaces: Vec<String> = namespaces
            .iter()
            .cloned()
            .collect::<HashSet<_>>()
            .into_iter()
            .collect();
        self.with_reader(
            "count_edges_by_relation_and_endpoint_base_in_namespaces",
            move |conn| {
                let mut totals: HashMap<EdgeRelation, EdgeEndpointBaseCounts> = HashMap::new();
                for chunk in namespaces.chunks(NAMESPACE_COUNT_CHUNK_SIZE) {
                    let (where_clause, params) =
                        build_edge_filter_sql_for_namespaces(chunk, &EdgeFilter::default());
                    // One lookup per endpoint per table answers both questions the
                    // single-purpose counts ask with separate correlated subqueries:
                    // liveness as in [`LIVE_ENDPOINTS_CONDITION`] (an endpoint is
                    // excluded only when present and tombstoned) and the base as in
                    // [`endpoint_base_case`] (entity first, then note, else none). `id`
                    // is the primary key of both tables, so each LEFT JOIN matches at
                    // most one row and never multiplies an edge. The edge filter runs
                    // in the inner select, where its unqualified columns resolve
                    // against graph_edges alone.
                    let sql = format!(
                        "SELECT e.relation, \
                         CASE WHEN se.id IS NOT NULL THEN 'entity' \
                         WHEN sn.id IS NOT NULL THEN 'note' ELSE 'none' END AS source_base, \
                         CASE WHEN te.id IS NOT NULL THEN 'entity' \
                         WHEN tn.id IS NOT NULL THEN 'note' ELSE 'none' END AS target_base, \
                         COUNT(*) \
                         FROM (SELECT relation, source_id, target_id \
                         FROM graph_edges{where_clause}) e \
                         LEFT JOIN entities se ON se.id = e.source_id \
                         LEFT JOIN notes sn ON sn.id = e.source_id \
                         LEFT JOIN entities te ON te.id = e.target_id \
                         LEFT JOIN notes tn ON tn.id = e.target_id \
                         WHERE se.deleted_at IS NULL AND sn.deleted_at IS NULL \
                         AND te.deleted_at IS NULL AND tn.deleted_at IS NULL \
                         GROUP BY e.relation, source_base, target_base"
                    );
                    let mut stmt = conn.prepare(&sql)?;
                    let param_refs: Vec<&dyn rusqlite::types::ToSql> =
                        params.iter().map(|p| p.as_ref()).collect();
                    let rows = stmt.query_map(param_refs.as_slice(), |row| {
                        let relation: String = row.get(0)?;
                        let source: String = row.get(1)?;
                        let target: String = row.get(2)?;
                        let count: i64 = row.get(3)?;
                        Ok((relation, source, target, count))
                    })?;
                    for row in rows {
                        let (relation_str, source, target, count) = row?;
                        let relation = relation_str.parse::<EdgeRelation>().map_err(|e| {
                            rusqlite::Error::FromSqlConversionFailure(
                                0,
                                rusqlite::types::Type::Text,
                                Box::new(e),
                            )
                        })?;
                        fold_endpoint_base_row(
                            totals.entry(relation).or_default(),
                            &source,
                            &target,
                            count as u64,
                        );
                    }
                }
                Ok(totals.into_iter().collect())
            },
        )
        .await
    }

    async fn query_edges_after(
        &self,
        filter: EdgeFilter,
        after: Option<Uuid>,
        limit: u32,
    ) -> Result<EdgeSeekPage, StorageError> {
        let namespace = self.namespace.clone();
        let limit_usize = limit as usize;
        let probe_limit_i64 = i64::from(limit) + 1;
        self.with_reader("query_edges_after", move |conn| {
            let (mut where_clause, mut params) = build_edge_filter_sql(&namespace, &filter);
            if let Some(cursor) = after {
                params.push(Box::new(cursor.to_string()));
                where_clause.push_str(&format!(" AND id > ?{}", params.len()));
            }
            params.push(Box::new(probe_limit_i64));
            let limit_idx = params.len();

            // `where_clause` always pins `namespace = ?1`; adding `id > ?N` here
            // keeps the predicate a range scan against the implicit unique index
            // backing `PRIMARY KEY (namespace, id)` — equality on the leading
            // column plus a range on the trailing one, with `ORDER BY id ASC`
            // matching the index order, so SQLite seeks instead of scanning.
            let data_sql = format!(
                "SELECT namespace, id, source_id, target_id, relation, weight, \
                        created_at, updated_at, deleted_at, metadata, target_backend \
                 FROM graph_edges{} ORDER BY id ASC LIMIT ?{}",
                where_clause, limit_idx,
            );

            let mut stmt = conn.prepare(&data_sql)?;
            let param_refs: Vec<&dyn rusqlite::types::ToSql> =
                params.iter().map(|p| p.as_ref()).collect();
            let rows = stmt.query_map(param_refs.as_slice(), read_edge)?;

            let mut items = Vec::new();
            for row in rows {
                items.push(row?);
            }
            let has_more = items.len() > limit_usize;
            if has_more {
                items.truncate(limit_usize);
            }
            let next_after = if has_more {
                items.last().map(|e| Uuid::from(e.id))
            } else {
                None
            };

            Ok(EdgeSeekPage { items, next_after })
        })
        .await
    }

    async fn query_edges_sequence_after(
        &self,
        filter: EdgeFilter,
        after: Option<SeekCursor>,
        limit: u32,
    ) -> Result<SeekPage<Edge>, StorageError> {
        if limit == 0 {
            return Ok(SeekPage::default());
        }
        let namespace = self.namespace.clone();
        let limit_usize = limit as usize;
        let probe_limit_i64 = i64::from(limit) + 1;
        self.with_reader("query_edges_sequence_after", move |conn| {
            let (mut where_clause, mut params) = build_edge_filter_sql(&namespace, &filter);
            if let Some(cursor) = after {
                params.push(Box::new(cursor.sequence));
                where_clause.push_str(&format!(" AND graph_edges_seq.seq > ?{}", params.len()));
            }
            params.push(Box::new(probe_limit_i64));
            let limit_idx = params.len();
            // CROSS JOIN fixes the ledger as the outer loop, preserving an
            // indexed `seq > boundary` scan with no full-match sort.
            let sql = format!(
                "SELECT namespace, id, source_id, target_id, relation, weight, \
                        created_at, updated_at, deleted_at, metadata, target_backend, \
                        graph_edges_seq.seq \
                 FROM graph_edges_seq CROSS JOIN graph_edges \
                    ON graph_edges.id = graph_edges_seq.edge_id{where_clause} \
                 ORDER BY graph_edges_seq.seq ASC LIMIT ?{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_edge(row)?, row.get::<_, i64>(11)?))
            })?;
            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(|(edge, sequence)| SeekCursor {
                    sequence: *sequence,
                    id: Uuid::from(edge.id),
                })
            } else {
                None
            };
            let items = entries.into_iter().map(|(edge, _)| edge).collect();
            Ok(SeekPage { items, next_after })
        })
        .await
    }

    async fn neighbors(
        &self,
        node_id: Uuid,
        query: NeighborQuery,
    ) -> Result<Vec<NeighborHit>, StorageError> {
        self.query_neighbors_page("neighbors", node_id, query, None, None)
            .await
    }

    async fn neighbors_page(
        &self,
        node_id: Uuid,
        query: NeighborQuery,
        after: Option<NeighborCursor>,
        neighbor_kinds: Option<Vec<String>>,
    ) -> Result<Vec<NeighborHit>, StorageError> {
        self.query_neighbors_page("neighbors_page", node_id, query, after, neighbor_kinds)
            .await
    }

    /// Single-query both-direction neighbor fetch (ADR-089 context-verb
    /// optimization): projects a `'out'`/`'in'` literal from each `UNION ALL`
    /// arm so the caller gets direction labels without a second direction-
    /// scoped round trip. `query.direction` is ignored — always both.
    async fn neighbors_both_directions(
        &self,
        node_id: Uuid,
        query: NeighborQuery,
    ) -> Result<Vec<DirectedNeighborHit>, StorageError> {
        count_neighbor_select();

        let namespace = self.namespace.clone();
        let node_str = node_id.to_string();

        let counted_queries = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let counted_rows = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let closure_queries = Arc::clone(&counted_queries);
        let closure_rows = Arc::clone(&counted_rows);
        let result = self
            .with_reader("neighbors_both_directions", move |conn| {
                let base_out = "SELECT target_id AS node_id, id AS edge_id, relation, weight, \
                            'out' AS dir \
                            FROM graph_edges \
                            WHERE namespace = ?1 AND source_id = ?2 AND deleted_at IS NULL";
                let base_in = "SELECT source_id AS node_id, id AS edge_id, relation, weight, \
                           'in' AS dir \
                           FROM graph_edges \
                           WHERE namespace = ?1 AND target_id = ?2 AND deleted_at IS NULL";
                let sql = format!("{} UNION ALL {}", base_out, base_in);

                let (where_extra, limit_clause, extra_params) =
                    neighbor_extra_clause(&query, 3, None, None);

                // Same global weight-descending/node_id-ascending order as `neighbors`
                // (ADR-089 context-verb review),
                // applied across BOTH directions before `LIMIT` truncates. A
                // reciprocal pair (an Out edge and an In edge to/from the same
                // neighbor at the same weight) ties on `(weight, node_id)`, so the
                // order is extended with a direction rank (`out` before `in`) and
                // finally `edge_id` to make the pre-`LIMIT` order fully
                // deterministic).
                let full_sql = format!(
                    "SELECT node_id, edge_id, relation, weight, dir FROM ({}){} \
                 ORDER BY weight DESC, node_id ASC, \
                 CASE dir WHEN 'out' THEN 0 ELSE 1 END ASC, edge_id ASC{}",
                    sql, where_extra, limit_clause
                );

                let mut stmt = conn.prepare(&full_sql)?;

                let mut all_params: Vec<Box<dyn rusqlite::types::ToSql>> = Vec::new();
                all_params.push(Box::new(namespace.clone()));
                all_params.push(Box::new(node_str.clone()));
                all_params.extend(extra_params);

                let param_refs: Vec<&dyn rusqlite::types::ToSql> =
                    all_params.iter().map(|p| p.as_ref()).collect();

                closure_queries.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                let rows = stmt.query_map(param_refs.as_slice(), |row| {
                    let nid_str: String = row.get(0)?;
                    let eid_str: String = row.get(1)?;
                    let relation_str: String = row.get(2)?;
                    let weight: f64 = row.get(3)?;
                    let dir_str: String = row.get(4)?;
                    Ok((nid_str, eid_str, relation_str, weight, dir_str))
                })?;

                let mut hits = Vec::new();
                for row in rows {
                    let (nid_str, eid_str, relation_str, weight, dir_str) = row?;
                    closure_rows.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                    let relation = relation_str.parse::<EdgeRelation>().map_err(|e| {
                        rusqlite::Error::FromSqlConversionFailure(
                            2,
                            rusqlite::types::Type::Text,
                            Box::new(e),
                        )
                    })?;
                    let direction = if dir_str == "out" {
                        Direction::Out
                    } else {
                        Direction::In
                    };
                    hits.push(DirectedNeighborHit {
                        hit: NeighborHit {
                            node_id: parse_uuid(&nid_str)?,
                            edge_id: parse_uuid(&eid_str)?,
                            relation,
                            weight,
                            name: None,
                            kind: None,
                            entity_type: None,
                        },
                        direction,
                    });
                }

                Ok(hits)
            })
            .await;

        report_graph_usage(&counted_queries, &counted_rows);
        result
    }

    async fn traverse(&self, request: TraversalRequest) -> Result<Vec<GraphPath>, StorageError> {
        request
            .validate()
            .map_err(|message| StorageError::InvalidInput {
                capability: StorageCapability::Graph,
                operation: "traverse".into(),
                message,
            })?;
        if request.roots.is_empty() {
            return Ok(Vec::new());
        }

        let budget = request.execution_budget;
        let outer_context = khive_storage::capture_request_read_context();
        let execution_deadline =
            khive_storage::RequestReadDeadline::after(budget.remaining_duration());
        khive_storage::scope_request_read_deadline_at(execution_deadline, async {
            if outer_context.stop_reason().is_some() {
                return Err(StorageError::Timeout {
                    operation: "traverse".into(),
                });
            }
            if budget.is_expired() {
                return Err(traversal_timeout_error(&budget));
            }
            let mut distinct_roots = HashSet::with_capacity(request.roots.len());
            let roots = request
                .roots
                .iter()
                .copied()
                .filter(|root| distinct_roots.insert(*root))
                .collect::<Vec<_>>();
            let opts = request.options;
            if self
                .index_repair
                .as_ref()
                .is_some_and(super::index_repair::IndexRepairContext::is_writable)
            {
                // Prepare and step the actual indexed adjacency statements with
                // LIMIT 0 before BFS takes its long-lived reader. This checks the
                // schema cookie without consuming walk rows or query counters.
                // A schema change during the walk remains its original typed
                // failure; we never restart BFS or renew its budget.
                let directions = match opts.direction {
                    Direction::Out => vec![Direction::Out],
                    Direction::In => vec![Direction::In],
                    Direction::Both => vec![Direction::Out, Direction::In],
                };
                let relation_count = opts.relations.as_ref().map_or(0, Vec::len);
                let statements = directions
                    .into_iter()
                    .map(|direction| {
                        traversal_neighbor_sql(direction, relation_count, opts.min_weight.is_some())
                    })
                    .collect::<Vec<_>>();
                // Dropping preflight stops pending repair admission. Already admitted
                // constructor DDL keeps its completion ownership outside this await.
                let preflight = self.with_indexed_reader("traverse", move |conn| {
                    for sql in &statements {
                        let mut statement = conn.prepare(sql)?;
                        statement.raw_bind_parameter(3, 0_i64)?;
                        let _ = statement.raw_query().next()?;
                    }
                    Ok(())
                });
                let preflight_result = tokio::select! {
                    biased;
                    _ = outer_context.clone().wait_for_stop() => Err(StorageError::Timeout {
                        operation: "traverse".into(),
                    }),
                    result = tokio::time::timeout_at(execution_deadline.async_at(), preflight) => {
                        match result {
                            Ok(result) => result,
                            Err(_) => Err(traversal_timeout_error(&budget)),
                        }
                    },
                };
                preflight_result.map_err(|error| match error {
                    StorageError::Timeout { .. }
                        if budget.is_expired() && outer_context.stop_reason().is_none() =>
                    {
                        traversal_timeout_error(&budget)
                    }
                    error => error,
                })?;
                if budget.is_expired() {
                    return Err(traversal_timeout_error(&budget));
                }
            }
            let include_roots = request.include_roots;
            let namespace = self.namespace.clone();
            let origin = self.pool.origin();
            let closure_budget = budget.clone();
            // Shared with the blocking closure so the counts survive an error.
            // `with_reader` runs the closure on a blocking thread where the
            // task-local usage context is invisible, so it cannot call
            // `usage::count` itself; returning the totals in the Ok value would
            // lose every round trip already issued when a later statement fails.
            let counted_rows = Arc::new(std::sync::atomic::AtomicU64::new(0));
            let counted_queries = Arc::new(std::sync::atomic::AtomicU64::new(0));
            let closure_rows = Arc::clone(&counted_rows);
            let closure_queries = Arc::clone(&counted_queries);
            let result = self
                .with_reader("traverse", move |conn| {
                    Ok(run_bounded_traversal(
                        conn,
                        roots,
                        opts,
                        include_roots,
                        namespace,
                        origin,
                        closure_budget,
                        closure_rows.as_ref(),
                        closure_queries.as_ref(),
                    ))
                })
                .await
                .and_then(|inner| inner)
                .map_err(|error| match error {
                    StorageError::Timeout { .. }
                        if budget.is_expired() && outer_context.stop_reason().is_none() =>
                    {
                        traversal_timeout_error(&budget)
                    }
                    error => error,
                });

            // Accounted on BOTH outcomes. `db_round_trips` counts round trips
            // *issued* and `graph_hops` counts adjacency rows storage *returned*,
            // so work already done before a later statement errors is real work and
            // must appear. Reading the shared counters here rather than off the
            // Ok value is what makes that possible: the closure runs on a blocking
            // thread where the task-local usage context is not visible, so it
            // cannot count for itself, and a value returned only on success
            // reports nothing at all when the traversal fails partway.
            khive_storage::usage::count(
                khive_storage::usage::UsageUnit::DbRoundTrips,
                counted_queries.load(std::sync::atomic::Ordering::Relaxed),
            );
            khive_storage::usage::count(
                khive_storage::usage::UsageUnit::GraphHops,
                counted_rows.load(std::sync::atomic::Ordering::Relaxed),
            );

            result
        })
        .await
    }

    async fn purge_incident_edges(&self, node_id: Uuid) -> Result<u64, StorageError> {
        // No namespace filter: UUID v4 is globally unique. Hard-delete cascade must
        // remove ALL incident edges regardless of which namespace they were written in
        // (ADR-002 no-dangling-references, ADR-007 by-ID contract).
        let statement = purge_incident_edges_statement(node_id);
        self.with_writer("purge_incident_edges", move |conn| {
            let mut stmt = conn.prepare(&statement.sql)?;
            bind_params(&mut stmt, &statement.params)?;
            Ok(stmt.raw_execute()? as u64)
        })
        .await
    }
}