Skip to main content

hawdb_search/
recall_validation.rs

1// Copyright 2026 Nowledge
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use super::{SearchRetrieverReport, DISKANN_CANDIDATE_BACKEND, RABITQ_CANDIDATE_BACKEND};
16use crate::{HawDBError, Result};
17use hawdb_evidence::production_evidence_blocker_codes;
18use std::collections::BTreeSet;
19
20pub const VECTOR_RECALL_VALIDATION_PROTOCOL: &str = "hawdb-vector-recall-validation-v1";
21pub const VECTOR_RECALL_PRODUCTION_QUALIFICATION_PROTOCOL: &str =
22    "hawdb-vector-recall-production-qualification-v1";
23pub const MAX_VECTOR_RECALL_VALIDATION_SAMPLES: usize = 128;
24pub const MAX_VECTOR_RECALL_VALIDATION_TOP_K: usize = 100;
25pub const MAX_VECTOR_RECALL_VALIDATION_CANDIDATE_LIMIT: usize = 1_000;
26pub const MINIMUM_VECTOR_QUALIFICATION_DOCUMENT_COUNT: usize = 100_000;
27const PER_MILLION: u64 = 1_000_000;
28const RECALL_SAMPLE_SEED: u64 = 0x534B_4549_4E52_4543;
29
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct VectorRecallValidationOptions {
32    pub max_samples: usize,
33    pub top_k: usize,
34    pub candidate_limit: usize,
35    pub minimum_recall_per_million: u32,
36    pub metadata_filters: std::collections::BTreeMap<String, String>,
37}
38
39impl Default for VectorRecallValidationOptions {
40    fn default() -> Self {
41        Self {
42            max_samples: 32,
43            top_k: 10,
44            candidate_limit: 40,
45            minimum_recall_per_million: 950_000,
46            metadata_filters: std::collections::BTreeMap::new(),
47        }
48    }
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
52pub enum VectorRecallValidationBlocker {
53    NoSamplesRequested,
54    TopKZero,
55    CandidateLimitBelowTopK,
56    MetadataFilterInvalid,
57    ProbeExecutionFailed,
58    NoEligibleVectors,
59    GroundTruthEmpty,
60    ApproximateBackendUnavailable,
61    ApproximateFallbackObserved,
62    IndexCoverageIncomplete,
63    CandidateRecallBelowThreshold,
64    RecallBelowThreshold,
65}
66
67impl VectorRecallValidationBlocker {
68    pub const fn as_str(self) -> &'static str {
69        match self {
70            Self::NoSamplesRequested => "no_samples_requested",
71            Self::TopKZero => "top_k_zero",
72            Self::CandidateLimitBelowTopK => "candidate_limit_below_top_k",
73            Self::MetadataFilterInvalid => "metadata_filter_invalid",
74            Self::ProbeExecutionFailed => "probe_execution_failed",
75            Self::NoEligibleVectors => "no_eligible_vectors",
76            Self::GroundTruthEmpty => "ground_truth_empty",
77            Self::ApproximateBackendUnavailable => "approximate_backend_unavailable",
78            Self::ApproximateFallbackObserved => "approximate_fallback_observed",
79            Self::IndexCoverageIncomplete => "index_coverage_incomplete",
80            Self::CandidateRecallBelowThreshold => "candidate_recall_below_threshold",
81            Self::RecallBelowThreshold => "recall_below_threshold",
82        }
83    }
84}
85
86/// Deterministic sampled recall over indexed vectors used as queries.
87///
88/// Sampling is uniform without replacement with a fixed replay seed, not a
89/// document-ID stride. The query's own ID is excluded from hits, but these are
90/// still in-corpus queries: this is not held-out production-query recall.
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub struct VectorRecallValidationReport {
93    pub protocol: String,
94    pub ready: bool,
95    pub approximate_backend: String,
96    pub sample_candidate_count: usize,
97    pub requested_sample_count: usize,
98    pub executed_sample_count: usize,
99    pub top_k: usize,
100    pub candidate_limit: usize,
101    pub minimum_recall_per_million: u32,
102    pub exact_hit_count: usize,
103    pub candidate_hit_count: usize,
104    pub candidate_overlap_count: usize,
105    pub candidate_recall_at_k_per_million: u32,
106    pub approximate_hit_count: usize,
107    pub overlap_count: usize,
108    pub recall_at_k_per_million: u32,
109    pub overlap_at_k_per_million: u32,
110    pub fallback_count: usize,
111    pub index_coverage_incomplete_count: usize,
112    pub average_filter_selectivity_per_million: u32,
113    pub max_filter_selectivity_per_million: u32,
114    pub blocker_codes: Vec<VectorRecallValidationBlocker>,
115}
116
117impl VectorRecallValidationReport {
118    /// Validate the explicitly required compressed candidate backend.
119    pub fn validates_required_approximate_backend(&self) -> bool {
120        self.validates_backend(RABITQ_CANDIDATE_BACKEND)
121    }
122
123    pub fn validates_default_approximate_backend(&self) -> bool {
124        self.validates_backend(DISKANN_CANDIDATE_BACKEND)
125    }
126
127    fn validates_backend(&self, backend: &str) -> bool {
128        self.protocol == VECTOR_RECALL_VALIDATION_PROTOCOL
129            && self.ready
130            && self.approximate_backend == backend
131            && self.requested_sample_count > 0
132            && self.executed_sample_count == self.requested_sample_count
133            && self.exact_hit_count > 0
134            && self.candidate_recall_at_k_per_million >= self.minimum_recall_per_million
135            && self.fallback_count == 0
136            && self.index_coverage_incomplete_count == 0
137            && self.recall_at_k_per_million >= self.minimum_recall_per_million
138            && self.blocker_codes.is_empty()
139    }
140
141    pub fn json(&self) -> serde_json::Value {
142        serde_json::json!({
143            "protocol": self.protocol,
144            "ready": self.ready,
145            "sampling": {
146                "method": "floyd_splitmix64_without_replacement",
147                "seed": format!("{RECALL_SAMPLE_SEED:016x}"),
148                "query_source": "indexed_vectors",
149                "self_hit_excluded": true,
150                "held_out_queries": false,
151                "caveat": "In-corpus self-queries can overestimate held-out query recall.",
152            },
153            "approximate_backend": self.approximate_backend,
154            "sample_candidate_count": self.sample_candidate_count,
155            "requested_sample_count": self.requested_sample_count,
156            "executed_sample_count": self.executed_sample_count,
157            "top_k": self.top_k,
158            "candidate_limit": self.candidate_limit,
159            "minimum_recall_per_million": self.minimum_recall_per_million,
160            "exact_hit_count": self.exact_hit_count,
161            "candidate_hit_count": self.candidate_hit_count,
162            "candidate_overlap_count": self.candidate_overlap_count,
163            "candidate_recall_at_k_per_million": self.candidate_recall_at_k_per_million,
164            "approximate_hit_count": self.approximate_hit_count,
165            "overlap_count": self.overlap_count,
166            "recall_at_k_per_million": self.recall_at_k_per_million,
167            "overlap_at_k_per_million": self.overlap_at_k_per_million,
168            "fallback_count": self.fallback_count,
169            "index_coverage_incomplete_count": self.index_coverage_incomplete_count,
170            "average_filter_selectivity_per_million": self.average_filter_selectivity_per_million,
171            "max_filter_selectivity_per_million": self.max_filter_selectivity_per_million,
172            "blocker_codes": self.blocker_codes.iter().map(|code| code.as_str()).collect::<Vec<_>>(),
173        })
174    }
175}
176
177#[derive(Debug, Clone, Default, PartialEq, Eq)]
178pub struct VectorProjectionQualificationIdentity {
179    pub projection_generation: u64,
180    pub source_graph_commit_epoch: Option<u64>,
181    pub document_count: usize,
182    pub source_digest: u64,
183    pub payload_bytes: u64,
184    /// Raw projection checksum, or the complete selected-manifest fingerprint
185    /// for out-of-core DiskANN graph/visibility artifact closures.
186    pub payload_checksum: u32,
187    pub format_version: u32,
188    pub algorithm: String,
189    pub bit_width: u8,
190    pub dimension: usize,
191    pub transform_seed: u64,
192    pub embedding_model: Option<String>,
193    pub embedding_version: Option<String>,
194    pub file_backed: bool,
195}
196
197#[derive(Debug, Clone, Default, PartialEq, Eq)]
198pub struct VectorProjectionResourceEvidence {
199    pub segment_count: usize,
200    pub requested_segment_rows: usize,
201    pub admitted_segment_rows: usize,
202    pub configured_build_working_bytes: usize,
203    pub peak_build_working_bytes: usize,
204    pub raw_vector_bytes: u64,
205    pub projection_payload_bytes: u64,
206    pub build_write_amplification_per_million: u64,
207}
208
209impl VectorProjectionResourceEvidence {
210    pub fn json(&self) -> serde_json::Value {
211        serde_json::json!({
212            "segment_count": self.segment_count,
213            "requested_segment_rows": self.requested_segment_rows,
214            "admitted_segment_rows": self.admitted_segment_rows,
215            "configured_build_working_bytes": self.configured_build_working_bytes,
216            "peak_build_working_bytes": self.peak_build_working_bytes,
217            "raw_vector_bytes": self.raw_vector_bytes,
218            "projection_payload_bytes": self.projection_payload_bytes,
219            "build_write_amplification_per_million": self.build_write_amplification_per_million,
220        })
221    }
222}
223
224impl VectorProjectionQualificationIdentity {
225    pub fn json(&self) -> serde_json::Value {
226        serde_json::json!({
227            "projection_generation": self.projection_generation,
228            "source_graph_commit_epoch": self.source_graph_commit_epoch,
229            "document_count": self.document_count,
230            "source_digest": self.source_digest,
231            "payload_bytes": self.payload_bytes,
232            "payload_checksum": self.payload_checksum,
233            "format_version": self.format_version,
234            "algorithm": self.algorithm,
235            "bit_width": self.bit_width,
236            "dimension": self.dimension,
237            "transform_seed": self.transform_seed,
238            "embedding_model": self.embedding_model,
239            "embedding_version": self.embedding_version,
240            "file_backed": self.file_backed,
241        })
242    }
243
244    fn complete(&self) -> bool {
245        self.projection_generation > 0
246            && self.source_graph_commit_epoch.is_some()
247            && self.document_count > 0
248            && self.source_digest > 0
249            && self.payload_bytes > 0
250            && self.format_version > 0
251            && match self.algorithm.as_str() {
252                "rabitq" => matches!(self.bit_width, 1 | 4),
253                "diskann" => {
254                    self.format_version == 2 && self.bit_width == 0 && self.transform_seed == 0
255                }
256                _ => false,
257            }
258            && self.dimension > 0
259            && self
260                .embedding_model
261                .as_deref()
262                .is_some_and(|value| !value.trim().is_empty())
263            && self
264                .embedding_version
265                .as_deref()
266                .is_some_and(|value| !value.trim().is_empty())
267            && self.file_backed
268    }
269}
270
271#[derive(Debug, Clone, PartialEq, Eq)]
272pub struct VectorRecallProductionQualificationReport {
273    pub protocol: String,
274    pub recall: VectorRecallValidationReport,
275    pub projection_identity: VectorProjectionQualificationIdentity,
276    pub evidence_binding: crate::ProductionEvidenceBinding,
277    pub expected_identity: crate::ProductionQualificationIdentity,
278    pub blocker_codes: Vec<String>,
279    pub ready: bool,
280}
281
282impl VectorRecallProductionQualificationReport {
283    pub fn evaluate(
284        recall: VectorRecallValidationReport,
285        projection_identity: VectorProjectionQualificationIdentity,
286        evidence_binding: crate::ProductionEvidenceBinding,
287        expected_identity: crate::ProductionQualificationIdentity,
288    ) -> Self {
289        let mut report = Self {
290            protocol: VECTOR_RECALL_PRODUCTION_QUALIFICATION_PROTOCOL.to_string(),
291            recall,
292            projection_identity,
293            evidence_binding,
294            expected_identity,
295            blocker_codes: Vec::new(),
296            ready: false,
297        };
298        report.blocker_codes =
299            report.recompute_blocker_codes(&report.projection_identity, &report.expected_identity);
300        report.ready = report.blocker_codes.is_empty();
301        report
302    }
303
304    pub fn validate_for(
305        &self,
306        projection_identity: &VectorProjectionQualificationIdentity,
307        expected_identity: &crate::ProductionQualificationIdentity,
308    ) -> Result<()> {
309        let blockers = self.recompute_blocker_codes(projection_identity, expected_identity);
310        if blockers.is_empty() {
311            Ok(())
312        } else {
313            Err(HawDBError::Storage(format!(
314                "Vector projection is not qualified for the current production release: {}",
315                blockers.join(",")
316            )))
317        }
318    }
319
320    pub fn json(&self) -> serde_json::Value {
321        let blockers =
322            self.recompute_blocker_codes(&self.projection_identity, &self.expected_identity);
323        serde_json::json!({
324            "protocol": self.protocol,
325            "recall": self.recall.json(),
326            "projection_identity": self.projection_identity.json(),
327            "evidence_binding": self.evidence_binding.json(),
328            "expected_identity": self.expected_identity.json(),
329            "minimum_document_count": MINIMUM_VECTOR_QUALIFICATION_DOCUMENT_COUNT,
330            "blocker_codes": blockers,
331            "ready": blockers.is_empty(),
332        })
333    }
334
335    fn recompute_blocker_codes(
336        &self,
337        projection_identity: &VectorProjectionQualificationIdentity,
338        expected_identity: &crate::ProductionQualificationIdentity,
339    ) -> Vec<String> {
340        let mut blockers = Vec::new();
341        if self.protocol != VECTOR_RECALL_PRODUCTION_QUALIFICATION_PROTOCOL {
342            blockers.push("protocol_mismatch".to_string());
343        }
344        let backend = match projection_identity.algorithm.as_str() {
345            "rabitq" => RABITQ_CANDIDATE_BACKEND,
346            "diskann" => DISKANN_CANDIDATE_BACKEND,
347            _ => "",
348        };
349        if !self.recall.validates_backend(backend) {
350            blockers.push("recall_validation_failed".to_string());
351        }
352        let backend_matches_identity = matches!(
353            (
354                self.recall.approximate_backend.as_str(),
355                projection_identity.algorithm.as_str()
356            ),
357            (RABITQ_CANDIDATE_BACKEND, "rabitq") | (DISKANN_CANDIDATE_BACKEND, "diskann")
358        );
359        if !backend_matches_identity {
360            blockers.push("approximate_backend_identity_mismatch".to_string());
361        }
362        if !self.projection_identity.complete() || self.projection_identity != *projection_identity
363        {
364            blockers.push("projection_identity_mismatch".to_string());
365        }
366        if projection_identity.document_count < MINIMUM_VECTOR_QUALIFICATION_DOCUMENT_COUNT {
367            blockers.push("dataset_too_small".to_string());
368        }
369        if self.expected_identity != *expected_identity {
370            blockers.push("current_release_identity_mismatch".to_string());
371        }
372        blockers.extend(production_evidence_blocker_codes(
373            &self.evidence_binding,
374            expected_identity,
375        ));
376        if projection_identity.source_graph_commit_epoch
377            != Some(expected_identity.canonical_graph_commit_epoch)
378        {
379            blockers.push("source_graph_epoch_current_release_mismatch".to_string());
380        }
381        blockers.sort();
382        blockers.dedup();
383        blockers
384    }
385}
386
387pub(super) struct VectorRecallValidationAccumulator {
388    backend: &'static str,
389    sample_candidate_count: usize,
390    requested_sample_count: usize,
391    top_k: usize,
392    candidate_limit: usize,
393    minimum_recall_per_million: u32,
394    executed_sample_count: usize,
395    exact_hit_count: usize,
396    candidate_hit_count: usize,
397    candidate_overlap_count: usize,
398    approximate_hit_count: usize,
399    overlap_count: usize,
400    fallback_count: usize,
401    approximate_backend_count: usize,
402    index_coverage_incomplete_count: usize,
403    filter_selectivity_sum: u64,
404    max_filter_selectivity_per_million: u32,
405    metadata_filter_valid: bool,
406    probe_execution_failed: bool,
407}
408
409impl VectorRecallValidationAccumulator {
410    pub(super) fn new(
411        sample_candidate_count: usize,
412        options: &VectorRecallValidationOptions,
413    ) -> Self {
414        Self {
415            backend: RABITQ_CANDIDATE_BACKEND,
416            sample_candidate_count,
417            requested_sample_count: options
418                .max_samples
419                .min(MAX_VECTOR_RECALL_VALIDATION_SAMPLES)
420                .min(sample_candidate_count),
421            top_k: options.top_k.min(MAX_VECTOR_RECALL_VALIDATION_TOP_K),
422            candidate_limit: options
423                .candidate_limit
424                .min(MAX_VECTOR_RECALL_VALIDATION_CANDIDATE_LIMIT),
425            minimum_recall_per_million: options.minimum_recall_per_million.min(PER_MILLION as u32),
426            executed_sample_count: 0,
427            exact_hit_count: 0,
428            candidate_hit_count: 0,
429            candidate_overlap_count: 0,
430            approximate_hit_count: 0,
431            overlap_count: 0,
432            fallback_count: 0,
433            approximate_backend_count: 0,
434            index_coverage_incomplete_count: 0,
435            filter_selectivity_sum: 0,
436            max_filter_selectivity_per_million: 0,
437            metadata_filter_valid: true,
438            probe_execution_failed: false,
439        }
440    }
441
442    pub(super) fn with_backend(mut self, backend: &'static str) -> Self {
443        self.backend = backend;
444        self
445    }
446
447    pub(super) fn requested_sample_count(&self) -> usize {
448        self.requested_sample_count
449    }
450
451    pub(super) fn top_k(&self) -> usize {
452        self.top_k
453    }
454
455    pub(super) fn candidate_limit(&self) -> usize {
456        self.candidate_limit.max(self.top_k)
457    }
458
459    pub(super) fn mark_metadata_filter_invalid(&mut self) {
460        self.metadata_filter_valid = false;
461    }
462
463    pub(super) fn mark_probe_execution_failed(&mut self) {
464        self.probe_execution_failed = true;
465    }
466
467    pub(super) fn record(
468        &mut self,
469        exact_ids: &[String],
470        candidate_ids: &[String],
471        approximate_ids: &[String],
472        approximate_retriever: &SearchRetrieverReport,
473    ) {
474        self.executed_sample_count = self.executed_sample_count.saturating_add(1);
475        self.exact_hit_count = self.exact_hit_count.saturating_add(exact_ids.len());
476        self.candidate_hit_count = self.candidate_hit_count.saturating_add(candidate_ids.len());
477        self.approximate_hit_count = self
478            .approximate_hit_count
479            .saturating_add(approximate_ids.len());
480        let exact_ids = exact_ids
481            .iter()
482            .map(String::as_str)
483            .collect::<BTreeSet<_>>();
484        self.candidate_overlap_count = self.candidate_overlap_count.saturating_add(
485            candidate_ids
486                .iter()
487                .filter(|id| exact_ids.contains(id.as_str()))
488                .count(),
489        );
490        self.overlap_count = self.overlap_count.saturating_add(
491            approximate_ids
492                .iter()
493                .filter(|id| exact_ids.contains(id.as_str()))
494                .count(),
495        );
496        if approximate_retriever.backend == self.backend {
497            self.approximate_backend_count = self.approximate_backend_count.saturating_add(1);
498        }
499        if !approximate_retriever.fallback_reason_codes.is_empty() {
500            self.fallback_count = self.fallback_count.saturating_add(1);
501        }
502        if !approximate_retriever.index_coverage_complete {
503            self.index_coverage_incomplete_count =
504                self.index_coverage_incomplete_count.saturating_add(1);
505        }
506        let selectivity = approximate_retriever
507            .filter_selectivity_per_million
508            .unwrap_or(0);
509        self.filter_selectivity_sum = self
510            .filter_selectivity_sum
511            .saturating_add(u64::from(selectivity));
512        self.max_filter_selectivity_per_million =
513            self.max_filter_selectivity_per_million.max(selectivity);
514    }
515
516    pub(super) fn finish(self) -> VectorRecallValidationReport {
517        let recall_at_k_per_million = ratio_per_million(self.overlap_count, self.exact_hit_count);
518        let candidate_recall_at_k_per_million =
519            ratio_per_million(self.candidate_overlap_count, self.exact_hit_count);
520        let overlap_denominator = self.executed_sample_count.saturating_mul(self.top_k);
521        let overlap_at_k_per_million = ratio_per_million(self.overlap_count, overlap_denominator);
522        let average_filter_selectivity_per_million =
523            average_per_million(self.filter_selectivity_sum, self.executed_sample_count);
524        let mut blocker_codes = BTreeSet::new();
525        if self.requested_sample_count == 0 {
526            blocker_codes.insert(VectorRecallValidationBlocker::NoSamplesRequested);
527        }
528        if self.top_k == 0 {
529            blocker_codes.insert(VectorRecallValidationBlocker::TopKZero);
530        }
531        if self.candidate_limit < self.top_k {
532            blocker_codes.insert(VectorRecallValidationBlocker::CandidateLimitBelowTopK);
533        }
534        if !self.metadata_filter_valid {
535            blocker_codes.insert(VectorRecallValidationBlocker::MetadataFilterInvalid);
536        }
537        if self.probe_execution_failed {
538            blocker_codes.insert(VectorRecallValidationBlocker::ProbeExecutionFailed);
539        }
540        if self.sample_candidate_count == 0 {
541            blocker_codes.insert(VectorRecallValidationBlocker::NoEligibleVectors);
542        }
543        if !self.probe_execution_failed {
544            if self.exact_hit_count == 0 {
545                blocker_codes.insert(VectorRecallValidationBlocker::GroundTruthEmpty);
546            }
547            if self.approximate_backend_count != self.executed_sample_count {
548                blocker_codes.insert(VectorRecallValidationBlocker::ApproximateBackendUnavailable);
549            }
550        }
551        if self.fallback_count > 0 {
552            blocker_codes.insert(VectorRecallValidationBlocker::ApproximateFallbackObserved);
553        }
554        if self.index_coverage_incomplete_count > 0 {
555            blocker_codes.insert(VectorRecallValidationBlocker::IndexCoverageIncomplete);
556        }
557        if !self.probe_execution_failed
558            && self.exact_hit_count > 0
559            && candidate_recall_at_k_per_million < self.minimum_recall_per_million
560        {
561            blocker_codes.insert(VectorRecallValidationBlocker::CandidateRecallBelowThreshold);
562        }
563        if !self.probe_execution_failed
564            && self.exact_hit_count > 0
565            && recall_at_k_per_million < self.minimum_recall_per_million
566        {
567            blocker_codes.insert(VectorRecallValidationBlocker::RecallBelowThreshold);
568        }
569        let blocker_codes = blocker_codes.into_iter().collect::<Vec<_>>();
570        VectorRecallValidationReport {
571            protocol: VECTOR_RECALL_VALIDATION_PROTOCOL.to_string(),
572            ready: blocker_codes.is_empty(),
573            approximate_backend: self.backend.to_string(),
574            sample_candidate_count: self.sample_candidate_count,
575            requested_sample_count: self.requested_sample_count,
576            executed_sample_count: self.executed_sample_count,
577            top_k: self.top_k,
578            candidate_limit: self.candidate_limit,
579            minimum_recall_per_million: self.minimum_recall_per_million,
580            exact_hit_count: self.exact_hit_count,
581            candidate_hit_count: self.candidate_hit_count,
582            candidate_overlap_count: self.candidate_overlap_count,
583            candidate_recall_at_k_per_million,
584            approximate_hit_count: self.approximate_hit_count,
585            overlap_count: self.overlap_count,
586            recall_at_k_per_million,
587            overlap_at_k_per_million,
588            fallback_count: self.fallback_count,
589            index_coverage_incomplete_count: self.index_coverage_incomplete_count,
590            average_filter_selectivity_per_million,
591            max_filter_selectivity_per_million: self.max_filter_selectivity_per_million,
592            blocker_codes,
593        }
594    }
595}
596
597pub(super) fn sample_positions(candidate_count: usize, sample_count: usize) -> Vec<usize> {
598    sample_positions_with_seed(candidate_count, sample_count, RECALL_SAMPLE_SEED)
599}
600
601fn sample_positions_with_seed(
602    candidate_count: usize,
603    sample_count: usize,
604    seed: u64,
605) -> Vec<usize> {
606    let sample_count = sample_count
607        .min(candidate_count)
608        .min(MAX_VECTOR_RECALL_VALIDATION_SAMPLES);
609    let mut selected = BTreeSet::new();
610    let mut state = seed;
611    // Floyd sampling uses O(samples) memory rather than shuffling the corpus.
612    // Sorted positions let the caller retain its single ascending document scan.
613    for upper in candidate_count - sample_count..candidate_count {
614        let position = sample_below(&mut state, upper as u64 + 1) as usize;
615        if !selected.insert(position) {
616            selected.insert(upper);
617        }
618    }
619    selected.into_iter().collect()
620}
621
622fn sample_below(state: &mut u64, bound: u64) -> u64 {
623    let threshold = bound.wrapping_neg() % bound;
624    loop {
625        *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
626        let mut value = *state;
627        value = (value ^ (value >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
628        value = (value ^ (value >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
629        value ^= value >> 31;
630        // Rejection avoids modulo bias for non-power-of-two corpus sizes.
631        if value >= threshold {
632            return value % bound;
633        }
634    }
635}
636
637fn ratio_per_million(numerator: usize, denominator: usize) -> u32 {
638    if denominator == 0 {
639        return 0;
640    }
641    u32::try_from(
642        u64::try_from(numerator)
643            .unwrap_or(u64::MAX)
644            .saturating_mul(PER_MILLION)
645            / u64::try_from(denominator).unwrap_or(u64::MAX),
646    )
647    .unwrap_or(u32::MAX)
648}
649
650fn average_per_million(sum: u64, count: usize) -> u32 {
651    if count == 0 {
652        return 0;
653    }
654    u32::try_from(sum / u64::try_from(count).unwrap_or(u64::MAX)).unwrap_or(u32::MAX)
655}
656
657#[cfg(test)]
658mod tests {
659    use super::*;
660    use crate::{
661        SearchCandidateSetReport, SearchPredicatePushdownReport, SearchRetrieverCandidateSetReport,
662    };
663
664    fn retriever(backend: &str) -> SearchRetrieverReport {
665        SearchRetrieverReport {
666            name: "vector".to_string(),
667            backend: backend.to_string(),
668            backend_selection_reason: None,
669            estimated_raw_vector_bytes: None,
670            filter_selectivity_per_million: Some(500_000),
671            available: true,
672            input_candidate_set: SearchCandidateSetReport {
673                id_space: String::new(),
674                representation: String::new(),
675                cardinality: 0,
676                exact: true,
677                snapshot_source_graph_commit_epoch: None,
678                policy_epoch: None,
679                filtered_out_count: 0,
680                metadata_filters: Default::default(),
681                metadata_predicate_pushdown: SearchPredicatePushdownReport::default(),
682            },
683            candidate_score_source: String::new(),
684            final_score_source: String::new(),
685            generated_candidate_count: 0,
686            candidate_scan_rounds: 0,
687            descriptor_pruned_count: 0,
688            scalar_filtered_count: 0,
689            residual_filtered_count: 0,
690            reranked_candidate_count: 0,
691            raw_vector_bytes_read: 0,
692            candidate_scan_kernel: None,
693            candidate_scan_worker_count: 0,
694            candidate_scan_segment_count: 0,
695            candidate_scan_scanned_segment_count: 0,
696            candidate_scan_scored_document_count: 0,
697            candidate_scan_filtered_document_count: 0,
698            candidate_scan_scanned_block_count: 0,
699            candidate_scan_skipped_block_count: 0,
700            candidate_scan_adaptive_exact_scan_count: 0,
701            candidate_scan_payload_bytes_read: 0,
702            candidate_scan_admitted_working_bytes: 0,
703            posting_bytes_read: 0,
704            candidate_postings_visited: 0,
705            candidate_blocks_skipped: 0,
706            segmented_lexical_projection_used: false,
707            index_covered_document_count: 1,
708            index_candidate_document_count: 1,
709            index_coverage_complete: true,
710            candidate_count: 0,
711            candidate_set: SearchRetrieverCandidateSetReport {
712                id_space: String::new(),
713                representation: String::new(),
714                cardinality: 0,
715                exact: true,
716                snapshot_source_graph_commit_epoch: None,
717                policy_epoch: None,
718            },
719            fallback_reason_codes: Vec::new(),
720            fallback_reasons: Vec::new(),
721            candidate_top_ids: Vec::new(),
722            top_hit_ids: Vec::new(),
723            top_candidates: Vec::new(),
724        }
725    }
726
727    fn ready_recall_report() -> VectorRecallValidationReport {
728        ready_recall_report_for(RABITQ_CANDIDATE_BACKEND)
729    }
730
731    fn ready_recall_report_for(backend: &'static str) -> VectorRecallValidationReport {
732        let options = VectorRecallValidationOptions {
733            max_samples: 1,
734            top_k: 1,
735            candidate_limit: 1,
736            minimum_recall_per_million: 1_000_000,
737            metadata_filters: Default::default(),
738        };
739        let mut accumulator =
740            VectorRecallValidationAccumulator::new(1, &options).with_backend(backend);
741        accumulator.record(
742            &["a".to_string()],
743            &["a".to_string()],
744            &["a".to_string()],
745            &retriever(backend),
746        );
747        accumulator.finish()
748    }
749
750    fn projection_identity() -> VectorProjectionQualificationIdentity {
751        VectorProjectionQualificationIdentity {
752            projection_generation: 7,
753            source_graph_commit_epoch: Some(42),
754            document_count: MINIMUM_VECTOR_QUALIFICATION_DOCUMENT_COUNT,
755            source_digest: 11,
756            payload_bytes: 4096,
757            payload_checksum: 12,
758            format_version: 1,
759            algorithm: "rabitq".to_string(),
760            bit_width: 4,
761            dimension: 3,
762            transform_seed: 17,
763            embedding_model: Some("test-embedding".to_string()),
764            embedding_version: Some("1".to_string()),
765            file_backed: true,
766        }
767    }
768
769    fn production_identity() -> crate::ProductionQualificationIdentity {
770        crate::ProductionQualificationIdentity {
771            source_revision: "test-revision".to_string(),
772            rust_toolchain: "test-toolchain".to_string(),
773            target_os: "linux".to_string(),
774            target_arch: "x86_64".to_string(),
775            enabled_features: vec!["vector-search".to_string()],
776            durable_format_version: 1,
777            schema_version: 1,
778            configuration_digest: "test-config".to_string(),
779            deployment_profile: "production-replica".to_string(),
780            dataset_fingerprint: "test-dataset".to_string(),
781            canonical_graph_commit_epoch: 42,
782            policy_version: crate::PRODUCTION_QUALIFICATION_POLICY_VERSION,
783        }
784    }
785
786    #[test]
787    fn accumulator_reports_recall_and_overlap_without_copying_ids() {
788        let options = VectorRecallValidationOptions {
789            max_samples: 2,
790            top_k: 2,
791            candidate_limit: 2,
792            minimum_recall_per_million: 500_000,
793            metadata_filters: Default::default(),
794        };
795        let mut accumulator = VectorRecallValidationAccumulator::new(2, &options);
796        accumulator.record(
797            &["a".to_string(), "b".to_string()],
798            &["a".to_string(), "x".to_string()],
799            &["a".to_string(), "x".to_string()],
800            &retriever(RABITQ_CANDIDATE_BACKEND),
801        );
802        accumulator.record(
803            &["c".to_string(), "d".to_string()],
804            &["c".to_string(), "d".to_string()],
805            &["c".to_string(), "d".to_string()],
806            &retriever(RABITQ_CANDIDATE_BACKEND),
807        );
808
809        let report = accumulator.finish();
810
811        assert!(report.ready);
812        assert!(report.validates_required_approximate_backend());
813        assert_eq!(report.candidate_hit_count, 4);
814        assert_eq!(report.candidate_overlap_count, 3);
815        assert_eq!(report.candidate_recall_at_k_per_million, 750_000);
816        assert_eq!(report.recall_at_k_per_million, 750_000);
817        assert_eq!(report.overlap_at_k_per_million, 750_000);
818        assert_eq!(report.average_filter_selectivity_per_million, 500_000);
819        let json = report.json().to_string();
820        assert!(!json.contains("\"a\""));
821        assert!(!json.contains("\"d\""));
822    }
823
824    #[test]
825    fn missing_approximate_backend_fails_closed() {
826        let options = VectorRecallValidationOptions {
827            max_samples: 1,
828            top_k: 1,
829            candidate_limit: 1,
830            minimum_recall_per_million: 1_000_000,
831            metadata_filters: Default::default(),
832        };
833        let mut accumulator = VectorRecallValidationAccumulator::new(1, &options);
834        accumulator.record(
835            &["a".to_string()],
836            &[],
837            &[],
838            &retriever("compressed_vector_projection_required"),
839        );
840
841        let report = accumulator.finish();
842
843        assert!(!report.ready);
844        assert!(!report.validates_required_approximate_backend());
845        assert!(report
846            .blocker_codes
847            .contains(&VectorRecallValidationBlocker::ApproximateBackendUnavailable));
848        assert!(report
849            .blocker_codes
850            .contains(&VectorRecallValidationBlocker::RecallBelowThreshold));
851        assert!(report
852            .blocker_codes
853            .contains(&VectorRecallValidationBlocker::CandidateRecallBelowThreshold));
854    }
855
856    #[test]
857    fn candidate_limit_below_top_k_fails_closed() {
858        let options = VectorRecallValidationOptions {
859            max_samples: 1,
860            top_k: 2,
861            candidate_limit: 1,
862            minimum_recall_per_million: 0,
863            metadata_filters: Default::default(),
864        };
865        let report = VectorRecallValidationAccumulator::new(1, &options).finish();
866
867        assert!(!report.ready);
868        assert!(report
869            .blocker_codes
870            .contains(&VectorRecallValidationBlocker::CandidateLimitBelowTopK));
871    }
872
873    #[test]
874    fn production_qualification_binds_current_release_and_projection_identity() {
875        let expected = production_identity();
876        let projection = projection_identity();
877        let report = VectorRecallProductionQualificationReport::evaluate(
878            ready_recall_report(),
879            projection.clone(),
880            crate::ProductionEvidenceBinding {
881                identity: expected.clone(),
882                generated_at_unix_seconds: 1,
883            },
884            expected.clone(),
885        );
886
887        assert!(
888            report.ready,
889            "unexpected blockers: {:?}",
890            report.blocker_codes
891        );
892        report.validate_for(&projection, &expected).unwrap();
893        assert_eq!(report.json()["ready"], true);
894
895        let mut stale_projection = projection;
896        stale_projection.projection_generation += 1;
897        let error = report
898            .validate_for(&stale_projection, &expected)
899            .unwrap_err();
900        assert!(error.to_string().contains("projection_identity_mismatch"));
901
902        let mut other_dataset = expected;
903        other_dataset.dataset_fingerprint = "other-dataset".to_string();
904        let error = report
905            .validate_for(&stale_projection, &other_dataset)
906            .unwrap_err();
907        assert!(error
908            .to_string()
909            .contains("current_release_identity_mismatch"));
910        assert!(error.to_string().contains("evidence_identity_mismatch"));
911    }
912
913    #[test]
914    fn production_qualification_cannot_substitute_compression_recall_for_a_graph() {
915        let expected = production_identity();
916        let mut projection = projection_identity();
917        projection.algorithm = "diskann".into();
918        projection.format_version = 2;
919        projection.bit_width = 0;
920        projection.transform_seed = 0;
921        for backend in [RABITQ_CANDIDATE_BACKEND, DISKANN_CANDIDATE_BACKEND] {
922            let report = VectorRecallProductionQualificationReport::evaluate(
923                ready_recall_report_for(backend),
924                projection.clone(),
925                crate::ProductionEvidenceBinding {
926                    identity: expected.clone(),
927                    generated_at_unix_seconds: 1,
928                },
929                expected.clone(),
930            );
931            if backend == DISKANN_CANDIDATE_BACKEND {
932                assert!(report.ready, "{:?}", report.blocker_codes);
933                report.validate_for(&projection, &expected).unwrap();
934            } else {
935                assert!(!report.ready);
936                assert_eq!(
937                    report.blocker_codes,
938                    vec![
939                        "approximate_backend_identity_mismatch",
940                        "recall_validation_failed"
941                    ]
942                );
943            }
944        }
945        projection.bit_width = 4;
946        assert!(!projection.complete());
947    }
948
949    #[test]
950    fn sample_positions_are_bounded_and_replayable_without_a_fixed_stride() {
951        assert_ne!(sample_positions(10, 3), vec![0, 4, 9]);
952        assert_eq!(sample_positions(2, 10), vec![0, 1]);
953        assert!(sample_positions(0, 3).is_empty());
954        assert!(sample_positions(10, 0).is_empty());
955        for count in [1, 2, 10, 31, 128, 100_000, usize::MAX] {
956            for requested in [1, 3, 32, 128, usize::MAX] {
957                for seed in 0..32 {
958                    let positions = sample_positions_with_seed(count, requested, seed);
959                    assert_eq!(
960                        positions,
961                        sample_positions_with_seed(count, requested, seed)
962                    );
963                    assert_eq!(
964                        positions.len(),
965                        count
966                            .min(requested)
967                            .min(MAX_VECTOR_RECALL_VALIDATION_SAMPLES)
968                    );
969                    assert!(positions.iter().all(|position| *position < count));
970                    assert!(positions.windows(2).all(|pair| pair[0] < pair[1]));
971                }
972            }
973        }
974    }
975
976    #[test]
977    fn seeded_sampling_reaches_every_position_without_endpoint_bias() {
978        let mut counts = [0; 31];
979        for seed in 0..4096 {
980            for position in sample_positions_with_seed(counts.len(), 3, seed) {
981                counts[position] += 1;
982            }
983        }
984        // A deterministic sanity check, not a statistical confidence interval.
985        // The old stride only ever picked 0, 15 and 30.
986        assert!(
987            counts.iter().all(|count| (300..500).contains(count)),
988            "{counts:?}"
989        );
990        let json = ready_recall_report().json();
991        assert_eq!(
992            json["sampling"]["seed"],
993            format!("{RECALL_SAMPLE_SEED:016x}")
994        );
995        assert_eq!(json["sampling"]["query_source"], "indexed_vectors");
996        assert_eq!(json["sampling"]["held_out_queries"], false);
997        assert_eq!(json["sampling"]["self_hit_excluded"], true);
998    }
999}