kkernel 0.9.0

khive kernel — stdio MCP server binary and admin CLI (sync, pack introspection, db ops)
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
//! SubstrateCoordinator — cross-backend dispatch (D2-D4).

use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use sha2::{Digest, Sha256};
use tokio::task::JoinError;
use uuid::Uuid;

use khive_pack_kg::handlers::{SearchSubstrate, ValidatedSearchRequest};
use khive_runtime::{
    BackendId, EdgeEndpointKind, KhiveRuntime, NoteSearchHit, Resolved, RuntimeError, SearchHit,
    SearchSource,
};
use khive_score::{rrf_score, DeterministicScore};
use khive_storage::EdgeRelation;
use khive_types::{namespace::Namespace, SubstrateKind};

use super::locator::LocatorCache;
use super::registry::BackendRegistry;

/// Keep arbitrary configured backend identifiers safe and bounded before
/// they reach persistent coordinator diagnostics.  The raw identifier stays
/// on [`BackendSearchResult`] for internal routing; the MCP boundary applies
/// the same canonical secret masker before exposing it on the wire.
fn bounded_backend_id_for_log(backend_id: &str) -> String {
    const MAX_OUTPUT_CHARS: usize = 256;

    let backend_id_chars = backend_id.chars().count();
    // Bound the masker's own input window (see `secret_gate::mask_bounded`)
    // rather than masking the full, unbounded id. The window doubles as the
    // output cap here — this function applies its own further prefix +
    // fingerprint bounding below.
    let result = khive_runtime::secret_gate::mask_bounded(
        khive_runtime::secret_gate::RedactionSurface::McpDiagnostic,
        backend_id,
        khive_runtime::secret_gate::MASK_WINDOW_CHARS,
        khive_runtime::secret_gate::MASK_WINDOW_CHARS,
    );
    let was_masked = result.redacted || result.truncated || result.text.trim().is_empty();
    let sanitized = if result.text.trim().is_empty() {
        "masked-backend"
    } else {
        result.text.as_str()
    };
    if !was_masked && backend_id_chars <= MAX_OUTPUT_CHARS {
        return sanitized.to_string();
    }

    // Fingerprint the original value so independently configured secrets or
    // long identifiers do not collapse onto one diagnostic key after
    // masking/truncation.  The digest reveals no credential material.
    let fingerprint = format!("{:x}", Sha256::digest(backend_id.as_bytes()));
    let suffix = format!("…#{fingerprint}");
    let prefix_chars = MAX_OUTPUT_CHARS - suffix.chars().count();
    let prefix: String = sanitized.chars().take(prefix_chars).collect();
    format!("{prefix}{suffix}")
}

/// Bound and mask a backend failure cause before it reaches a warning.  This
/// mirrors the MCP wire boundary so the earlier coordinator diagnostic cannot
/// leak a credential that the response would later redact.
pub(super) fn bounded_backend_cause_for_log(message: &str) -> String {
    const MAX_OUTPUT_CHARS: usize = 1_024;
    const MISSING_CAUSE: &str = "backend search failed without diagnostic detail";

    // Bound the masker's own input window (see `secret_gate::mask_bounded`)
    // rather than masking the full, unbounded message: cost stays
    // proportional to the shared window regardless of message length, and a
    // token straddling the window is dropped whole rather than echoed
    // unmasked.
    let result = khive_runtime::secret_gate::mask_bounded(
        khive_runtime::secret_gate::RedactionSurface::McpDiagnostic,
        message,
        khive_runtime::secret_gate::MASK_WINDOW_CHARS,
        MAX_OUTPUT_CHARS,
    );
    if result.text.trim().is_empty() {
        return MISSING_CAUSE.to_string();
    }
    result.text
}

/// Stable classification for a failed fan-out backend leg.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BackendSearchFailureKind {
    BackendError,
    Timeout,
}

/// Typed failure for one fan-out backend leg.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BackendSearchFailure {
    pub kind: BackendSearchFailureKind,
    pub message: String,
}

impl BackendSearchFailure {
    fn timeout(timeout_ms: u64) -> Self {
        Self {
            kind: BackendSearchFailureKind::Timeout,
            message: format!("backend search timed out after {timeout_ms}ms"),
        }
    }

    pub(super) fn from_runtime_error(error: RuntimeError) -> Self {
        let kind = if matches!(
            &error,
            RuntimeError::Storage(khive_storage::StorageError::Timeout { .. })
                | RuntimeError::DeadlineExceeded { .. }
        ) {
            BackendSearchFailureKind::Timeout
        } else {
            BackendSearchFailureKind::BackendError
        };
        Self {
            kind,
            message: error.to_string(),
        }
    }
}

/// Result of a single backend's entity-search contribution to a fan-out.
///
/// `hits` may be empty when the backend returned no results.
/// `error` carries the backend-specific typed failure for a whole-backend
/// failure (text arm, or a fatal error before either arm ran); a backend that
/// reported one is treated as having contributed no hits at all.
/// `vector_error` instead carries a vector-arm-only failure: the text arm
/// still ran and `hits` still carries its results, so this backend is NOT
/// `error`-failed.
#[derive(Debug)]
pub struct BackendSearchResult {
    pub backend_id: BackendId,
    pub hits: Vec<SearchHit>,
    pub note_hits: Vec<NoteSearchHit>,
    pub error: Option<BackendSearchFailure>,
    pub vector_error: Option<String>,
}

/// A located edge endpoint: which backend owns it, and its substrate kind.
///
/// `kind` lets cross-backend `annotates` validation accept edge-substrate
/// targets (ADR-002 rule 1) without a second DB round-trip once located.
#[derive(Clone, Debug)]
struct LocatedEndpoint {
    backend_id: BackendId,
    kind: EdgeEndpointKind,
}

/// Cross-backend dispatch layer.
///
/// Owns node-to-backend location (D2), cross-backend link stamping (D3),
/// fan-out entity/note search with RRF (D4), traversal (D5, future),
/// and partition tolerance (D6, future).
pub struct SubstrateCoordinator {
    registry: BackendRegistry,
    locator: Arc<LocatorCache>,
    #[cfg(test)]
    pub(super) fail_backend_id: Option<String>,
    #[cfg(test)]
    pub(super) panic_backend_id: Option<String>,
    /// Test-only: named backend's fan-out search task never resolves,
    /// simulating a hung backend (MAJ-2 timeout regression coverage).
    #[cfg(test)]
    pub(super) hang_backend_ids: Vec<String>,
    /// Test-only: delay a backend result past the shared absolute deadline.
    #[cfg(test)]
    pub(super) delay_backend: Option<(String, Duration)>,
    /// Test-only: when set, a backend's entity fan-out task returns this
    /// list verbatim instead of calling `hybrid_search`, so RRF-merge
    /// regression tests can pin exact ranks/UUIDs (MAJ-4).
    #[cfg(test)]
    pub(super) entity_hits_override: Option<HashMap<String, Vec<SearchHit>>>,
    /// Test-only: same as `entity_hits_override`, for the note substrate.
    #[cfg(test)]
    pub(super) note_hits_override: Option<HashMap<String, Vec<NoteSearchHit>>>,
}

impl SubstrateCoordinator {
    /// Construct from a [`BackendRegistry`].
    pub fn new(registry: BackendRegistry) -> Self {
        Self {
            registry,
            locator: Arc::new(LocatorCache::new()),
            #[cfg(test)]
            fail_backend_id: None,
            #[cfg(test)]
            panic_backend_id: None,
            #[cfg(test)]
            hang_backend_ids: Vec::new(),
            #[cfg(test)]
            delay_backend: None,
            #[cfg(test)]
            entity_hits_override: None,
            #[cfg(test)]
            note_hits_override: None,
        }
    }

    /// Construct from a [`BackendRegistry`] with a custom locator TTL.
    pub fn with_locator_ttl(registry: BackendRegistry, ttl: Duration) -> Self {
        Self {
            registry,
            locator: Arc::new(LocatorCache::with_ttl(ttl)),
            #[cfg(test)]
            fail_backend_id: None,
            #[cfg(test)]
            panic_backend_id: None,
            #[cfg(test)]
            hang_backend_ids: Vec::new(),
            #[cfg(test)]
            delay_backend: None,
            #[cfg(test)]
            entity_hits_override: None,
            #[cfg(test)]
            note_hits_override: None,
        }
    }

    /// Construct with a single backend (single-backend deployment default).
    pub fn single(runtime: Arc<KhiveRuntime>) -> Self {
        let mut registry = BackendRegistry::new();
        registry.register(BackendId::main(), runtime);
        Self {
            registry,
            locator: Arc::new(LocatorCache::new()),
            #[cfg(test)]
            fail_backend_id: None,
            #[cfg(test)]
            panic_backend_id: None,
            #[cfg(test)]
            hang_backend_ids: Vec::new(),
            #[cfg(test)]
            delay_backend: None,
            #[cfg(test)]
            entity_hits_override: None,
            #[cfg(test)]
            note_hits_override: None,
        }
    }

    /// Test-only: force `fan_out_search` to simulate a search failure for the named backend.
    #[cfg(test)]
    pub fn with_failing_backend(mut self, backend_id: &str) -> Self {
        self.fail_backend_id = Some(backend_id.to_string());
        self
    }

    /// Test-only: force a named backend's fan-out task to panic.
    #[cfg(test)]
    pub fn with_panicking_backend(mut self, backend_id: &str) -> Self {
        self.panic_backend_id = Some(backend_id.to_string());
        self
    }

    /// Test-only: force a named backend's fan-out search task to hang forever
    /// (never resolves), simulating an unresponsive backend.
    #[cfg(test)]
    pub fn with_hanging_backend(mut self, backend_id: &str) -> Self {
        self.hang_backend_ids = vec![backend_id.to_string()];
        self
    }

    /// Test-only: hang several concurrently-started backend tasks.
    #[cfg(test)]
    pub fn with_hanging_backends<I, S>(mut self, backend_ids: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.hang_backend_ids = backend_ids.into_iter().map(Into::into).collect();
        self
    }

    /// Test-only: delay one backend's result by `delay`.
    #[cfg(test)]
    pub fn with_delayed_backend(mut self, backend_id: &str, delay: Duration) -> Self {
        self.delay_backend = Some((backend_id.to_string(), delay));
        self
    }

    /// Test-only: pin a named backend's entity fan-out contribution to an
    /// exact, caller-supplied ranked list instead of querying storage.
    #[cfg(test)]
    pub fn with_entity_hits_override(mut self, overrides: HashMap<String, Vec<SearchHit>>) -> Self {
        self.entity_hits_override = Some(overrides);
        self
    }

    /// Test-only: pin a named backend's note fan-out contribution to an
    /// exact, caller-supplied ranked list instead of querying storage.
    #[cfg(test)]
    pub fn with_note_hits_override(
        mut self,
        overrides: HashMap<String, Vec<NoteSearchHit>>,
    ) -> Self {
        self.note_hits_override = Some(overrides);
        self
    }

    /// The underlying [`BackendRegistry`].
    pub fn registry(&self) -> &BackendRegistry {
        &self.registry
    }

    /// A shared reference to the locator cache (D2).
    pub fn locator_cache(&self) -> &Arc<LocatorCache> {
        &self.locator
    }

    /// The primary backend's runtime, or `None` if the registry is empty.
    pub fn primary_runtime(&self) -> Option<Arc<KhiveRuntime>> {
        self.registry.primary().map(|e| Arc::clone(&e.runtime))
    }

    /// List all registered backend ids.
    pub fn backend_ids(&self) -> Vec<BackendId> {
        self.registry.ids()
    }

    /// Number of registered backends.
    pub fn backend_count(&self) -> usize {
        self.registry.len()
    }

    /// True when this is a single-backend deployment.
    pub fn is_single_backend(&self) -> bool {
        self.registry.len() <= 1
    }

    // ---- D2: Locator cache ----

    /// Resolve which backend owns the substrate node identified by `id`.
    ///
    /// Namespace-agnostic per ADR-007 Rev 3: presence of the record on a backend
    /// is sufficient — the stored namespace is NOT compared to the caller namespace.
    /// The `namespace` parameter is used only for `runtime.authorize()` capability checks.
    ///
    /// Delegates to the private `locate_endpoint`, which resolves in the same
    /// substrate order as `get` (entity/note/event, then edge — #674), so a
    /// full-UUID `link` endpoint locates exactly what `get` resolves for the
    /// same UUID.
    pub async fn locate(&self, id: Uuid, namespace: &Namespace) -> Option<BackendId> {
        self.locate_endpoint(id, namespace)
            .await
            .map(|e| e.backend_id)
    }

    /// Resolve which backend owns the substrate node identified by `id`,
    /// together with its endpoint kind (entity, note, event, or edge).
    ///
    /// Namespace-agnostic per ADR-007 Rev 3, same contract as [`Self::locate`].
    /// Checks the locator cache first; on a miss, scans all backends concurrently.
    /// Resolves in the same substrate order as `get` (ADR-002 rule 1 parity,
    /// #674): entity/note/event via `resolve_edge_endpoint`, then edge via
    /// `get_edge`.
    async fn locate_endpoint(&self, id: Uuid, namespace: &Namespace) -> Option<LocatedEndpoint> {
        if let Some(backend_id) = self.locator.get(id) {
            let runtime = self
                .registry
                .get(&backend_id)
                .map(|e| Arc::clone(&e.runtime))?;
            let kind = Self::probe_endpoint_kind(&runtime, namespace, id).await?;
            return Some(LocatedEndpoint { backend_id, kind });
        }

        let entries: Vec<(BackendId, Arc<KhiveRuntime>)> = self
            .registry
            .iter()
            .map(|e| (e.id.clone(), Arc::clone(&e.runtime)))
            .collect();

        if entries.is_empty() {
            return None;
        }

        if entries.len() == 1 {
            let (backend_id, runtime) = &entries[0];
            let kind = Self::probe_endpoint_kind(runtime, namespace, id).await?;
            self.locator.insert(id, backend_id.clone());
            return Some(LocatedEndpoint {
                backend_id: backend_id.clone(),
                kind,
            });
        }

        let ns_clone = namespace.clone();
        let locator = Arc::clone(&self.locator);

        let mut handles = Vec::with_capacity(entries.len());
        for (backend_id, runtime) in entries {
            let ns = ns_clone.clone();
            let locator = Arc::clone(&locator);
            let handle = tokio::spawn(khive_storage::inherit_request_read_context(async move {
                let kind = Self::probe_endpoint_kind(&runtime, &ns, id).await?;
                locator.insert(id, backend_id.clone());
                Some(LocatedEndpoint { backend_id, kind })
            }));
            handles.push(handle);
        }

        let results: Vec<Result<Option<LocatedEndpoint>, JoinError>> =
            futures_util::future::join_all(handles).await;
        for result in results {
            if let Ok(Some(located)) = result {
                return Some(located);
            }
        }
        None
    }

    /// Probe a single backend for `id`'s substrate kind, authorizing for
    /// `namespace` first.
    ///
    /// ADR-007 Rev 3: presence on this backend is sufficient — the stored
    /// record namespace is NOT compared to the caller namespace. Mirrors the
    /// by-ID resolution order `get` uses: entity/note/event first
    /// (`resolve_edge_endpoint`), then edge (`get_edge`).
    async fn probe_endpoint_kind(
        runtime: &Arc<KhiveRuntime>,
        namespace: &Namespace,
        id: Uuid,
    ) -> Option<EdgeEndpointKind> {
        let token = match runtime.authorize(namespace.clone()) {
            Ok(t) => t,
            Err(e) => {
                tracing::warn!(error = %e, "locate_endpoint: authorization denied for namespace");
                return None;
            }
        };
        match runtime.resolve_edge_endpoint(&token, id).await {
            Ok(Some(Resolved::Entity(_))) => return Some(EdgeEndpointKind::Entity),
            Ok(Some(Resolved::Note(_))) => return Some(EdgeEndpointKind::Note),
            Ok(Some(Resolved::Event(_))) => return Some(EdgeEndpointKind::Event),
            Ok(Some(Resolved::PackRecord { .. })) | Ok(None) => {}
            Err(e) => {
                tracing::warn!(error = %e, "locate_endpoint: resolve_edge_endpoint failed");
                return None;
            }
        }
        match runtime.get_edge(&token, id).await {
            Ok(Some(_)) => Some(EdgeEndpointKind::Edge),
            Ok(None) => None,
            Err(e) => {
                tracing::warn!(error = %e, "locate_endpoint: get_edge failed");
                None
            }
        }
    }

    /// Prewarm the locator cache after a successful create.
    ///
    /// Called by the `SubstrateCoordinatorService` so that the first `locate()`
    /// for a newly-created record is a cache hit rather than a backend scan.
    pub fn record_created(&self, id: Uuid, backend_id: BackendId) {
        self.locator.insert(id, backend_id);
    }

    /// Invalidate the locator cache entry for `id`.
    pub fn invalidate(&self, id: Uuid) {
        self.locator.remove(id);
    }

    // ---- D3: Cross-backend link ----

    /// Create an edge whose endpoints may be on different backends (ADR-029 D3).
    ///
    /// Locates both `source_id` and `target_id`. When they are on different backends,
    /// the edge is written on the source backend with `target_backend` stamped to the
    /// target backend id. When both endpoints are on the same backend, delegates to
    /// the normal `link` path (no `target_backend` stamp).
    ///
    /// The coordinator validates endpoints via `validate_link_endpoints` on the source
    /// backend's runtime before writing the edge.
    pub async fn link_cross_backend(
        &self,
        namespace: &Namespace,
        source_id: Uuid,
        target_id: Uuid,
        relation: EdgeRelation,
        weight: f64,
        metadata: Option<serde_json::Value>,
    ) -> Result<khive_storage::Edge, String> {
        self.link_cross_backend_observed(
            namespace, source_id, target_id, relation, weight, metadata, false,
        )
        .await
        .map(|row| row.edge)
    }

    /// Observable, policy-aware form of [`Self::link_cross_backend`].
    #[allow(clippy::too_many_arguments)]
    pub async fn link_cross_backend_observed(
        &self,
        namespace: &Namespace,
        source_id: Uuid,
        target_id: Uuid,
        relation: EdgeRelation,
        weight: f64,
        metadata: Option<serde_json::Value>,
        resurrect: bool,
    ) -> Result<khive_storage::EdgeUpsertResult, String> {
        let src_located = self
            .locate_endpoint(source_id, namespace)
            .await
            .ok_or_else(|| format!("node {source_id} not found on any backend"))?;
        let tgt_located = self
            .locate_endpoint(target_id, namespace)
            .await
            .ok_or_else(|| format!("node {target_id} not found on any backend"))?;

        let src_backend = src_located.backend_id.clone();
        let tgt_backend = tgt_located.backend_id.clone();

        let src_runtime = self
            .registry
            .get(&src_backend)
            .map(|e| Arc::clone(&e.runtime))
            .ok_or_else(|| format!("backend {src_backend} not registered"))?;

        let token = src_runtime
            .authorize(namespace.clone())
            .map_err(|e: khive_runtime::RuntimeError| e.to_string())?;

        let cross_backend = src_backend.as_str() != tgt_backend.as_str();

        if !cross_backend {
            // Same-backend: full endpoint validation including existence and kind checks.
            src_runtime
                .validate_link_endpoints(&token, source_id, target_id, relation)
                .await
                .map_err(|e| e.to_string())?;
        } else if relation == EdgeRelation::Annotates {
            // Cross-backend annotates: `locate_endpoint` already resolved each
            // endpoint's substrate kind using the same by-ID order `get` uses
            // (ADR-002 rule 1 parity, #674), including edge-substrate targets
            // that `resolve_primary`/`Resolved` cannot express — no extra
            // cross-backend DB lookup is needed.
            src_runtime
                .validate_annotates_endpoint_kinds(
                    source_id,
                    target_id,
                    Some(src_located.kind),
                    Some(tgt_located.kind),
                )
                .map_err(|e| e.to_string())?;
        } else {
            // Cross-backend, non-annotates: the target entity lives on a different backend so the source
            // runtime cannot resolve it via its own DB. Fetch each endpoint from its
            // respective backend and validate the ADR-002 kind-pairing rules using the
            // pre-fetched records (no cross-backend DB lookup required).
            let tgt_runtime = self
                .registry
                .get(&tgt_backend)
                .map(|e| Arc::clone(&e.runtime))
                .ok_or_else(|| format!("backend {tgt_backend} not registered"))?;
            let tgt_token = tgt_runtime
                .authorize(namespace.clone())
                .map_err(|e: khive_runtime::RuntimeError| e.to_string())?;
            let src_resolved = src_runtime
                .resolve_primary(&token, source_id)
                .await
                .map_err(|e| e.to_string())?;
            let tgt_resolved = tgt_runtime
                .resolve_primary(&tgt_token, target_id)
                .await
                .map_err(|e| e.to_string())?;
            src_runtime
                .validate_link_endpoints_by_resolved(
                    source_id,
                    target_id,
                    relation,
                    src_resolved.as_ref(),
                    tgt_resolved.as_ref(),
                )
                .map_err(|e| e.to_string())?;
        }
        let target_backend_stamp = if cross_backend {
            Some(tgt_backend.as_str().to_string())
        } else {
            None
        };

        let edge = src_runtime
            .link_with_target_backend_observed(
                &token,
                source_id,
                target_id,
                relation,
                weight,
                metadata,
                target_backend_stamp,
                resurrect,
            )
            .await
            .map_err(|e| e.to_string())?;

        Ok(edge)
    }

    // ---- D4: Fan-out search ----

    /// Broadcast a validated KG search request to all registered backends in
    /// parallel. One selected backend passes its ranking evidence through;
    /// multiple selected backends use outer RRF (k=60). Every filter in the
    /// request reaches the matching runtime search method on every backend.
    ///
    /// Per-backend errors are captured in [`BackendSearchResult::error`] — a single
    /// failing backend does NOT abort the fan-out.
    ///
    /// Authorizes each backend token against `namespace` alone (visible set
    /// `[namespace]`) — see [`Self::fan_out_search_with_visibility`] for the
    /// caller-widened-visibility variant the MCP coordinator boundary uses.
    pub async fn fan_out_search(
        &self,
        request: &ValidatedSearchRequest,
        namespace: &Namespace,
    ) -> (Vec<SearchHit>, Vec<NoteSearchHit>, Vec<BackendSearchResult>) {
        self.fan_out_search_with_visibility(request, namespace, &[])
            .await
    }

    /// Same as [`Self::fan_out_search`], but authorizes each backend token
    /// with an explicit extra read-visibility set (MAJ-3 fix).
    ///
    /// `extra_visible` mirrors the normal registry dispatch path's
    /// `['local'] ∪ visible_namespaces` widening
    /// (`khive_runtime::pack::VerbRegistry::dispatch_with_identity`) — pass
    /// `&[]` (equivalent to [`Self::fan_out_search`]) to authorize against
    /// `namespace` alone, or the caller's resolved extra-visible set to widen
    /// read visibility the same way the single-backend registry path does.
    /// An explicit `namespace=` request parameter intentionally narrows
    /// visibility and must be passed as `&[]` by the caller — this method
    /// does not itself distinguish explicit from default namespace
    /// resolution.
    pub async fn fan_out_search_with_visibility(
        &self,
        request: &ValidatedSearchRequest,
        namespace: &Namespace,
        extra_visible: &[Namespace],
    ) -> (Vec<SearchHit>, Vec<NoteSearchHit>, Vec<BackendSearchResult>) {
        let (mut entity_hits, mut note_hits, per_backend) = self
            .fan_out_search_candidates_with_visibility(request, namespace, extra_visible)
            .await;
        self.finalize_search_hits(&mut entity_hits, &mut note_hits, request, namespace)
            .await;
        (entity_hits, note_hits, per_backend)
    }

    async fn fan_out_search_candidates_with_visibility(
        &self,
        request: &ValidatedSearchRequest,
        namespace: &Namespace,
        extra_visible: &[Namespace],
    ) -> (Vec<SearchHit>, Vec<NoteSearchHit>, Vec<BackendSearchResult>) {
        let search_notes = request.substrate() == SearchSubstrate::Note;
        let requested_substrate = if search_notes {
            SubstrateKind::Note
        } else {
            SubstrateKind::Entity
        };
        let search_limit = rrf_fanout_search_limit(request);
        let props_filter_owned = request.properties().cloned();
        let tags_owned = request.tags().to_vec();
        let kind_filter_owned = request.kind_filter().map(str::to_string);
        let entity_type_owned = request.entity_type().map(str::to_string);
        let include_superseded = request.include_superseded();

        let entries: Vec<(BackendId, Arc<KhiveRuntime>)> = self
            .registry
            .iter()
            .filter(|entry| entry.serves(requested_substrate))
            .map(|e| (e.id.clone(), Arc::clone(&e.runtime)))
            .collect();

        if entries.is_empty() {
            return (vec![], vec![], vec![]);
        }

        let timeout_ms = backend_search_timeout_ms();
        let timeout_dur = Duration::from_millis(timeout_ms);
        let request_deadline = khive_storage::effective_request_read_deadline(
            khive_storage::RequestReadDeadline::after(timeout_dur),
        );

        if entries.len() == 1 {
            let (backend_id, runtime) = &entries[0];
            let token = match runtime
                .authorize_with_visibility(namespace.clone(), extra_visible.to_vec())
            {
                Ok(t) => t,
                Err(e) => {
                    tracing::warn!(
                        error = %bounded_backend_cause_for_log(&e.to_string()),
                        "fan_out_search: authorization denied for namespace"
                    );
                    let backend_result = BackendSearchResult {
                        backend_id: backend_id.clone(),
                        hits: vec![],
                        note_hits: vec![],
                        error: Some(BackendSearchFailure::from_runtime_error(e)),
                        vector_error: None,
                    };
                    return (vec![], vec![], vec![backend_result]);
                }
            };
            // MAJ-2 (r2 follow-up): the single-backend early return has no
            // spawned task to bound with the fan-out timeout loop below, so
            // both awaits are wrapped directly in the same
            // `backend_search_timeout_ms()` budget — an unbounded await here
            // would leave a hung single-backend deployment's search
            // unbounded even though the multi-backend path is bounded.
            #[cfg(test)]
            let should_hang = self
                .hang_backend_ids
                .iter()
                .any(|id| id == backend_id.as_str());
            #[cfg(not(test))]
            let should_hang = false;
            if search_notes {
                let search_fut = async {
                    if should_hang {
                        std::future::pending::<()>().await;
                        unreachable!("a pending future never resolves");
                    }
                    runtime
                        .search_notes_outcome_with_text_mode(
                            &token,
                            request.query(),
                            search_limit,
                            request.kind_filter(),
                            include_superseded,
                            &tags_owned,
                            props_filter_owned.as_ref(),
                            request.text_mode(),
                        )
                        .await
                };
                let search_fut =
                    khive_storage::scope_request_read_deadline_at(request_deadline, search_fut);
                tokio::pin!(search_fut);
                match tokio::time::timeout_at(request_deadline.async_at(), &mut search_fut).await {
                    Ok(Ok(outcome)) => {
                        let filtered_note_hits: Vec<NoteSearchHit> = outcome
                            .hits
                            .iter()
                            .filter(|hit| {
                                request
                                    .source()
                                    .is_none_or(|expected| hit.source == expected)
                            })
                            .cloned()
                            .collect();
                        let backend_result = BackendSearchResult {
                            backend_id: backend_id.clone(),
                            hits: vec![],
                            note_hits: outcome.hits,
                            error: None,
                            vector_error: outcome.vector_error,
                        };
                        return (vec![], filtered_note_hits, vec![backend_result]);
                    }
                    Ok(Err(e)) => {
                        let backend_result = BackendSearchResult {
                            backend_id: backend_id.clone(),
                            hits: vec![],
                            note_hits: vec![],
                            error: Some(BackendSearchFailure::from_runtime_error(e)),
                            vector_error: None,
                        };
                        return (vec![], vec![], vec![backend_result]);
                    }
                    Err(_elapsed) => {
                        let _ = tokio::time::timeout(
                            khive_db::sqlite_interrupt_grace_from_env(),
                            &mut search_fut,
                        )
                        .await;
                        tracing::warn!(
                            backend = %bounded_backend_id_for_log(backend_id.as_str()),
                            timeout_ms,
                            "backend search task timed out"
                        );
                        let backend_result = BackendSearchResult {
                            backend_id: backend_id.clone(),
                            hits: vec![],
                            note_hits: vec![],
                            error: Some(BackendSearchFailure::timeout(timeout_ms)),
                            vector_error: None,
                        };
                        return (vec![], vec![], vec![backend_result]);
                    }
                }
            } else {
                let search_fut = async {
                    if should_hang {
                        std::future::pending::<()>().await;
                        unreachable!("a pending future never resolves");
                    }
                    runtime
                        .hybrid_search_outcome_with_text_mode(
                            &token,
                            request.query(),
                            search_limit,
                            request.kind_filter(),
                            request.entity_type(),
                            &tags_owned,
                            props_filter_owned.as_ref(),
                            request.text_mode(),
                        )
                        .await
                };
                let search_fut =
                    khive_storage::scope_request_read_deadline_at(request_deadline, search_fut);
                tokio::pin!(search_fut);
                match tokio::time::timeout_at(request_deadline.async_at(), &mut search_fut).await {
                    Ok(Ok(outcome)) => {
                        let filtered_hits: Vec<SearchHit> = outcome
                            .hits
                            .iter()
                            .filter(|hit| {
                                request
                                    .source()
                                    .is_none_or(|expected| hit.source == expected)
                            })
                            .cloned()
                            .collect();
                        let backend_result = BackendSearchResult {
                            backend_id: backend_id.clone(),
                            hits: outcome.hits,
                            note_hits: vec![],
                            error: None,
                            vector_error: outcome.vector_error,
                        };
                        return (filtered_hits, vec![], vec![backend_result]);
                    }
                    Ok(Err(e)) => {
                        let backend_result = BackendSearchResult {
                            backend_id: backend_id.clone(),
                            hits: vec![],
                            note_hits: vec![],
                            error: Some(BackendSearchFailure::from_runtime_error(e)),
                            vector_error: None,
                        };
                        return (vec![], vec![], vec![backend_result]);
                    }
                    Err(_elapsed) => {
                        let _ = tokio::time::timeout(
                            khive_db::sqlite_interrupt_grace_from_env(),
                            &mut search_fut,
                        )
                        .await;
                        tracing::warn!(
                            backend = %bounded_backend_id_for_log(backend_id.as_str()),
                            timeout_ms,
                            "backend search task timed out"
                        );
                        let backend_result = BackendSearchResult {
                            backend_id: backend_id.clone(),
                            hits: vec![],
                            note_hits: vec![],
                            error: Some(BackendSearchFailure::timeout(timeout_ms)),
                            vector_error: None,
                        };
                        return (vec![], vec![], vec![backend_result]);
                    }
                }
            }
        }

        let query = request.query().to_string();
        let ns = namespace.clone();
        let extra_visible_owned = extra_visible.to_vec();

        #[cfg(test)]
        let fail_id: Option<String> = self.fail_backend_id.clone();
        #[cfg(not(test))]
        let fail_id: Option<String> = None;
        #[cfg(test)]
        let panic_id: Option<String> = self.panic_backend_id.clone();
        #[cfg(not(test))]
        let panic_id: Option<String> = None;
        #[cfg(test)]
        let hang_ids: Vec<String> = self.hang_backend_ids.clone();
        #[cfg(not(test))]
        let hang_ids: Vec<String> = Vec::new();
        #[cfg(test)]
        let delay_backend = self.delay_backend.clone();
        #[cfg(not(test))]
        let delay_backend: Option<(String, Duration)> = None;

        let mut handles = Vec::with_capacity(entries.len());
        for (backend_id, runtime) in entries {
            let q = query.clone();
            let ns = ns.clone();
            let extra_visible_task = extra_visible_owned.clone();
            let kf = kind_filter_owned.clone();
            let et = entity_type_owned.clone();
            let pf = props_filter_owned.clone();
            let tg = tags_owned.clone();
            let sl = search_limit;
            let text_mode = request.text_mode();
            let should_fail = fail_id
                .as_deref()
                .map(|id| id == backend_id.as_str())
                .unwrap_or(false);
            let should_panic = panic_id
                .as_deref()
                .map(|id| id == backend_id.as_str())
                .unwrap_or(false);
            let should_hang = hang_ids.iter().any(|id| id == backend_id.as_str());
            let delay = delay_backend
                .as_ref()
                .and_then(|(id, delay)| (id == backend_id.as_str()).then_some(*delay));
            #[cfg(test)]
            let entity_override: Option<Vec<SearchHit>> = self
                .entity_hits_override
                .as_ref()
                .and_then(|m| m.get(backend_id.as_str()))
                .cloned();
            #[cfg(not(test))]
            let entity_override: Option<Vec<SearchHit>> = None;
            #[cfg(test)]
            let note_override: Option<Vec<NoteSearchHit>> = self
                .note_hits_override
                .as_ref()
                .and_then(|m| m.get(backend_id.as_str()))
                .cloned();
            #[cfg(not(test))]
            let note_override: Option<Vec<NoteSearchHit>> = None;
            let joined_backend_id = backend_id.clone();
            let search = async move {
                if should_panic {
                    panic!("injected backend search panic");
                }
                if should_hang {
                    // Never resolves — exercises the fan-out timeout (MAJ-2).
                    std::future::pending::<()>().await;
                    unreachable!("a pending future never resolves");
                }
                if let Some(delay) = delay {
                    tokio::time::sleep(delay).await;
                }
                if should_fail {
                    return (
                        backend_id,
                        Err(khive_runtime::RuntimeError::Internal(
                            "injected failure".to_string(),
                        )),
                        None::<Vec<NoteSearchHit>>,
                        None,
                    );
                }
                if search_notes {
                    if let Some(hits) = note_override {
                        return (backend_id, Ok(vec![]), Some(hits), None);
                    }
                } else if let Some(hits) = entity_override {
                    return (backend_id, Ok(hits), None, None);
                }
                let token = match runtime.authorize_with_visibility(ns, extra_visible_task) {
                    Ok(t) => t,
                    Err(e) => {
                        tracing::warn!(
                            error = %bounded_backend_cause_for_log(&e.to_string()),
                            "fan_out_search: authorization denied for namespace"
                        );
                        return (backend_id, Err(e), None, None);
                    }
                };
                if search_notes {
                    let result = runtime
                        .search_notes_outcome_with_text_mode(
                            &token,
                            &q,
                            sl,
                            kf.as_deref(),
                            include_superseded,
                            &tg,
                            pf.as_ref(),
                            text_mode,
                        )
                        .await;
                    match result {
                        // Full search_limit-bounded window is retained here —
                        // truncating to the caller's limit per backend (MAJ-4)
                        // would remove candidates the RRF merge needs to fairly
                        // rank a hit that only places #2+ on any single backend.
                        // Finalization applies the floor and requested order
                        // before imposing the caller's limit.
                        Ok(outcome) => (
                            backend_id,
                            Ok(vec![]),
                            Some(outcome.hits),
                            outcome.vector_error,
                        ),
                        Err(e) => (backend_id, Err(e), None, None),
                    }
                } else {
                    let result = runtime
                        .hybrid_search_outcome_with_text_mode(
                            &token,
                            &q,
                            sl,
                            kf.as_deref(),
                            et.as_deref(),
                            &tg,
                            pf.as_ref(),
                            text_mode,
                        )
                        .await;
                    match result {
                        // See the note-substrate arm above: no per-backend
                        // truncation before RRF merge (MAJ-4).
                        Ok(outcome) => (backend_id, Ok(outcome.hits), None, outcome.vector_error),
                        Err(e) => (backend_id, Err(e), None, None),
                    }
                }
            };
            let search = async move {
                let result = search.await;
                (result, tokio::time::Instant::now())
            };
            let handle = tokio::spawn(khive_storage::inherit_request_read_context(
                khive_storage::scope_request_read_deadline_at(request_deadline, search),
            ));
            handles.push((joined_backend_id, handle));
        }

        let mut per_backend: Vec<BackendSearchResult> = Vec::new();
        let mut entity_ranked_lists: Vec<Vec<SearchHit>> = Vec::new();
        let mut note_ranked_lists: Vec<Vec<NoteSearchHit>> = Vec::new();
        let interrupt_settlement_deadline =
            request_deadline.async_at() + khive_db::sqlite_interrupt_grace_from_env();
        for (joined_backend_id, mut handle) in handles {
            let joined = if handle.is_finished() {
                Ok((&mut handle).await)
            } else {
                match tokio::time::timeout_at(request_deadline.async_at(), &mut handle).await {
                    Ok(result) => Ok(result),
                    Err(elapsed) => {
                        let settled =
                            tokio::time::timeout_at(interrupt_settlement_deadline, &mut handle)
                                .await;
                        if settled.is_err() {
                            handle.abort();
                            let _ = (&mut handle).await;
                        }
                        // The grace window exists only to let SQLite tear down
                        // an interrupted statement and return its permit.  It
                        // must not extend the advertised request deadline.
                        Err(elapsed)
                    }
                }
            };
            match joined {
                Ok(Ok(((backend_id, Ok(hits), note_hits_opt, vector_error), completed_at)))
                    if completed_at <= request_deadline.async_at() =>
                {
                    let note_hits = note_hits_opt.unwrap_or_default();
                    if !hits.is_empty() {
                        entity_ranked_lists.push(hits.clone());
                    }
                    if !note_hits.is_empty() {
                        note_ranked_lists.push(note_hits.clone());
                    }
                    per_backend.push(BackendSearchResult {
                        backend_id,
                        hits,
                        note_hits,
                        error: None,
                        vector_error,
                    });
                }
                Ok(Ok(((backend_id, Err(e), _, _), completed_at)))
                    if completed_at <= request_deadline.async_at() =>
                {
                    per_backend.push(BackendSearchResult {
                        backend_id,
                        hits: vec![],
                        note_hits: vec![],
                        error: Some(BackendSearchFailure::from_runtime_error(e)),
                        vector_error: None,
                    });
                }
                Ok(Err(join_err)) => {
                    let error = khive_runtime::RuntimeError::Internal(format!(
                        "backend search task join failed: {join_err}"
                    ));
                    tracing::warn!(
                        backend = %bounded_backend_id_for_log(joined_backend_id.as_str()),
                        error = %bounded_backend_cause_for_log(&error.to_string()),
                        "backend search task failed"
                    );
                    per_backend.push(BackendSearchResult {
                        backend_id: joined_backend_id,
                        hits: vec![],
                        note_hits: vec![],
                        error: Some(BackendSearchFailure::from_runtime_error(error)),
                        vector_error: None,
                    });
                }
                Ok(Ok((_late_result, _completed_at))) => {
                    tracing::warn!(
                        backend = %bounded_backend_id_for_log(joined_backend_id.as_str()),
                        timeout_ms,
                        "backend search task completed after the shared request deadline"
                    );
                    per_backend.push(BackendSearchResult {
                        backend_id: joined_backend_id,
                        hits: vec![],
                        note_hits: vec![],
                        error: Some(BackendSearchFailure::timeout(timeout_ms)),
                        vector_error: None,
                    });
                }
                Err(_elapsed) => {
                    tracing::warn!(
                        backend = %bounded_backend_id_for_log(joined_backend_id.as_str()),
                        timeout_ms,
                        "backend search task timed out"
                    );
                    per_backend.push(BackendSearchResult {
                        backend_id: joined_backend_id,
                        hits: vec![],
                        note_hits: vec![],
                        error: Some(BackendSearchFailure::timeout(timeout_ms)),
                        vector_error: None,
                    });
                }
            }
        }

        let merged_entities =
            rrf_merge_entity_hits_filtered(entity_ranked_lists, usize::MAX, request.source());
        let merged_notes =
            rrf_merge_note_hits_filtered(note_ranked_lists, usize::MAX, request.source());
        (merged_entities, merged_notes, per_backend)
    }
}

/// Per-backend fan-out search timeout (MAJ-2 fix): bounds how long a single
/// backend's search task may run before the coordinator gives up on it and
/// reports a timeout-specific error for that backend, so one hung backend
/// cannot block the whole fan-out from returning healthy siblings' results.
const DEFAULT_BACKEND_SEARCH_TIMEOUT_MS: u64 = 5_000;

/// Return the cached per-backend fan-out search timeout in milliseconds.
/// See `KHIVE_COORDINATOR_SEARCH_TIMEOUT_MS` in
/// `crates/kkernel/docs/api/configuration.md`.
fn backend_search_timeout_ms() -> u64 {
    static TIMEOUT_MS: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
    *TIMEOUT_MS.get_or_init(|| {
        let ms = std::env::var("KHIVE_COORDINATOR_SEARCH_TIMEOUT_MS")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(DEFAULT_BACKEND_SEARCH_TIMEOUT_MS);
        khive_runtime::config_ledger::record_config_locked(
            "KHIVE_COORDINATOR_SEARCH_TIMEOUT_MS",
            ms.to_string(),
        );
        ms
    })
}

/// Per-backend fan-out over-fetch bound for RRF merge fairness (MAJ-4 fix).
///
/// Each backend must contribute more than just the caller's `limit` worth of
/// ranked candidates, or a candidate that ranks #2+ on multiple backends can
/// never out-fuse a rank-1 singleton that only one backend saw — truncating
/// to `limit` per backend removes it before the merge ever sees it.
/// `request.candidate_limit()` already widens the per-backend fetch for
/// request-filter recall; this widens further (bounded) so unfiltered
/// fan-out searches get the same fairness. The caller's `limit` is applied
/// exactly once in `finalize_search_hits`, after fusion, the score floor and
/// the requested ordering.
const RRF_FANOUT_MULTIPLIER: u32 = 10;
/// Same cap shape as `FILTERED_SCAN_CAP` in khive-pack-kg's search handler,
/// applied to the fan-out-wide candidate window.
const RRF_FANOUT_CAP: u32 = 500;

fn rrf_fanout_search_limit(request: &ValidatedSearchRequest) -> u32 {
    request
        .candidate_limit()
        .max(request.limit().saturating_mul(RRF_FANOUT_MULTIPLIER))
        .min(RRF_FANOUT_CAP)
}

// ---- RRF merge ----

#[derive(Default)]
struct RrfMergeBucket {
    score: DeterministicScore,
    // Ranked lists follow backend ID order; equal ranks retain the earlier backend.
    evidence_rank: Option<usize>,
    signals: khive_runtime::SearchSignals,
    source: Option<SearchSource>,
    title: Option<String>,
    snippet: Option<String>,
}

/// Merge multiple ranked entity hit lists via Reciprocal Rank Fusion (k=60).
#[cfg(test)]
pub(super) fn rrf_merge_entity_hits(lists: Vec<Vec<SearchHit>>, limit: usize) -> Vec<SearchHit> {
    rrf_merge_entity_hits_filtered(lists, limit, None)
}

fn rrf_merge_entity_hits_filtered(
    lists: Vec<Vec<SearchHit>>,
    limit: usize,
    source_filter: Option<SearchSource>,
) -> Vec<SearchHit> {
    const K: usize = 60;

    let mut scores: HashMap<Uuid, RrfMergeBucket> = HashMap::new();

    for list in &lists {
        for (i, hit) in list.iter().enumerate() {
            let entry = scores.entry(hit.entity_id).or_default();
            entry.score = entry.score + rrf_score(i + 1, K);
            if entry.evidence_rank.is_none_or(|best_rank| i < best_rank) {
                entry.evidence_rank = Some(i);
                entry.signals = hit.signals;
            }
            entry.source = Some(match entry.source {
                Some(source) => source.union(hit.source),
                None => hit.source,
            });
            if entry.title.is_none() {
                entry.title = hit.title.clone();
            }
            if entry.snippet.is_none() {
                entry.snippet = hit.snippet.clone();
            }
        }
    }

    let mut merged: Vec<SearchHit> = scores
        .into_iter()
        .filter_map(|(id, bucket)| {
            let source = bucket.source.expect("each bucket gets a source");
            if source_filter.is_some_and(|expected| source != expected) {
                return None;
            }
            Some(SearchHit {
                entity_id: id,
                score: bucket.score,
                rank_score_kind: khive_runtime::RankScoreKind::Rrf,
                signals: bucket.signals,
                source,
                title: bucket.title,
                snippet: bucket.snippet,
            })
        })
        .collect();

    merged.sort_by(|a, b| b.score.cmp(&a.score).then(a.entity_id.cmp(&b.entity_id)));
    merged.truncate(limit);
    merged
}

/// Merge multiple ranked note hit lists via Reciprocal Rank Fusion (k=60).
#[cfg(test)]
pub(super) fn rrf_merge_note_hits(
    lists: Vec<Vec<NoteSearchHit>>,
    limit: usize,
) -> Vec<NoteSearchHit> {
    rrf_merge_note_hits_filtered(lists, limit, None)
}

fn rrf_merge_note_hits_filtered(
    lists: Vec<Vec<NoteSearchHit>>,
    limit: usize,
    source_filter: Option<SearchSource>,
) -> Vec<NoteSearchHit> {
    const K: usize = 60;

    let mut scores: HashMap<Uuid, RrfMergeBucket> = HashMap::new();

    for list in &lists {
        for (i, hit) in list.iter().enumerate() {
            let entry = scores.entry(hit.note_id).or_default();
            entry.score = entry.score + rrf_score(i + 1, K);
            if entry.evidence_rank.is_none_or(|best_rank| i < best_rank) {
                entry.evidence_rank = Some(i);
                entry.signals = hit.signals;
            }
            entry.source = Some(match entry.source {
                Some(source) => source.union(hit.source),
                None => hit.source,
            });
            if entry.title.is_none() {
                entry.title = hit.title.clone();
            }
            if entry.snippet.is_none() {
                entry.snippet = hit.snippet.clone();
            }
        }
    }

    let mut merged: Vec<NoteSearchHit> = scores
        .into_iter()
        .filter_map(|(id, bucket)| {
            let source = bucket.source.expect("each bucket gets a source");
            if source_filter.is_some_and(|expected| source != expected) {
                return None;
            }
            Some(NoteSearchHit {
                note_id: id,
                score: bucket.score,
                rank_score_kind: khive_runtime::RankScoreKind::Rrf,
                signals: bucket.signals,
                source,
                title: bucket.title,
                snippet: bucket.snippet,
            })
        })
        .collect();

    merged.sort_by(|a, b| b.score.cmp(&a.score).then(a.note_id.cmp(&b.note_id)));
    merged.truncate(limit);
    merged
}

// ---- futures_util shim ----
//
// `khive-runtime` pulls in `futures` transitively. We use `futures::future::join_all`
// through this local shim to avoid adding a direct `futures` dep on kkernel.
mod futures_util {
    pub mod future {
        pub async fn join_all<F: std::future::Future>(
            futs: Vec<F>,
        ) -> Vec<<F as std::future::Future>::Output> {
            let mut results = Vec::with_capacity(futs.len());
            for fut in futs {
                results.push(fut.await);
            }
            results
        }
    }
}

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

    // Mirrors khive-mcp's
    // backend_error_message_drops_a_url_credential_whose_terminator_crosses_the_window:
    // the credential's terminating `@` lands past the shared masking window,
    // so a masker restricted to the window can never recognize the span. The
    // whole straddling token — having no internal whitespace — is dropped
    // rather than partially echoed, so no fragment of it survives even
    // though it is never marked as masked.

    #[test]
    fn backend_cause_for_log_drops_a_url_credential_whose_terminator_crosses_the_window() {
        let marker = "CoordinatorCauseMarkerXYZ789";
        let padding = "z".repeat(khive_runtime::secret_gate::MASK_WINDOW_CHARS + 200);
        let password = format!("{marker}{padding}");
        let url = format!("postgres://svc:{password}@internal-host.example.com/db");
        let message = format!("backend probe failed: {url}");

        let at_offset = message.find('@').expect("test fixture must contain '@'");
        assert!(at_offset > khive_runtime::secret_gate::MASK_WINDOW_CHARS);

        let bounded = bounded_backend_cause_for_log(&message);
        assert!(
            !bounded.contains(marker),
            "no fragment of the credential may survive: {bounded}"
        );
        assert!(
            !bounded.contains("postgres://"),
            "the straddling token must be dropped whole, not partially echoed: {bounded}"
        );
        assert!(bounded.starts_with("backend probe failed:"));
        assert!(bounded.ends_with('…'));
    }

    #[test]
    fn backend_id_for_log_drops_a_url_credential_whose_terminator_crosses_the_window() {
        let marker = "CoordinatorIdMarkerXYZ789";
        let padding = "z".repeat(khive_runtime::secret_gate::MASK_WINDOW_CHARS + 200);
        let password = format!("{marker}{padding}");
        let backend_id = format!("postgres://svc:{password}@internal-host.example.com/db");

        let at_offset = backend_id.find('@').expect("test fixture must contain '@'");
        assert!(at_offset > khive_runtime::secret_gate::MASK_WINDOW_CHARS);

        let bounded = bounded_backend_id_for_log(&backend_id);
        assert!(
            !bounded.contains(marker),
            "no fragment of the credential may survive: {bounded}"
        );
    }
}