Skip to main content

hawdb_search/
lexical_readiness.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 crate::error::{HawDBError, Result};
16use hawdb_evidence::production_evidence_blocker_codes;
17
18pub const SEARCH_LEXICAL_QUALIFICATION_PROTOCOL: &str =
19    "hawdb-search-lexical-production-qualification";
20pub const SEARCH_LEXICAL_QUALIFICATION_PROTOCOL_VERSION: u64 = 2;
21const MINIMUM_DOCUMENT_COUNT: usize = 100_000;
22const MAX_RSS_BUDGET_PER_MILLION: u64 = 1_100_000;
23const MAX_WRITE_REGRESSION_PER_MILLION: u64 = 1_100_000;
24const MIN_SELECTIVE_P95_IMPROVEMENT_PER_MILLION: u64 = 500_000;
25
26#[derive(Debug, Clone, Default, PartialEq, Eq)]
27pub struct SearchLexicalFeasibilityCoverage {
28    pub selective_identifier: bool,
29    pub cjk_text: bool,
30    pub common_term: bool,
31    pub no_hit: bool,
32    pub metadata_filter: bool,
33    pub acl_filter: bool,
34    pub hybrid_rrf: bool,
35    pub bounded_generation_update: bool,
36    pub bounded_rabitq_serving: bool,
37    pub incremental_upsert_delete: bool,
38    pub checkpoint_reopen: bool,
39    pub corrupt_artifact: bool,
40    pub stale_manifest: bool,
41    pub mixed_foreground_background: bool,
42    pub larger_than_memory: bool,
43}
44
45impl SearchLexicalFeasibilityCoverage {
46    fn complete(&self, acl_required: bool) -> bool {
47        self.selective_identifier
48            && self.cjk_text
49            && self.common_term
50            && self.no_hit
51            && self.metadata_filter
52            && (!acl_required || self.acl_filter)
53            && self.hybrid_rrf
54            && self.bounded_generation_update
55            && self.bounded_rabitq_serving
56            && self.incremental_upsert_delete
57            && self.checkpoint_reopen
58            && self.corrupt_artifact
59            && self.stale_manifest
60            && self.mixed_foreground_background
61            && self.larger_than_memory
62    }
63
64    fn json(&self) -> serde_json::Value {
65        serde_json::json!({
66            "selective_identifier": self.selective_identifier,
67            "cjk_text": self.cjk_text,
68            "common_term": self.common_term,
69            "no_hit": self.no_hit,
70            "metadata_filter": self.metadata_filter,
71            "acl_filter": self.acl_filter,
72            "hybrid_rrf": self.hybrid_rrf,
73            "bounded_generation_update": self.bounded_generation_update,
74            "bounded_rabitq_serving": self.bounded_rabitq_serving,
75            "incremental_upsert_delete": self.incremental_upsert_delete,
76            "checkpoint_reopen": self.checkpoint_reopen,
77            "corrupt_artifact": self.corrupt_artifact,
78            "stale_manifest": self.stale_manifest,
79            "mixed_foreground_background": self.mixed_foreground_background,
80            "larger_than_memory": self.larger_than_memory,
81        })
82    }
83}
84
85#[derive(Debug, Clone, Default, PartialEq, Eq)]
86pub struct SearchLexicalFeasibilityMetrics {
87    pub canonical_dataset_bytes: u64,
88    pub storage_memory_budget_bytes: u64,
89    pub steady_resident_bytes: u64,
90    pub peak_resident_bytes: u64,
91    pub baseline_selective_text_p50_micros: u64,
92    pub baseline_selective_text_p95_micros: u64,
93    pub baseline_selective_text_p99_micros: u64,
94    pub segmented_selective_text_p50_micros: u64,
95    pub segmented_selective_text_p95_micros: u64,
96    pub segmented_selective_text_p99_micros: u64,
97    pub baseline_throughput_per_second: u64,
98    pub segmented_throughput_per_second: u64,
99    pub selective_posting_bytes_read: u64,
100    pub selective_candidate_postings_visited: u64,
101    pub selective_matching_document_count: usize,
102    pub process_memory_capabilities: hawdb_qos::ProcessMemoryCapabilities,
103    pub total_page_faults: Option<u64>,
104    pub minor_page_faults: Option<u64>,
105    pub major_page_faults: Option<u64>,
106    pub metadata_sidecar_bytes_read: u64,
107    pub vector_sidecar_bytes_read: u64,
108    pub hydration_bytes: u64,
109    pub segmented_vector_p50_micros: u64,
110    pub segmented_vector_p95_micros: u64,
111    pub segmented_vector_p99_micros: u64,
112    pub segmented_hybrid_p50_micros: u64,
113    pub segmented_hybrid_p95_micros: u64,
114    pub segmented_hybrid_p99_micros: u64,
115    pub baseline_update_p95_micros: u64,
116    pub segmented_update_p95_micros: u64,
117    pub baseline_checkpoint_p95_micros: u64,
118    pub segmented_checkpoint_p95_micros: u64,
119    pub consolidation_write_amplification_per_million: u64,
120    pub recovery_p95_micros: u64,
121}
122
123impl SearchLexicalFeasibilityMetrics {
124    fn json(&self) -> serde_json::Value {
125        serde_json::json!({
126            "canonical_dataset_bytes": self.canonical_dataset_bytes,
127            "storage_memory_budget_bytes": self.storage_memory_budget_bytes,
128            "steady_resident_bytes": self.steady_resident_bytes,
129            "peak_resident_bytes": self.peak_resident_bytes,
130            "baseline_selective_text_p50_micros": self.baseline_selective_text_p50_micros,
131            "baseline_selective_text_p95_micros": self.baseline_selective_text_p95_micros,
132            "baseline_selective_text_p99_micros": self.baseline_selective_text_p99_micros,
133            "segmented_selective_text_p50_micros": self.segmented_selective_text_p50_micros,
134            "segmented_selective_text_p95_micros": self.segmented_selective_text_p95_micros,
135            "segmented_selective_text_p99_micros": self.segmented_selective_text_p99_micros,
136            "baseline_throughput_per_second": self.baseline_throughput_per_second,
137            "segmented_throughput_per_second": self.segmented_throughput_per_second,
138            "selective_posting_bytes_read": self.selective_posting_bytes_read,
139            "selective_candidate_postings_visited": self.selective_candidate_postings_visited,
140            "selective_matching_document_count": self.selective_matching_document_count,
141            "process_memory_capabilities": {
142                "resident_memory": self.process_memory_capabilities.resident_memory,
143                "total_page_faults": self.process_memory_capabilities.total_page_faults,
144                "split_page_faults": self.process_memory_capabilities.split_page_faults,
145            },
146            "total_page_faults": self.total_page_faults,
147            "minor_page_faults": self.minor_page_faults,
148            "major_page_faults": self.major_page_faults,
149            "metadata_sidecar_bytes_read": self.metadata_sidecar_bytes_read,
150            "vector_sidecar_bytes_read": self.vector_sidecar_bytes_read,
151            "hydration_bytes": self.hydration_bytes,
152            "segmented_vector_p50_micros": self.segmented_vector_p50_micros,
153            "segmented_vector_p95_micros": self.segmented_vector_p95_micros,
154            "segmented_vector_p99_micros": self.segmented_vector_p99_micros,
155            "segmented_hybrid_p50_micros": self.segmented_hybrid_p50_micros,
156            "segmented_hybrid_p95_micros": self.segmented_hybrid_p95_micros,
157            "segmented_hybrid_p99_micros": self.segmented_hybrid_p99_micros,
158            "baseline_update_p95_micros": self.baseline_update_p95_micros,
159            "segmented_update_p95_micros": self.segmented_update_p95_micros,
160            "baseline_checkpoint_p95_micros": self.baseline_checkpoint_p95_micros,
161            "segmented_checkpoint_p95_micros": self.segmented_checkpoint_p95_micros,
162            "consolidation_write_amplification_per_million": self.consolidation_write_amplification_per_million,
163            "recovery_p95_micros": self.recovery_p95_micros,
164        })
165    }
166}
167
168#[derive(Debug, Clone, Default, PartialEq, Eq)]
169pub struct SearchProjectionQualificationIdentity {
170    pub projection_generation: u64,
171    pub source_graph_commit_epoch: Option<u64>,
172    pub document_count: usize,
173    pub documents_digest: u64,
174    pub analyzer_digest: u64,
175    pub embedding_model: Option<String>,
176    pub embedding_version: Option<String>,
177    pub embedding_dimension: Option<usize>,
178}
179
180impl SearchProjectionQualificationIdentity {
181    pub fn json(&self) -> serde_json::Value {
182        serde_json::json!({
183            "projection_generation": self.projection_generation,
184            "source_graph_commit_epoch": self.source_graph_commit_epoch,
185            "document_count": self.document_count,
186            "documents_digest": self.documents_digest,
187            "analyzer_digest": self.analyzer_digest,
188            "embedding_model": self.embedding_model,
189            "embedding_version": self.embedding_version,
190            "embedding_dimension": self.embedding_dimension,
191        })
192    }
193
194    fn complete(&self) -> bool {
195        self.projection_generation > 0
196            && self.source_graph_commit_epoch.is_some()
197            && self.document_count > 0
198            && self.documents_digest > 0
199            && self.analyzer_digest > 0
200            && self
201                .embedding_model
202                .as_deref()
203                .is_some_and(|value| !value.trim().is_empty())
204            && self
205                .embedding_version
206                .as_deref()
207                .is_some_and(|value| !value.trim().is_empty())
208            && self
209                .embedding_dimension
210                .is_some_and(|dimension| dimension > 0)
211    }
212}
213
214#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
215pub struct SearchTopKScoreParity {
216    pub text: bool,
217    pub vector: bool,
218    pub hybrid: bool,
219}
220
221impl SearchTopKScoreParity {
222    fn complete(self) -> bool {
223        self.text && self.vector && self.hybrid
224    }
225
226    fn json(self) -> serde_json::Value {
227        serde_json::json!({
228            "text": self.text,
229            "vector": self.vector,
230            "hybrid": self.hybrid,
231        })
232    }
233}
234
235#[derive(Debug, Clone, PartialEq, Eq)]
236pub struct SearchLexicalProductionQualificationReport {
237    pub protocol: String,
238    pub protocol_version: u64,
239    pub projection_generation: u64,
240    pub source_graph_commit_epoch: Option<u64>,
241    pub document_count: usize,
242    pub projection_identity: SearchProjectionQualificationIdentity,
243    pub evidence_binding: Option<crate::ProductionEvidenceBinding>,
244    pub expected_identity: Option<crate::ProductionQualificationIdentity>,
245    pub topk_score_parity: SearchTopKScoreParity,
246    pub exact_topk_score_parity: bool,
247    pub coverage: SearchLexicalFeasibilityCoverage,
248    pub metrics: SearchLexicalFeasibilityMetrics,
249    pub blocker_codes: Vec<String>,
250    pub ready: bool,
251}
252
253impl SearchLexicalProductionQualificationReport {
254    pub fn evaluate(
255        projection_generation: u64,
256        source_graph_commit_epoch: Option<u64>,
257        document_count: usize,
258        exact_topk_score_parity: bool,
259        coverage: SearchLexicalFeasibilityCoverage,
260        metrics: SearchLexicalFeasibilityMetrics,
261    ) -> Self {
262        let projection_identity = SearchProjectionQualificationIdentity {
263            projection_generation,
264            source_graph_commit_epoch,
265            document_count,
266            ..SearchProjectionQualificationIdentity::default()
267        };
268        Self::evaluate_internal(
269            projection_identity,
270            None,
271            None,
272            SearchTopKScoreParity {
273                text: exact_topk_score_parity,
274                vector: exact_topk_score_parity,
275                hybrid: exact_topk_score_parity,
276            },
277            coverage,
278            metrics,
279        )
280    }
281
282    pub fn evaluate_for_production(
283        projection_identity: SearchProjectionQualificationIdentity,
284        evidence_binding: crate::ProductionEvidenceBinding,
285        expected_identity: crate::ProductionQualificationIdentity,
286        topk_score_parity: SearchTopKScoreParity,
287        coverage: SearchLexicalFeasibilityCoverage,
288        metrics: SearchLexicalFeasibilityMetrics,
289    ) -> Self {
290        Self::evaluate_internal(
291            projection_identity,
292            Some(evidence_binding),
293            Some(expected_identity),
294            topk_score_parity,
295            coverage,
296            metrics,
297        )
298    }
299
300    fn evaluate_internal(
301        projection_identity: SearchProjectionQualificationIdentity,
302        evidence_binding: Option<crate::ProductionEvidenceBinding>,
303        expected_identity: Option<crate::ProductionQualificationIdentity>,
304        topk_score_parity: SearchTopKScoreParity,
305        coverage: SearchLexicalFeasibilityCoverage,
306        metrics: SearchLexicalFeasibilityMetrics,
307    ) -> Self {
308        let projection_generation = projection_identity.projection_generation;
309        let source_graph_commit_epoch = projection_identity.source_graph_commit_epoch;
310        let document_count = projection_identity.document_count;
311        let mut report = Self {
312            protocol: SEARCH_LEXICAL_QUALIFICATION_PROTOCOL.to_string(),
313            protocol_version: SEARCH_LEXICAL_QUALIFICATION_PROTOCOL_VERSION,
314            projection_generation,
315            source_graph_commit_epoch,
316            document_count,
317            projection_identity: projection_identity.clone(),
318            evidence_binding,
319            expected_identity,
320            topk_score_parity,
321            exact_topk_score_parity: topk_score_parity.complete(),
322            coverage,
323            metrics,
324            blocker_codes: Vec::new(),
325            ready: false,
326        };
327        report.blocker_codes = report.recompute_blocker_codes(&projection_identity);
328        report.ready = report.blocker_codes.is_empty();
329        report
330    }
331
332    pub fn validate_for_projection(
333        &self,
334        projection_identity: &SearchProjectionQualificationIdentity,
335    ) -> Result<()> {
336        let blockers = self.recompute_blocker_codes(projection_identity);
337        if blockers.is_empty() {
338            Ok(())
339        } else {
340            Err(HawDBError::Storage(format!(
341                "segmented lexical projection is not qualified for production: {}",
342                blockers.join(",")
343            )))
344        }
345    }
346
347    /// Recomputes the blockers for `projection_identity` under
348    /// `expected_identity`. A non-empty set is a typed, non-poisoning
349    /// [`HawDBError::SearchProductionQualificationRefused`]: the report does
350    /// not qualify this projection for this release, so qualify it again.
351    pub fn validate_for_projection_and_release(
352        &self,
353        projection_identity: &SearchProjectionQualificationIdentity,
354        expected_identity: &crate::ProductionQualificationIdentity,
355    ) -> Result<()> {
356        let blockers =
357            self.recompute_blocker_codes_for_release(projection_identity, expected_identity);
358        if blockers.is_empty() {
359            Ok(())
360        } else {
361            // Every blocker compares the supplied report with identities the
362            // projection already proved at open; none is damage (#1932).
363            Err(HawDBError::SearchProductionQualificationRefused {
364                blocker_codes: blockers,
365            })
366        }
367    }
368
369    pub fn json(&self) -> serde_json::Value {
370        let recomputed_blockers = self.recompute_blocker_codes(&self.projection_identity);
371        serde_json::json!({
372            "protocol": self.protocol,
373            "protocol_version": self.protocol_version,
374            "projection_generation": self.projection_generation,
375            "source_graph_commit_epoch": self.source_graph_commit_epoch,
376            "document_count": self.document_count,
377            "projection_identity": self.projection_identity.json(),
378            "evidence_binding": self.evidence_binding.as_ref().map(crate::ProductionEvidenceBinding::json),
379            "expected_identity": self.expected_identity.as_ref().map(crate::ProductionQualificationIdentity::json),
380            "topk_score_parity": self.topk_score_parity.json(),
381            "exact_topk_score_parity": self.exact_topk_score_parity,
382            "coverage": self.coverage.json(),
383            "metrics": self.metrics.json(),
384            "thresholds": {
385                "minimum_document_count": MINIMUM_DOCUMENT_COUNT,
386                "minimum_selective_p95_improvement_per_million": MIN_SELECTIVE_P95_IMPROVEMENT_PER_MILLION,
387                "maximum_rss_budget_per_million": MAX_RSS_BUDGET_PER_MILLION,
388                "maximum_write_regression_per_million": MAX_WRITE_REGRESSION_PER_MILLION,
389            },
390            "blocker_codes": recomputed_blockers,
391            "ready": recomputed_blockers.is_empty(),
392        })
393    }
394
395    fn recompute_blocker_codes(
396        &self,
397        projection_identity: &SearchProjectionQualificationIdentity,
398    ) -> Vec<String> {
399        let mut blockers = Vec::new();
400        let document_count = projection_identity.document_count;
401        if self.protocol != SEARCH_LEXICAL_QUALIFICATION_PROTOCOL
402            || self.protocol_version != SEARCH_LEXICAL_QUALIFICATION_PROTOCOL_VERSION
403        {
404            blockers.push("protocol_mismatch".to_string());
405        }
406        if !self.projection_identity.complete()
407            || self.projection_identity != *projection_identity
408            || self.projection_generation != projection_identity.projection_generation
409            || self.source_graph_commit_epoch != projection_identity.source_graph_commit_epoch
410            || self.document_count != projection_identity.document_count
411        {
412            blockers.push("projection_identity_mismatch".to_string());
413        }
414        match (&self.evidence_binding, &self.expected_identity) {
415            (Some(binding), Some(expected)) => {
416                blockers.extend(production_evidence_blocker_codes(binding, expected));
417                if self.projection_identity.source_graph_commit_epoch
418                    != Some(expected.canonical_graph_commit_epoch)
419                {
420                    blockers.push("source_graph_epoch_release_identity_mismatch".to_string());
421                }
422            }
423            (None, _) => blockers.push("production_evidence_binding_missing".to_string()),
424            (_, None) => blockers.push("production_expected_identity_missing".to_string()),
425        }
426        if document_count < MINIMUM_DOCUMENT_COUNT {
427            blockers.push("dataset_too_small".to_string());
428        }
429        if !self.exact_topk_score_parity || !self.topk_score_parity.complete() {
430            blockers.push("topk_score_parity_failed".to_string());
431        }
432        let acl_required = self.expected_identity.as_ref().is_some_and(|identity| {
433            identity
434                .enabled_features
435                .iter()
436                .any(|feature| feature == "acl")
437        });
438        if !self.coverage.complete(acl_required) {
439            blockers.push("workload_coverage_incomplete".to_string());
440        }
441        if self.metrics.storage_memory_budget_bytes == 0
442            || self.metrics.canonical_dataset_bytes <= self.metrics.storage_memory_budget_bytes
443        {
444            blockers.push("larger_than_memory_not_proven".to_string());
445        }
446        if !ratio_within(
447            self.metrics.steady_resident_bytes,
448            self.metrics.storage_memory_budget_bytes,
449            MAX_RSS_BUDGET_PER_MILLION,
450        ) || !ratio_within(
451            self.metrics.peak_resident_bytes,
452            self.metrics.storage_memory_budget_bytes,
453            MAX_RSS_BUDGET_PER_MILLION,
454        ) {
455            blockers.push("resident_memory_budget_exceeded".to_string());
456        }
457        if self.metrics.baseline_selective_text_p95_micros == 0
458            || self.metrics.segmented_selective_text_p95_micros == 0
459            || !ratio_within(
460                self.metrics.segmented_selective_text_p95_micros,
461                self.metrics.baseline_selective_text_p95_micros,
462                MIN_SELECTIVE_P95_IMPROVEMENT_PER_MILLION,
463            )
464        {
465            blockers.push("selective_text_p95_improvement_insufficient".to_string());
466        }
467        if self.metrics.selective_posting_bytes_read == 0
468            || self.metrics.selective_candidate_postings_visited == 0
469            || self.metrics.selective_candidate_postings_visited >= document_count as u64
470            || self.metrics.selective_matching_document_count >= document_count
471        {
472            blockers.push("selective_work_not_posting_proportional".to_string());
473        }
474        if !self.metrics.process_memory_capabilities.resident_memory
475            || !self.metrics.process_memory_capabilities.total_page_faults
476            || self.metrics.total_page_faults.is_none()
477            || (self.metrics.process_memory_capabilities.split_page_faults
478                && (self.metrics.minor_page_faults.is_none()
479                    || self.metrics.major_page_faults.is_none()))
480            || (!self.metrics.process_memory_capabilities.split_page_faults
481                && (self.metrics.minor_page_faults.is_some()
482                    || self.metrics.major_page_faults.is_some()))
483        {
484            blockers.push("process_memory_metrics_invalid".to_string());
485        }
486        if self.metrics.metadata_sidecar_bytes_read == 0
487            || self.metrics.vector_sidecar_bytes_read == 0
488            || self.metrics.hydration_bytes == 0
489        {
490            blockers.push("out_of_core_io_metrics_missing".to_string());
491        }
492        if [
493            self.metrics.segmented_vector_p50_micros,
494            self.metrics.segmented_vector_p95_micros,
495            self.metrics.segmented_vector_p99_micros,
496            self.metrics.segmented_hybrid_p50_micros,
497            self.metrics.segmented_hybrid_p95_micros,
498            self.metrics.segmented_hybrid_p99_micros,
499        ]
500        .contains(&0)
501        {
502            blockers.push("vector_hybrid_latency_metrics_missing".to_string());
503        }
504        if !regression_within(
505            self.metrics.segmented_update_p95_micros,
506            self.metrics.baseline_update_p95_micros,
507        ) {
508            blockers.push("update_p95_regression_exceeded".to_string());
509        }
510        if !regression_within(
511            self.metrics.segmented_checkpoint_p95_micros,
512            self.metrics.baseline_checkpoint_p95_micros,
513        ) {
514            blockers.push("checkpoint_p95_regression_exceeded".to_string());
515        }
516        blockers.sort();
517        blockers.dedup();
518        blockers
519    }
520
521    fn recompute_blocker_codes_for_release(
522        &self,
523        projection_identity: &SearchProjectionQualificationIdentity,
524        expected_identity: &crate::ProductionQualificationIdentity,
525    ) -> Vec<String> {
526        let mut blockers = self.recompute_blocker_codes(projection_identity);
527        if self.expected_identity.as_ref() != Some(expected_identity) {
528            blockers.push("current_release_identity_mismatch".to_string());
529        }
530        match &self.evidence_binding {
531            Some(binding) => blockers.extend(production_evidence_blocker_codes(
532                binding,
533                expected_identity,
534            )),
535            None => blockers.push("production_evidence_binding_missing".to_string()),
536        }
537        if projection_identity.source_graph_commit_epoch
538            != Some(expected_identity.canonical_graph_commit_epoch)
539        {
540            blockers.push("source_graph_epoch_current_release_mismatch".to_string());
541        }
542        blockers.sort();
543        blockers.dedup();
544        blockers
545    }
546}
547
548fn regression_within(measured: u64, baseline: u64) -> bool {
549    baseline > 0
550        && measured > 0
551        && ratio_within(measured, baseline, MAX_WRITE_REGRESSION_PER_MILLION)
552}
553
554fn ratio_within(measured: u64, baseline: u64, limit_per_million: u64) -> bool {
555    baseline > 0
556        && u128::from(measured).saturating_mul(1_000_000)
557            <= u128::from(baseline).saturating_mul(u128::from(limit_per_million))
558}
559
560#[cfg(test)]
561mod tests {
562    use super::*;
563
564    fn complete_coverage() -> SearchLexicalFeasibilityCoverage {
565        SearchLexicalFeasibilityCoverage {
566            selective_identifier: true,
567            cjk_text: true,
568            common_term: true,
569            no_hit: true,
570            metadata_filter: true,
571            acl_filter: true,
572            hybrid_rrf: true,
573            bounded_generation_update: true,
574            bounded_rabitq_serving: true,
575            incremental_upsert_delete: true,
576            checkpoint_reopen: true,
577            corrupt_artifact: true,
578            stale_manifest: true,
579            mixed_foreground_background: true,
580            larger_than_memory: true,
581        }
582    }
583
584    fn passing_metrics() -> SearchLexicalFeasibilityMetrics {
585        SearchLexicalFeasibilityMetrics {
586            canonical_dataset_bytes: 2_000_000_000,
587            storage_memory_budget_bytes: 1_000_000_000,
588            steady_resident_bytes: 900_000_000,
589            peak_resident_bytes: 1_050_000_000,
590            baseline_selective_text_p50_micros: 100,
591            baseline_selective_text_p95_micros: 200,
592            baseline_selective_text_p99_micros: 300,
593            segmented_selective_text_p50_micros: 40,
594            segmented_selective_text_p95_micros: 100,
595            segmented_selective_text_p99_micros: 140,
596            baseline_throughput_per_second: 1_000,
597            segmented_throughput_per_second: 2_000,
598            selective_posting_bytes_read: 4096,
599            selective_candidate_postings_visited: 32,
600            selective_matching_document_count: 16,
601            process_memory_capabilities: hawdb_qos::ProcessMemoryCapabilities {
602                resident_memory: true,
603                total_page_faults: true,
604                split_page_faults: true,
605            },
606            total_page_faults: Some(20),
607            minor_page_faults: Some(20),
608            major_page_faults: Some(0),
609            metadata_sidecar_bytes_read: 2048,
610            vector_sidecar_bytes_read: 4096,
611            hydration_bytes: 1024,
612            segmented_vector_p50_micros: 50,
613            segmented_vector_p95_micros: 110,
614            segmented_vector_p99_micros: 160,
615            segmented_hybrid_p50_micros: 60,
616            segmented_hybrid_p95_micros: 120,
617            segmented_hybrid_p99_micros: 180,
618            baseline_update_p95_micros: 100,
619            segmented_update_p95_micros: 110,
620            baseline_checkpoint_p95_micros: 1_000,
621            segmented_checkpoint_p95_micros: 1_100,
622            consolidation_write_amplification_per_million: 1_100_000,
623            recovery_p95_micros: 20_000,
624        }
625    }
626
627    fn projection_identity(
628        projection_generation: u64,
629        source_graph_commit_epoch: Option<u64>,
630        document_count: usize,
631    ) -> SearchProjectionQualificationIdentity {
632        SearchProjectionQualificationIdentity {
633            projection_generation,
634            source_graph_commit_epoch,
635            document_count,
636            documents_digest: 11,
637            analyzer_digest: 12,
638            embedding_model: Some("test-embedding".to_string()),
639            embedding_version: Some("1".to_string()),
640            embedding_dimension: Some(3),
641        }
642    }
643
644    fn production_identity() -> crate::ProductionQualificationIdentity {
645        crate::ProductionQualificationIdentity {
646            source_revision: "test-revision".to_string(),
647            rust_toolchain: "test-toolchain".to_string(),
648            target_os: "linux".to_string(),
649            target_arch: "x86_64".to_string(),
650            enabled_features: vec!["full-text-search".to_string(), "vector-search".to_string()],
651            durable_format_version: 1,
652            schema_version: 1,
653            configuration_digest: "test-config".to_string(),
654            deployment_profile: "production-replica".to_string(),
655            dataset_fingerprint: "test-dataset".to_string(),
656            canonical_graph_commit_epoch: 42,
657            policy_version: crate::PRODUCTION_QUALIFICATION_POLICY_VERSION,
658        }
659    }
660
661    fn complete_parity() -> SearchTopKScoreParity {
662        SearchTopKScoreParity {
663            text: true,
664            vector: true,
665            hybrid: true,
666        }
667    }
668
669    #[test]
670    fn accepts_complete_generation_bound_production_evidence() {
671        let identity = production_identity();
672        let projection_identity = projection_identity(7, Some(42), 100_000);
673        let report = SearchLexicalProductionQualificationReport::evaluate_for_production(
674            projection_identity.clone(),
675            crate::ProductionEvidenceBinding {
676                identity: identity.clone(),
677                generated_at_unix_seconds: 1,
678            },
679            identity,
680            complete_parity(),
681            complete_coverage(),
682            passing_metrics(),
683        );
684
685        assert!(
686            report.ready,
687            "unexpected blockers: {:?}",
688            report.blocker_codes
689        );
690        report
691            .validate_for_projection(&projection_identity)
692            .unwrap();
693        report
694            .validate_for_projection_and_release(&projection_identity, &production_identity())
695            .unwrap();
696        assert_eq!(report.json()["ready"], true);
697    }
698
699    #[test]
700    fn requires_acl_coverage_only_when_acl_is_in_the_release_feature_set() {
701        let mut coverage = complete_coverage();
702        coverage.acl_filter = false;
703        let identity = production_identity();
704        let without_acl = SearchLexicalProductionQualificationReport::evaluate_for_production(
705            projection_identity(7, Some(42), 100_000),
706            crate::ProductionEvidenceBinding {
707                identity: identity.clone(),
708                generated_at_unix_seconds: 1,
709            },
710            identity,
711            complete_parity(),
712            coverage.clone(),
713            passing_metrics(),
714        );
715        assert!(without_acl.ready);
716
717        let mut identity = production_identity();
718        identity.enabled_features.push("acl".to_string());
719        let with_acl = SearchLexicalProductionQualificationReport::evaluate_for_production(
720            projection_identity(7, Some(42), 100_000),
721            crate::ProductionEvidenceBinding {
722                identity: identity.clone(),
723                generated_at_unix_seconds: 1,
724            },
725            identity,
726            complete_parity(),
727            coverage,
728            passing_metrics(),
729        );
730        assert!(with_acl
731            .blocker_codes
732            .contains(&"workload_coverage_incomplete".to_string()));
733    }
734
735    #[test]
736    fn rejects_evidence_bound_to_a_different_current_dataset() {
737        let identity = production_identity();
738        let projection_identity = projection_identity(7, Some(42), 100_000);
739        let report = SearchLexicalProductionQualificationReport::evaluate_for_production(
740            projection_identity.clone(),
741            crate::ProductionEvidenceBinding {
742                identity: identity.clone(),
743                generated_at_unix_seconds: 1,
744            },
745            identity,
746            complete_parity(),
747            complete_coverage(),
748            passing_metrics(),
749        );
750        let mut current_identity = production_identity();
751        current_identity.dataset_fingerprint = "different-dataset".to_string();
752
753        let error = report
754            .validate_for_projection_and_release(&projection_identity, &current_identity)
755            .unwrap_err();
756        assert!(error
757            .to_string()
758            .contains("current_release_identity_mismatch"));
759        assert!(error.to_string().contains("evidence_identity_mismatch"));
760    }
761
762    /// A projection and graph that moved on after qualification are a typed
763    /// state refusal that keeps its message, never a storage failure (#1932).
764    #[test]
765    fn stale_release_qualification_is_a_typed_refusal_not_storage() {
766        let identity = production_identity();
767        let report = SearchLexicalProductionQualificationReport::evaluate_for_production(
768            projection_identity(7, Some(42), 100_000),
769            crate::ProductionEvidenceBinding {
770                identity: identity.clone(),
771                generated_at_unix_seconds: 1,
772            },
773            identity,
774            complete_parity(),
775            complete_coverage(),
776            passing_metrics(),
777        );
778        assert!(report.ready);
779        let mut advanced_release = production_identity();
780        advanced_release.canonical_graph_commit_epoch = 43;
781
782        let error = report
783            .validate_for_projection_and_release(
784                &projection_identity(8, Some(43), 100_000),
785                &advanced_release,
786            )
787            .unwrap_err();
788        assert_eq!(
789            error,
790            HawDBError::SearchProductionQualificationRefused {
791                blocker_codes: vec![
792                    "current_release_identity_mismatch".to_string(),
793                    "evidence_identity_mismatch".to_string(),
794                    "projection_identity_mismatch".to_string(),
795                ],
796            }
797        );
798        assert_eq!(
799            error.to_string(),
800            "storage error: segmented lexical projection is not qualified for the current production release: current_release_identity_mismatch,evidence_identity_mismatch,projection_identity_mismatch"
801        );
802    }
803
804    #[test]
805    fn rejects_forged_ready_flag_and_stale_projection_identity() {
806        let mut metrics = passing_metrics();
807        metrics.segmented_selective_text_p95_micros = 101;
808        let identity = production_identity();
809        let mut report = SearchLexicalProductionQualificationReport::evaluate_for_production(
810            projection_identity(7, Some(42), 100_000),
811            crate::ProductionEvidenceBinding {
812                identity: identity.clone(),
813                generated_at_unix_seconds: 1,
814            },
815            identity,
816            complete_parity(),
817            complete_coverage(),
818            metrics,
819        );
820        report.ready = true;
821        report.blocker_codes.clear();
822
823        let error = report
824            .validate_for_projection(&projection_identity(8, Some(43), 100_000))
825            .unwrap_err();
826        assert!(error.to_string().contains("projection_identity_mismatch"));
827        assert!(error
828            .to_string()
829            .contains("selective_text_p95_improvement_insufficient"));
830        assert_eq!(report.json()["ready"], false);
831    }
832
833    #[test]
834    fn rejects_small_or_memory_resident_benchmark_fixtures() {
835        let mut metrics = passing_metrics();
836        metrics.canonical_dataset_bytes = metrics.storage_memory_budget_bytes;
837        let report = SearchLexicalProductionQualificationReport::evaluate(
838            1,
839            None,
840            99_999,
841            true,
842            complete_coverage(),
843            metrics,
844        );
845
846        assert!(!report.ready);
847        assert!(report
848            .blocker_codes
849            .contains(&"dataset_too_small".to_string()));
850        assert!(report
851            .blocker_codes
852            .contains(&"larger_than_memory_not_proven".to_string()));
853    }
854}