Skip to main content

hawdb_search/
lib.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
15mod projection_scan;
16pub use projection_scan::{SearchProjectionScanBudget, SearchProjectionScanReport};
17mod projection_id_page;
18pub use projection_id_page::{
19    SearchProjectionIdBatch, SearchProjectionIdPage, SearchProjectionPageGeneration,
20};
21#[doc(hidden)]
22pub mod candidate_evidence;
23#[doc(hidden)]
24pub mod candidate_evidence_cli;
25use hawdb_core::{
26    Catalog, HawDBError, ResourceBudgetError, ResourceBudgetKind, ResourceBudgetScope, Result,
27    RuntimeCapabilities, RuntimeCapability, Value,
28};
29pub use hawdb_core::{RuntimeCancellationToken, RuntimeTaskContext};
30pub use hawdb_evidence::{
31    ProductionEvidenceBinding, ProductionQualificationIdentity,
32    PRODUCTION_QUALIFICATION_POLICY_VERSION,
33};
34use hawdb_integrity::checksum_u64;
35use hawdb_optimizer_predicate::{
36    normalize_search_enum_value, search_field_is_enum_like, SearchPredicate, SearchPredicateOp,
37    SearchPredicateSet, SearchScalarValue,
38};
39use hawdb_optimizer_vector::{
40    select_adaptive_vector_backend, AdaptiveVectorBackend, AdaptiveVectorBackendDecision,
41    AdaptiveVectorBackendInput, AdaptiveVectorBackendPolicy, VectorCompressionPreference,
42};
43use hawdb_plan_core::{VectorBackendSelectionReason, VectorCandidateSource};
44use hawdb_qos::{
45    BackgroundWorkHint, BackgroundWorkPlan, LocalQosPolicy, LocalQosScheduler, LocalQosState,
46    WorkClass, WorkRequest,
47};
48use hawdb_storage::file_io::{self as fs, File};
49use hawdb_storage::{
50    durability::durable_replace_file,
51    scan::{
52        EnumDictionaryStats, FieldSummary, RangeBound, ScanPredicate, SegmentPruner,
53        SegmentReadRange, SegmentSummary,
54    },
55};
56use hawdb_storage::{NodeId, NodeRecord};
57use hawdb_telemetry::{KernelTelemetry, KernelTelemetryOperation, TelemetrySink};
58use std::borrow::Cow;
59use std::cmp::Ordering;
60use std::collections::{BTreeMap, BTreeSet, HashMap};
61use std::io::{Cursor, Read, Write};
62use std::num::NonZeroUsize;
63use std::path::{Path, PathBuf};
64use std::str::FromStr;
65use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
66use std::sync::{Arc, Mutex};
67
68mod analyzer_lexicon;
69mod analyzer_memory;
70mod analyzer_stream;
71mod analyzer_workspace;
72mod bounded_file;
73mod build_control;
74mod build_memory;
75mod build_term;
76#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
77mod cjk_dictionary;
78mod cjk_tokenizer;
79#[cfg(test)]
80mod compression_tests;
81/// Internal assembly support for the embedded database facade.
82#[doc(hidden)]
83pub mod consumer;
84#[cfg(feature = "vector-search")]
85mod diskann_identity;
86#[cfg(test)]
87mod document_decoding_tests;
88mod document_encoding;
89mod document_set_digest;
90pub use document_set_digest::SearchDocumentSetDigest;
91mod generation_cleanup;
92mod identifier;
93#[doc(hidden)]
94pub mod knowledge_retrieval_pipeline;
95mod lexical_projection;
96#[cfg(test)]
97mod resident_checkpoint_atomicity_tests;
98pub use lexical_projection::LexicalQueryTermPolicy;
99mod lexical_readiness;
100#[cfg(all(test, feature = "full-text-search"))]
101mod lexical_snapshot_test_gate;
102mod lexical_source_policy;
103mod lexical_term_policy;
104mod out_of_core;
105mod projection_catch_up;
106mod projection_delta_contracts;
107#[doc(hidden)]
108pub mod projection_evidence;
109#[doc(hidden)]
110pub mod projection_evidence_cli;
111pub mod projection_ownership;
112mod query_control;
113mod query_matches;
114mod resident_bm25;
115#[cfg(feature = "vector-search")]
116mod resident_diskann;
117mod resident_text_seed;
118
119#[doc(hidden)]
120pub mod projection_consumer;
121#[cfg(feature = "vector-search")]
122pub mod rabitq_projection;
123mod range_io;
124mod resident_documents;
125mod resident_snapshot;
126use resident_documents::{DocumentView, ResidentDocuments};
127pub use resident_snapshot::{
128    SearchIndexPublishedSnapshot, SearchIndexReadLease, SearchIndexReadSnapshot,
129};
130mod recall_validation;
131mod snapshot_writer;
132#[cfg(test)]
133#[path = "../tests/support/live_allocation.rs"]
134mod test_allocation;
135mod vector_execution;
136mod vector_index;
137mod vector_scoring;
138pub use vector_index::{
139    VectorIndexHit, VectorIndexQuery, VectorIndexQueryReport, VectorIndexRetainedOutput,
140};
141pub use vector_scoring::SearchVectorScoring;
142
143use document_encoding::encode_search_document_line;
144
145mod error {
146    pub use hawdb_core::{HawDBError, Result};
147}
148
149/// Storage-neutral source for graph-derived search projection maintenance.
150///
151/// The search kernel owns projection semantics; embedding code owns graph
152/// layout, scan, recovery, and relationship access. This is deliberately
153/// analogous to `hawdb_analytics::ProjectionSource`.
154pub trait SearchProjectionSource {
155    fn source_graph_commit_epoch(&self) -> u64;
156
157    fn estimated_projection_node_count(&self) -> usize;
158
159    fn visit_projection_nodes(
160        &self,
161        visitor: &mut dyn FnMut(NodeRecord) -> Result<()>,
162    ) -> Result<()>;
163
164    fn projection_business_labels(
165        &self,
166        catalog: &Catalog,
167        node: &NodeRecord,
168    ) -> Result<Vec<String>>;
169
170    /// Collects sorted, deduplicated business labels keyed by graph node.
171    ///
172    /// Sources with bulk relationship access should override this method so a
173    /// rebuild does not repeat the same relationship scan for every node.
174    fn projection_business_labels_by_node(
175        &self,
176        catalog: &Catalog,
177    ) -> Result<HashMap<NodeId, Vec<String>>> {
178        let mut labels_by_node = HashMap::new();
179        self.visit_projection_nodes(&mut |node| {
180            if projection_row_from_node(catalog, &node).is_none() {
181                return Ok(());
182            }
183            let mut labels = self.projection_business_labels(catalog, &node)?;
184            labels.sort();
185            labels.dedup();
186            if !labels.is_empty() {
187                labels_by_node.insert(node.id, labels);
188            }
189            Ok(())
190        })?;
191        Ok(labels_by_node)
192    }
193}
194
195pub const fn compiled_runtime_capabilities() -> RuntimeCapabilities {
196    RuntimeCapabilities {
197        access_control: cfg!(feature = "acl"),
198        full_text_search: cfg!(feature = "full-text-search"),
199        search_projection_publication: cfg!(any(unix, windows)),
200        vector_search: cfg!(feature = "vector-search"),
201        graph_analytics: cfg!(feature = "graph-analytics"),
202        background_maintenance: cfg!(feature = "background-maintenance"),
203    }
204}
205
206mod compiled_capabilities {
207    use hawdb_core::RuntimeCapabilities;
208
209    pub(crate) const fn effective_runtime_capabilities(
210        requested: RuntimeCapabilities,
211    ) -> RuntimeCapabilities {
212        requested.intersection(super::compiled_runtime_capabilities())
213    }
214}
215
216#[cfg(test)]
217mod fallible_wrapper_proof;
218use analyzer_lexicon::{CORE_SEMANTIC_ALIAS_RULES, NOWLEDGE_MEMORY_SEMANTIC_ALIAS_RULES};
219use analyzer_stream::{document_token_fields, visit_token_list, TokenOccurrence};
220#[cfg(test)]
221use cjk_tokenizer::is_cjk_search_char;
222use generation_cleanup::SearchProjectionCleanupState;
223pub use generation_cleanup::{
224    SearchProjectionCleanupOptions, SearchProjectionCleanupOutcome, SearchProjectionCleanupReport,
225    SEARCH_PROJECTION_CLEANUP_PROTOCOL,
226};
227pub use knowledge_retrieval_pipeline::{KnowledgeRetrievalPipelineReport, KnowledgeRetrievalStage};
228use lexical_projection::{
229    analyzer_digest as lexical_analyzer_digest, documents_digest as lexical_documents_digest,
230    LexicalMiniDelta, LexicalProjectionConfig, LexicalProjectionReader, LexicalProjectionWriter,
231};
232pub use lexical_readiness::{
233    SearchLexicalFeasibilityCoverage, SearchLexicalFeasibilityMetrics,
234    SearchLexicalProductionQualificationReport, SearchProjectionQualificationIdentity,
235    SearchTopKScoreParity, SEARCH_LEXICAL_QUALIFICATION_PROTOCOL,
236    SEARCH_LEXICAL_QUALIFICATION_PROTOCOL_VERSION,
237};
238pub use lexical_source_policy::SearchLexicalSourcePolicy;
239pub use lexical_term_policy::SearchLexicalTermPolicy;
240pub use out_of_core::{
241    GovernedSearchGenerationUpdate, GovernedSearchGenerationWriter, PreparedSearchPublication,
242    ScheduledSearchOutOfCoreSegmentCompactionReport, SearchAdmittedConsumerDocuments,
243    SearchBaselineComparisonLimits, SearchBaselineComparisonReport, SearchBodyReadOptions,
244    SearchComparedConsumerDocuments, SearchContentVerificationReport, SearchGenerationAdmission,
245    SearchMatchedBaseline, SearchMutationInspectionInput, SearchMutationInspectionStep,
246    SearchMutationSortStep, SearchMutationSortStepLimits, SearchMutationSortStepUsage,
247    SearchOutOfCoreBaselineComparison, SearchOutOfCoreCandidate, SearchOutOfCoreConfig,
248    SearchOutOfCoreDeltaComparison, SearchOutOfCoreDocumentLookup, SearchOutOfCoreExecutionContext,
249    SearchOutOfCoreGenerationBuildOptions, SearchOutOfCoreGenerationBuildReport,
250    SearchOutOfCoreGenerationUpdate, SearchOutOfCoreGenerationWriter,
251    SearchOutOfCoreHydrationOutput, SearchOutOfCoreMetrics, SearchOutOfCoreMutationWriter,
252    SearchOutOfCoreOutput, SearchOutOfCorePreparedGeneration, SearchOutOfCorePreparedUpdate,
253    SearchOutOfCoreReader, SearchOutOfCoreRefreshReport, SearchOutOfCoreSegmentCompaction,
254    SearchOutOfCoreSegmentCompactionPolicy, SearchOutOfCoreSegmentCompactionReport,
255    SearchOutOfCoreSegmentCompactionStopReason, SearchOutOfCoreUnorderedMutationWriter,
256    SearchOutOfCoreUnorderedReplacementWriter, SearchProjectionEpochAdvanceReport,
257    SearchQueryError, SearchQueryResult, SearchRetainedOutput, SearchStagingCleanupReport,
258    SearchTextSeedOutput, SearchTextSeedReport, SearchUnorderedMutationLimits,
259    SearchUnorderedMutationReport, SearchVerifiedBody,
260};
261pub use resident_text_seed::SearchResidentTextSeedOutput;
262// These are internal ownership seams. Hosts continue to use the embedded facade.
263#[doc(hidden)]
264pub use projection_catch_up::{
265    run_scheduled_search_projection_catch_up, run_search_projection_catch_up,
266    scheduled_search_projection_catch_up_report, search_projection_catch_up_report,
267    search_projection_durable_epoch, start_search_projection_background_work,
268    validate_search_projection_catch_up_request,
269};
270pub use projection_catch_up::{
271    ScheduledSearchProjectionCatchUpReport, SearchProjectionCatchUpReport,
272    SearchProjectionCatchUpStopReason,
273};
274#[doc(hidden)]
275pub use projection_delta_contracts::{
276    SearchProjectionChangeBatch, SearchProjectionGraphDeltaRequest, SearchProjectionRelationalDelta,
277};
278pub use range_io::SearchRangeReadConfig;
279use recall_validation::{sample_positions, VectorRecallValidationAccumulator};
280pub use recall_validation::{
281    VectorProjectionQualificationIdentity, VectorProjectionResourceEvidence,
282    VectorRecallProductionQualificationReport, VectorRecallValidationBlocker,
283    VectorRecallValidationOptions, VectorRecallValidationReport,
284    MAX_VECTOR_RECALL_VALIDATION_CANDIDATE_LIMIT, MAX_VECTOR_RECALL_VALIDATION_SAMPLES,
285    MAX_VECTOR_RECALL_VALIDATION_TOP_K, MINIMUM_VECTOR_QUALIFICATION_DOCUMENT_COUNT,
286    VECTOR_RECALL_PRODUCTION_QUALIFICATION_PROTOCOL, VECTOR_RECALL_VALIDATION_PROTOCOL,
287};
288pub use snapshot_writer::SearchCheckpointReport;
289use vector_execution::{execute_search_vector_plan, SearchVectorExecutionRequest};
290
291#[cfg(feature = "vector-search")]
292use rabitq_projection::{RaBitQCandidateProjection, RaBitQCandidateProjectionBuildOptions};
293
294const SEARCH_SNAPSHOT_FILE: &str = "search_projection.hawdb";
295const SEARCH_SEGMENT_DESCRIPTOR_FILE: &str = "search_projection_segments.hawdb";
296const SEARCH_SEGMENT_PAYLOAD_FILE: &str = "search_projection_segment_payloads.hawdb";
297const SEARCH_SEGMENT_PAYLOAD_ARTIFACT_ID: u64 = 1;
298
299/// Generation-named resident snapshot. An unregistered resident checkpoint
300/// writes this before its selector; `search_projection.hawdb` is then a hard
301/// link to the generation the out-of-core manifest selects.
302fn resident_snapshot_file(generation: u64) -> String {
303    format!("search_projection.{generation}.hawdb")
304}
305
306const RABITQ_CANDIDATE_BACKEND: &str = "hawdb_rabitq_candidate_projection";
307const DISKANN_CANDIDATE_BACKEND: &str = "hawdb_diskann_candidate_projection";
308
309#[derive(Clone, Copy)]
310enum VectorRecallProbeBackend {
311    Default,
312    Compressed,
313}
314
315impl VectorRecallProbeBackend {
316    fn name(self) -> &'static str {
317        match self {
318            Self::Default => DISKANN_CANDIDATE_BACKEND,
319            Self::Compressed => RABITQ_CANDIDATE_BACKEND,
320        }
321    }
322}
323static QUARANTINE_SEQUENCE: AtomicU64 = AtomicU64::new(0);
324#[cfg(feature = "vector-search")]
325const SEARCH_RABITQ_PROJECTION_PREFIX: &str = "search_rabitq.";
326#[cfg(feature = "vector-search")]
327const SEARCH_RABITQ_PROJECTION_SUFFIX: &str = ".hawdb";
328pub const FULL_REINDEX_MARKER: &str = ".reindex_needed";
329pub const METADATA_REPAIR_MARKER: &str = ".projection_metadata_repair_needed";
330/// Records the projection's externally owned kinds (#1814). Kept beside the
331/// selector instead of inside it so earlier readers, which refuse unknown
332/// manifest fields, still open the projection. See [`projection_ownership`].
333pub const EXTERNALLY_OWNED_KINDS_MARKER: &str = projection_ownership::MARKER;
334/// Records whether the host must resupply externally owned rows (#1814).
335pub const EXTERNALLY_OWNED_ROWS_MARKER: &str = projection_ownership::ROWS_MARKER;
336/// The BM25 constants shared with the SQL search index access path.
337use hawdb_executor::bm25::{BM25_B, BM25_K1};
338const TITLE_TERM_FREQUENCY_WEIGHT: usize = 2;
339const RRF_K: f64 = 60.0;
340const SEARCH_COMPRESSION_HEADER: &str = "HAWDB_COMPRESSED_V1";
341const SEARCH_COMPRESSION_LEVEL: i32 = 3;
342const SEARCH_DOCUMENT_ID_FIELD: &str = "document_id";
343pub use hawdb_evidence::replacement_contract::NOWLEDGE_SEARCH_PROJECTION_SCAN_FILTER_FIELDS;
344
345/// Nested Memory metadata paths with stable scalar/list semantics that are
346/// materialized into the search projection. Unknown paths remain residual
347/// predicates instead of expanding every segment descriptor for arbitrary
348/// application metadata.
349pub const NOWLEDGE_MEMORY_MATERIALIZED_METADATA_PATHS: &[&str] = &[
350    "state",
351    "topic",
352    "customer.tier",
353    "purpose",
354    "project_id",
355    "agent_id",
356    "host_agent_id",
357    "source_app",
358];
359#[cfg(not(test))]
360const SEARCH_FILTER_SEGMENT_TARGET_DOCUMENTS: usize = 128;
361#[cfg(test)]
362const SEARCH_FILTER_SEGMENT_TARGET_DOCUMENTS: usize = 2;
363
364#[derive(Debug, Clone, PartialEq)]
365pub struct SearchDocument {
366    pub id: String,
367    pub title: String,
368    pub content: String,
369    pub embedding: Option<Vec<f32>>,
370    pub metadata: BTreeMap<String, String>,
371}
372
373/// Bounded resident fields of a document whose body has separate ownership.
374#[derive(Debug, Clone, PartialEq)]
375pub struct SearchDocumentHeader {
376    pub id: String,
377    pub title: String,
378    pub embedding: Option<Vec<f32>>,
379    pub metadata: BTreeMap<String, String>,
380}
381
382/// Identity checks for a one-shot UTF-8 body supplied by the host.
383///
384/// The host must pin its canonical source snapshot through capture. CRC32c
385/// detects accidental changes; it is not cryptographic source authentication.
386#[derive(Debug, Clone, Copy, PartialEq, Eq)]
387pub struct SearchDocumentBody {
388    pub bytes: u64,
389    pub expected_checksum: Option<u64>,
390}
391
392#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
393pub enum SearchProjectionKind {
394    Memory,
395    Message,
396    Entity,
397    Source,
398    SourceChunk,
399    Community,
400}
401
402impl SearchProjectionKind {
403    pub fn as_str(self) -> &'static str {
404        match self {
405            SearchProjectionKind::Memory => "memory",
406            SearchProjectionKind::Message => "message",
407            SearchProjectionKind::Entity => "entity",
408            SearchProjectionKind::Source => "source",
409            SearchProjectionKind::SourceChunk => "source_chunk",
410            SearchProjectionKind::Community => "community",
411        }
412    }
413
414    /// Parses a name produced by [`Self::as_str`].
415    pub fn from_name(name: &str) -> Option<Self> {
416        Some(match name {
417            "memory" => SearchProjectionKind::Memory,
418            "message" => SearchProjectionKind::Message,
419            "entity" => SearchProjectionKind::Entity,
420            "source" => SearchProjectionKind::Source,
421            "source_chunk" => SearchProjectionKind::SourceChunk,
422            "community" => SearchProjectionKind::Community,
423            _ => return None,
424        })
425    }
426}
427
428#[derive(Debug, Clone, PartialEq)]
429pub struct SearchProjectionRow {
430    pub kind: SearchProjectionKind,
431    pub external_id: String,
432    pub title: String,
433    pub body: String,
434    pub embedding: Option<Vec<f32>>,
435    pub source_id: Option<String>,
436    pub metadata: BTreeMap<String, String>,
437}
438
439#[derive(Debug, Clone, PartialEq, Eq)]
440pub struct SearchEmbeddingManifest {
441    pub model: String,
442    pub version: Option<String>,
443    pub dimension: usize,
444}
445
446#[derive(Debug, Clone, PartialEq, Eq)]
447pub struct SearchProjectionFreshness {
448    pub document_count: usize,
449    /// Immutable provenance of a completed external bootstrap import. This is
450    /// not a local changefeed cursor and must never drive local catch-up.
451    pub import_source_graph_commit_epoch: Option<u64>,
452    pub source_graph_commit_epoch: Option<u64>,
453    pub durable_source_graph_commit_epoch: Option<u64>,
454    pub has_uncheckpointed_changes: bool,
455    pub full_reindex_needed: bool,
456    pub full_reindex_reasons: Vec<String>,
457    pub metadata_repair_needed: bool,
458    pub metadata_repair_reasons: Vec<String>,
459    pub embedding_model: Option<String>,
460    pub embedding_version: Option<String>,
461    pub embedding_dimension: Option<usize>,
462}
463
464#[derive(Debug, Clone, Default, PartialEq, Eq)]
465pub struct SearchProjectionProbeOptions {
466    pub active_embedding_model: Option<String>,
467    pub active_embedding_dimension: Option<usize>,
468}
469
470impl SearchProjectionRow {
471    pub fn into_document(self) -> SearchDocument {
472        let kind = self.kind.as_str();
473        let mut metadata = self.metadata;
474        metadata.insert("kind".to_string(), kind.to_string());
475        metadata.insert("external_id".to_string(), self.external_id.clone());
476        if let Some(source_id) = self.source_id {
477            metadata.insert("source_id".to_string(), source_id);
478        }
479        SearchDocument {
480            id: format!("{kind}:{}", self.external_id),
481            title: self.title,
482            content: self.body,
483            embedding: self.embedding,
484            metadata,
485        }
486    }
487}
488
489pub fn search_projection_document_id_for_node(
490    catalog: &Catalog,
491    node: &NodeRecord,
492) -> Option<String> {
493    hawdb_storage::projection::projection_document_id_for_node(catalog, node)
494}
495
496pub fn search_projection_document_id_for_label_and_properties(
497    label: &str,
498    properties: &BTreeMap<String, Value>,
499    node_id: NodeId,
500) -> Option<String> {
501    hawdb_storage::projection::projection_document_id_for_label_and_properties(
502        label, properties, node_id,
503    )
504}
505
506#[derive(Debug, Clone, Copy, PartialEq, Eq)]
507pub enum SearchMode {
508    Hybrid,
509    Vector,
510    Text,
511}
512
513#[derive(Debug, Clone, PartialEq)]
514pub struct SearchHit {
515    pub id: String,
516    pub score: f64,
517    /// Vector relevance in `[0, 1]`, higher is better. The scale depends on
518    /// the projection's metric: positive cosine similarity for cosine, and
519    /// `1 / (1 + l2_distance)` for Euclidean, which is often far below 1 for
520    /// unnormalized embeddings. Compare scores only within one metric; a
521    /// relevance floor tuned on cosine does not carry over to Euclidean.
522    /// `SearchVectorScoring::LinearSquaredL2` instead exposes
523    /// `max(0, 1 - squared_l2 / 2)` after selecting neighbors by distance.
524    pub vector_score: f64,
525    pub text_score: f64,
526    pub rrf_score: f64,
527    pub vector_rrf_score: f64,
528    pub text_rrf_score: f64,
529    pub vector_rank: Option<usize>,
530    pub text_rank: Option<usize>,
531    pub kind: Option<String>,
532    pub external_id: Option<String>,
533    pub source_id: Option<String>,
534    pub matched_terms: Vec<String>,
535    pub matched_spans: Vec<SearchMatchedSpan>,
536    pub fallback_reason_codes: Vec<SearchFallbackReasonCode>,
537    pub fallback_reasons: Vec<String>,
538    pub projection_freshness: SearchProjectionFreshness,
539}
540
541#[derive(Debug, Clone, PartialEq, Eq)]
542pub struct SearchMatchedSpan {
543    pub field: String,
544    pub start_byte: usize,
545    pub end_byte: usize,
546    pub text: String,
547    pub term: String,
548}
549
550#[derive(Debug, Clone, PartialEq)]
551pub struct SearchResultSet<H = SearchHit> {
552    pub hits: Vec<H>,
553    pub total_hits: usize,
554    pub limit: usize,
555    pub offset: usize,
556    pub truncated: bool,
557    pub truncation_reason_codes: Vec<SearchTruncationReasonCode>,
558    pub truncation_reasons: Vec<String>,
559    pub empty_reason_codes: Vec<SearchEmptyReasonCode>,
560    pub empty_reasons: Vec<String>,
561    pub fallback_reason_codes: Vec<SearchFallbackReasonCode>,
562    pub fallback_reasons: Vec<String>,
563    pub retrievers: Vec<SearchRetrieverReport>,
564    pub candidate_set: SearchCandidateSetReport,
565    pub rank_window: Option<usize>,
566    pub fusion_weights: SearchFusionWeights,
567    pub document_count: usize,
568    pub filtered_document_count: usize,
569    pub projection_freshness: SearchProjectionFreshness,
570}
571
572#[derive(Debug, Clone, PartialEq)]
573pub struct SearchScoredCandidate {
574    pub id: String,
575    pub score: f64,
576    pub vector_score: f64,
577    pub text_score: f64,
578    pub rrf_score: f64,
579    pub vector_rrf_score: f64,
580    pub text_rrf_score: f64,
581    pub vector_rank: Option<usize>,
582    pub text_rank: Option<usize>,
583}
584
585#[derive(Debug, Clone, Copy, PartialEq, Eq)]
586pub enum SearchTruncationReasonCode {
587    LimitExceeded,
588}
589
590impl SearchTruncationReasonCode {
591    pub fn as_str(self) -> &'static str {
592        match self {
593            SearchTruncationReasonCode::LimitExceeded => "limit_exceeded",
594        }
595    }
596}
597
598impl FromStr for SearchTruncationReasonCode {
599    type Err = &'static str;
600
601    fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
602        match value {
603            "limit_exceeded" => Ok(SearchTruncationReasonCode::LimitExceeded),
604            _ => Err("unknown search truncation reason code"),
605        }
606    }
607}
608
609#[derive(Debug, Clone, Copy, PartialEq, Eq)]
610pub enum SearchFallbackReasonCode {
611    VectorDimensionMismatch,
612    VectorIndexEmpty,
613    CompressedVectorProjectionUnavailable,
614    CompressedVectorBudgetExceeded,
615    DiskAnnCacheBudgetExceeded,
616    QueryEmbeddingMissing,
617    TextQueryEmpty,
618    /// The analyzed text query exceeded the scored-term cap; only its most
619    /// selective (lowest document frequency) terms were scored.
620    TextQueryTermsReduced,
621}
622
623impl SearchFallbackReasonCode {
624    pub fn as_str(self) -> &'static str {
625        match self {
626            SearchFallbackReasonCode::VectorDimensionMismatch => "vector_dimension_mismatch",
627            SearchFallbackReasonCode::VectorIndexEmpty => "vector_index_empty",
628            SearchFallbackReasonCode::CompressedVectorProjectionUnavailable => {
629                "compressed_vector_projection_unavailable"
630            }
631            SearchFallbackReasonCode::CompressedVectorBudgetExceeded => {
632                "compressed_vector_budget_exceeded"
633            }
634            SearchFallbackReasonCode::DiskAnnCacheBudgetExceeded => "diskann_cache_budget_exceeded",
635            SearchFallbackReasonCode::QueryEmbeddingMissing => "query_embedding_missing",
636            SearchFallbackReasonCode::TextQueryEmpty => "text_query_empty",
637            SearchFallbackReasonCode::TextQueryTermsReduced => "text_query_terms_reduced",
638        }
639    }
640}
641
642impl FromStr for SearchFallbackReasonCode {
643    type Err = &'static str;
644
645    fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
646        match value {
647            "vector_dimension_mismatch" => Ok(SearchFallbackReasonCode::VectorDimensionMismatch),
648            "vector_index_empty" => Ok(SearchFallbackReasonCode::VectorIndexEmpty),
649            "compressed_vector_projection_unavailable" => {
650                Ok(SearchFallbackReasonCode::CompressedVectorProjectionUnavailable)
651            }
652            "compressed_vector_budget_exceeded" => {
653                Ok(SearchFallbackReasonCode::CompressedVectorBudgetExceeded)
654            }
655            "diskann_cache_budget_exceeded" => {
656                Ok(SearchFallbackReasonCode::DiskAnnCacheBudgetExceeded)
657            }
658            "query_embedding_missing" => Ok(SearchFallbackReasonCode::QueryEmbeddingMissing),
659            "text_query_empty" => Ok(SearchFallbackReasonCode::TextQueryEmpty),
660            "text_query_terms_reduced" => Ok(SearchFallbackReasonCode::TextQueryTermsReduced),
661            _ => Err("unknown search fallback reason code"),
662        }
663    }
664}
665
666#[derive(Debug, Clone, Copy, PartialEq, Eq)]
667pub enum SearchEmptyReasonCode {
668    ProjectionEmpty,
669    MetadataFilterEmpty,
670    RetrieverNoHits,
671    LimitExcludedAllHits,
672}
673
674impl SearchEmptyReasonCode {
675    pub fn as_str(self) -> &'static str {
676        match self {
677            Self::ProjectionEmpty => "projection_empty",
678            Self::MetadataFilterEmpty => "metadata_filter_empty",
679            Self::RetrieverNoHits => "retriever_no_hits",
680            Self::LimitExcludedAllHits => "limit_excluded_all_hits",
681        }
682    }
683}
684
685#[derive(Debug, Clone, PartialEq, Eq)]
686pub struct SearchCandidateSetReport {
687    pub id_space: String,
688    pub representation: String,
689    pub cardinality: usize,
690    pub exact: bool,
691    pub snapshot_source_graph_commit_epoch: Option<u64>,
692    pub policy_epoch: Option<u64>,
693    pub filtered_out_count: usize,
694    pub metadata_filters: BTreeMap<String, String>,
695    pub metadata_predicate_pushdown: SearchPredicatePushdownReport,
696}
697
698#[derive(Debug, Clone, Default, PartialEq, Eq)]
699pub struct SearchPredicatePushdownReport {
700    pub input_predicate_count: usize,
701    pub pushed_predicate_count: usize,
702    pub residual_predicate_count: usize,
703    pub unsatisfiable: bool,
704    pub parse_error: Option<String>,
705    pub segment_count: usize,
706    pub pruned_segment_count: usize,
707    pub scanned_segment_count: usize,
708    pub segment_pruning_candidate_document_count: usize,
709    pub segment_pruned_document_count: usize,
710    pub segment_scanned_document_count: usize,
711    pub persisted_segment_descriptor_used: bool,
712    pub physical_range_read_count: usize,
713    pub physical_bytes_read: u64,
714    /// Scanned segments whose candidates came from metadata value postings
715    /// instead of decoding their metadata records.
716    pub postings_segment_count: usize,
717    /// Equality/IN predicates compiled into the segment postings plan.
718    pub postings_predicate_count: usize,
719    /// Predicates left for metadata evaluation after a postings prefilter.
720    pub postings_residual_predicate_count: usize,
721    /// Scanned segments where postings narrowed the metadata records evaluated
722    /// by residual predicates.
723    pub postings_prefiltered_segment_count: usize,
724    pub field_summaries: Vec<SearchPredicateFieldPruningReport>,
725}
726
727#[derive(Debug, Clone, Default, PartialEq, Eq)]
728pub struct SearchPredicateFieldPruningReport {
729    pub field: String,
730    pub value_kind: String,
731    pub operation_kinds: Vec<String>,
732    pub segment_count: usize,
733    pub pruned_segment_count: usize,
734    pub scanned_segment_count: usize,
735    pub numeric_range_summary_used: bool,
736    pub timestamp_range_summary_used: bool,
737    pub value_summary_used: bool,
738}
739
740#[derive(Debug, Clone, PartialEq)]
741pub struct SearchRetrieverReport {
742    pub name: String,
743    pub backend: String,
744    pub backend_selection_reason: Option<VectorBackendSelectionReason>,
745    pub estimated_raw_vector_bytes: Option<u64>,
746    pub filter_selectivity_per_million: Option<u32>,
747    pub available: bool,
748    pub input_candidate_set: SearchCandidateSetReport,
749    pub candidate_score_source: String,
750    pub final_score_source: String,
751    pub generated_candidate_count: usize,
752    pub candidate_scan_rounds: usize,
753    pub descriptor_pruned_count: usize,
754    pub scalar_filtered_count: usize,
755    pub residual_filtered_count: usize,
756    pub reranked_candidate_count: usize,
757    pub raw_vector_bytes_read: u64,
758    pub candidate_scan_kernel: Option<String>,
759    pub candidate_scan_worker_count: usize,
760    pub candidate_scan_segment_count: usize,
761    pub candidate_scan_scanned_segment_count: usize,
762    pub candidate_scan_scored_document_count: usize,
763    pub candidate_scan_filtered_document_count: usize,
764    pub candidate_scan_scanned_block_count: usize,
765    pub candidate_scan_skipped_block_count: usize,
766    pub candidate_scan_adaptive_exact_scan_count: usize,
767    pub candidate_scan_payload_bytes_read: u64,
768    pub candidate_scan_admitted_working_bytes: usize,
769    pub posting_bytes_read: u64,
770    pub candidate_postings_visited: u64,
771    /// Posting blocks whose frame-header bound could not reach the retained
772    /// floor, so their payloads were never decoded.
773    pub candidate_blocks_skipped: u64,
774    pub segmented_lexical_projection_used: bool,
775    pub index_covered_document_count: usize,
776    pub index_candidate_document_count: usize,
777    pub index_coverage_complete: bool,
778    pub candidate_count: usize,
779    pub candidate_set: SearchRetrieverCandidateSetReport,
780    pub fallback_reason_codes: Vec<SearchFallbackReasonCode>,
781    pub fallback_reasons: Vec<String>,
782    pub candidate_top_ids: Vec<String>,
783    pub top_hit_ids: Vec<String>,
784    pub top_candidates: Vec<SearchRetrieverCandidate>,
785}
786
787#[derive(Debug, Clone, PartialEq, Eq)]
788pub struct SearchRetrieverCandidateSetReport {
789    pub id_space: String,
790    pub representation: String,
791    pub cardinality: usize,
792    pub exact: bool,
793    pub snapshot_source_graph_commit_epoch: Option<u64>,
794    pub policy_epoch: Option<u64>,
795}
796
797#[derive(Debug, Clone, PartialEq)]
798pub struct SearchRetrieverCandidate {
799    pub id: String,
800    pub rank: usize,
801    pub score: f64,
802}
803
804#[derive(Debug, Clone, Copy, PartialEq)]
805pub struct SearchFusionWeights {
806    pub vector_weight: f64,
807    pub text_weight: f64,
808}
809
810impl Default for SearchFusionWeights {
811    fn default() -> Self {
812        Self {
813            vector_weight: 1.0,
814            text_weight: 1.0,
815        }
816    }
817}
818
819/// How much of each ranked out-of-core hit is materialized after scoring.
820///
821/// Ranking, filtering, totals and reports are identical for every level.
822#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
823pub enum SearchHitHydration {
824    /// Hydrate the metadata fields, matched terms/spans and the vector score
825    /// recomputed from the stored embedding. Vector-only requests without
826    /// query terms need no matched spans, so they read the metadata and vector
827    /// sidecars instead of the full document payload; the hits are identical.
828    #[default]
829    Documents,
830    /// Hydrate the metadata fields and the vector score recomputed from the
831    /// stored embedding, without matched terms/spans. Hits read only their
832    /// metadata sidecar segments and their own binary vector rows, never the
833    /// document payload, for every search mode. The hits equal `Documents`
834    /// hits except that `matched_terms` and `matched_spans` are empty.
835    Metadata,
836    /// Return identifiers and ranking scores without reading any document,
837    /// metadata or vector payload. `kind`, `external_id` and `source_id` are
838    /// `None`, matched terms/spans are empty, and `vector_score` is the vector
839    /// retriever's ranking score (0 for hits it did not rank).
840    ScoresOnly,
841}
842
843#[derive(Debug, Clone, PartialEq)]
844pub struct SearchQueryOptions {
845    pub limit: usize,
846    pub offset: usize,
847    pub rank_window: Option<usize>,
848    pub fusion_weights: SearchFusionWeights,
849    pub metadata_filters: BTreeMap<String, String>,
850    pub policy_epoch: Option<u64>,
851}
852
853#[derive(Debug, Clone, PartialEq, Eq)]
854pub struct SearchAccessControlContext {
855    pub policy_epoch: u64,
856    pub visibility_metadata_field: String,
857    pub allowed_visibility_values: BTreeSet<String>,
858}
859
860impl SearchAccessControlContext {
861    pub fn visibility_scopes(
862        policy_epoch: u64,
863        visibility_metadata_field: impl Into<String>,
864        allowed_visibility_values: impl IntoIterator<Item = impl Into<String>>,
865    ) -> Self {
866        Self {
867            policy_epoch,
868            visibility_metadata_field: visibility_metadata_field.into(),
869            allowed_visibility_values: allowed_visibility_values
870                .into_iter()
871                .map(Into::into)
872                .collect(),
873        }
874    }
875
876    /// Refuses a context the caller built incorrectly. These are caller
877    /// mistakes, not storage faults, so they are `Semantic` like the core
878    /// `QueryAccessControlContext::validate` (#1767).
879    fn validate(&self) -> Result<()> {
880        if self.policy_epoch == 0 {
881            return Err(HawDBError::Semantic(
882                "access control context requires a non-zero policy epoch".to_string(),
883            ));
884        }
885        if self.visibility_metadata_field.trim().is_empty() {
886            return Err(HawDBError::Semantic(
887                "access control context requires a visibility metadata field".to_string(),
888            ));
889        }
890        if self.allowed_visibility_values.is_empty() {
891            return Err(HawDBError::Semantic(
892                "access control context requires at least one visibility value".to_string(),
893            ));
894        }
895        if self
896            .allowed_visibility_values
897            .iter()
898            .any(|value| value.trim().is_empty())
899        {
900            return Err(HawDBError::Semantic(
901                "access control context visibility values must be non-empty".to_string(),
902            ));
903        }
904        Ok(())
905    }
906
907    /// Refuses search options whose own policy epoch disagrees with this
908    /// context. Both the resident and the out-of-core reader call this.
909    fn check_options_policy_epoch(&self, policy_epoch: Option<u64>) -> Result<()> {
910        match policy_epoch {
911            Some(policy_epoch) if policy_epoch != self.policy_epoch => {
912                Err(HawDBError::Semantic(format!(
913                    "search options policy epoch {policy_epoch} does not match access control policy epoch {}",
914                    self.policy_epoch
915                )))
916            }
917            _ => Ok(()),
918        }
919    }
920
921    /// Requests each caller check refuses: `(options policy epoch, context)`.
922    /// Shared by the resident and out-of-core reader tests (#1767).
923    #[cfg(all(test, feature = "acl", feature = "full-text-search"))]
924    pub(crate) fn invalid_requests_for_test() -> Vec<(Option<u64>, Self)> {
925        vec![
926            (Some(8), Self::visibility_scopes(7, "space_id", ["team"])),
927            (None, Self::visibility_scopes(0, "space_id", ["team"])),
928            (None, Self::visibility_scopes(7, " ", ["team"])),
929            (
930                None,
931                Self::visibility_scopes(7, "space_id", Vec::<String>::new()),
932            ),
933            (None, Self::visibility_scopes(7, "space_id", ["team", " "])),
934        ]
935    }
936
937    /// The metadata filters a query runs with under this context: `options`'
938    /// filters plus the visibility predicate, after both caller checks.
939    pub(crate) fn effective_query_filters(
940        &self,
941        options: &SearchQueryOptions,
942    ) -> Result<BTreeMap<String, String>> {
943        self.check_options_policy_epoch(options.policy_epoch)?;
944        self.effective_metadata_filters(&options.metadata_filters)
945    }
946
947    pub fn effective_metadata_filters(
948        &self,
949        metadata_filters: &BTreeMap<String, String>,
950    ) -> Result<BTreeMap<String, String>> {
951        self.validate()?;
952        let mut filters = metadata_filters.clone();
953        if self.allowed_visibility_values.len() == 1 {
954            filters.insert(
955                self.visibility_metadata_field.clone(),
956                self.allowed_visibility_values
957                    .iter()
958                    .next()
959                    .expect("single visibility value")
960                    .clone(),
961            );
962        } else {
963            filters.insert(
964                format!("{}__in", self.visibility_metadata_field),
965                serde_json::to_string(
966                    &self
967                        .allowed_visibility_values
968                        .iter()
969                        .cloned()
970                        .collect::<Vec<_>>(),
971                )
972                .map_err(|error| {
973                    HawDBError::or_stop(&error, || {
974                        HawDBError::Storage(format!(
975                            "failed to encode access control visibility predicate: {error}"
976                        ))
977                    })
978                })?,
979            );
980        }
981        Ok(filters)
982    }
983}
984
985#[derive(Debug, Clone, Copy, PartialEq, Eq)]
986pub enum CompressedVectorSearchMode {
987    Disabled,
988    Preferred,
989    Required,
990}
991
992impl CompressedVectorSearchMode {
993    pub fn as_str(self) -> &'static str {
994        match self {
995            Self::Disabled => "disabled",
996            Self::Preferred => "preferred",
997            Self::Required => "required",
998        }
999    }
1000}
1001
1002pub const DEFAULT_VECTOR_SEARCH_WORKING_BYTES: usize = 64 * 1024 * 1024;
1003
1004#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1005pub enum VectorSearchKernelPreference {
1006    #[default]
1007    Auto,
1008    Scalar,
1009    Avx2,
1010    Neon,
1011}
1012
1013impl VectorSearchKernelPreference {
1014    pub const fn as_str(self) -> &'static str {
1015        match self {
1016            Self::Auto => "auto",
1017            Self::Scalar => "scalar",
1018            Self::Avx2 => "avx2",
1019            Self::Neon => "neon",
1020        }
1021    }
1022
1023    #[cfg(feature = "vector-search")]
1024    pub(crate) fn projection_preference(self) -> hawdb_vector_projection::KernelPreference {
1025        match self {
1026            Self::Auto => hawdb_vector_projection::KernelPreference::Auto,
1027            Self::Scalar => hawdb_vector_projection::KernelPreference::Scalar,
1028            Self::Avx2 => hawdb_vector_projection::KernelPreference::Avx2,
1029            Self::Neon => hawdb_vector_projection::KernelPreference::Neon,
1030        }
1031    }
1032}
1033
1034/// Default DiskANN navigation beam for resident and canonical index serving.
1035pub const DEFAULT_NAVIGATION_BEAM: usize = 1024;
1036
1037/// Default beam for ordinary out-of-core Search queries. Canonical index
1038/// serving keeps `DEFAULT_NAVIGATION_BEAM` and its single-graph recall budget.
1039pub const DEFAULT_OUT_OF_CORE_NAVIGATION_BEAM: usize = 256;
1040
1041#[derive(Debug, Clone, Copy)]
1042pub struct VectorSearchExecutionOptions<'a> {
1043    pub max_parallelism: NonZeroUsize,
1044    pub max_working_bytes: usize,
1045    pub kernel: VectorSearchKernelPreference,
1046    pub task_context: Option<&'a hawdb_core::RuntimeTaskContext>,
1047    capture_candidate_ids: bool,
1048    exact: bool,
1049    navigation_beam: Option<NonZeroUsize>,
1050    candidate_window: Option<NonZeroUsize>,
1051}
1052
1053impl<'a> VectorSearchExecutionOptions<'a> {
1054    pub fn bounded(
1055        max_parallelism: NonZeroUsize,
1056        max_working_bytes: usize,
1057        task_context: Option<&'a hawdb_core::RuntimeTaskContext>,
1058    ) -> Self {
1059        Self {
1060            max_parallelism,
1061            max_working_bytes,
1062            kernel: VectorSearchKernelPreference::Auto,
1063            task_context,
1064            capture_candidate_ids: false,
1065            exact: false,
1066            navigation_beam: None,
1067            candidate_window: None,
1068        }
1069    }
1070
1071    pub fn admitted(
1072        max_working_bytes: usize,
1073        task_context: &'a hawdb_core::RuntimeTaskContext,
1074    ) -> Self {
1075        Self::bounded(
1076            task_context.admitted_parallelism(),
1077            max_working_bytes,
1078            Some(task_context),
1079        )
1080    }
1081
1082    pub fn with_kernel(mut self, kernel: VectorSearchKernelPreference) -> Self {
1083        self.kernel = kernel;
1084        self
1085    }
1086
1087    /// Bypass approximate graph candidates and score the complete eligible set.
1088    pub fn with_exact_search(mut self) -> Self {
1089        self.exact = true;
1090        self
1091    }
1092
1093    pub fn capture_candidates_for_validation(mut self) -> Self {
1094        self.capture_candidate_ids = true;
1095        self
1096    }
1097
1098    /// DiskANN navigation beam for this query, never below the
1099    /// requested result count. A smaller beam trades recall for speed, while a
1100    /// traversal that spreads over a graph small for the beam may finish with a
1101    /// complete evaluation. In a store of several graphs, a later graph may end
1102    /// its traversal early once earlier graphs hold the results (#1918). The
1103    /// traversal stays bounded by `max_working_bytes`, and a beam whose
1104    /// workspace does not fit is refused, not truncated.
1105    /// Ordinary out-of-core Search inherits its reader's default (256);
1106    /// resident and canonical index serving retain the generic default (1024).
1107    pub fn with_navigation_beam(mut self, beam: NonZeroUsize) -> Self {
1108        self.navigation_beam = Some(beam);
1109        self
1110    }
1111
1112    /// Approximate candidates generated and reranked for this query: the
1113    /// RaBitQ rerank depth and DiskANN candidate count. Without it, the window
1114    /// is `max(limit, rank_window, 128)` (out of core, at most
1115    /// `max_vector_candidates`). The window never goes below the limit or rank
1116    /// window. A window below the default 128 does less work but can lower
1117    /// recall, because fewer approximate candidates reach the exact rerank.
1118    /// In a segmented DiskANN store the shared result bound follows the
1119    /// retained page (`offset + limit`) or `rank_window`, not this window, so
1120    /// ranks above that page can be less complete than with a full traversal.
1121    /// Out of core, a window above the reader's `max_vector_candidates` is
1122    /// refused; resident search stays bounded by its working memory.
1123    pub fn with_candidate_window(mut self, window: NonZeroUsize) -> Self {
1124        self.candidate_window = Some(window);
1125        self
1126    }
1127
1128    #[cfg(feature = "vector-search")]
1129    pub(crate) fn navigation_beam(&self, top_k: usize) -> usize {
1130        top_k.max(self.navigation_beam.map_or(
1131            crate::vector_execution::DISKANN_NAVIGATION_BEAM,
1132            NonZeroUsize::get,
1133        ))
1134    }
1135
1136    #[cfg(feature = "vector-search")]
1137    pub(crate) fn candidate_window(&self) -> Option<usize> {
1138        self.candidate_window.map(NonZeroUsize::get)
1139    }
1140
1141    /// The resident DiskANN candidate floor: the per-query window, or the
1142    /// default navigation window.
1143    #[cfg(feature = "vector-search")]
1144    pub(crate) fn resident_candidate_window(&self) -> usize {
1145        self.candidate_window()
1146            .unwrap_or(hawdb_vector_projection::diskann::DiskAnnSearchOptions::default().beam_width)
1147    }
1148}
1149
1150impl Default for VectorSearchExecutionOptions<'_> {
1151    fn default() -> Self {
1152        Self {
1153            max_parallelism: NonZeroUsize::MIN,
1154            max_working_bytes: DEFAULT_VECTOR_SEARCH_WORKING_BYTES,
1155            kernel: VectorSearchKernelPreference::Auto,
1156            task_context: None,
1157            capture_candidate_ids: false,
1158            exact: false,
1159            navigation_beam: None,
1160            candidate_window: None,
1161        }
1162    }
1163}
1164
1165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1166pub struct AdaptiveVectorSearchOptions {
1167    pub compression_mode: CompressedVectorSearchMode,
1168    pub backend_policy: AdaptiveVectorBackendPolicy,
1169    pub recall_validation_probe: bool,
1170}
1171
1172impl AdaptiveVectorSearchOptions {
1173    pub fn new(compression_mode: CompressedVectorSearchMode) -> Self {
1174        Self {
1175            compression_mode,
1176            backend_policy: AdaptiveVectorBackendPolicy::default(),
1177            recall_validation_probe: false,
1178        }
1179    }
1180
1181    pub fn with_backend_policy(mut self, policy: AdaptiveVectorBackendPolicy) -> Self {
1182        self.backend_policy = policy;
1183        self
1184    }
1185
1186    pub fn as_recall_validation_probe(mut self) -> Self {
1187        self.recall_validation_probe = true;
1188        self
1189    }
1190}
1191
1192fn vector_compression_preference(mode: CompressedVectorSearchMode) -> VectorCompressionPreference {
1193    match mode {
1194        CompressedVectorSearchMode::Disabled => VectorCompressionPreference::Disabled,
1195        CompressedVectorSearchMode::Preferred => VectorCompressionPreference::Preferred,
1196        CompressedVectorSearchMode::Required => VectorCompressionPreference::Required,
1197    }
1198}
1199
1200fn adaptive_vector_fallback_reason(decision: AdaptiveVectorBackendDecision) -> Option<String> {
1201    match decision.reason {
1202        VectorBackendSelectionReason::QuantizedProjectionUnavailable => {
1203            Some(if decision.backend == AdaptiveVectorBackend::RequiredProjectionUnavailable {
1204                "compressed vector projection required but unavailable"
1205            } else {
1206                "compressed vector projection unavailable; fell back to scalar vector scan"
1207            }
1208            .to_string())
1209        }
1210        VectorBackendSelectionReason::QuantizedProjectionCoverageIncomplete => {
1211            Some(if decision.backend == AdaptiveVectorBackend::RequiredProjectionUnavailable {
1212                "compressed vector projection required but candidate coverage is incomplete"
1213            } else {
1214                "compressed vector projection candidate coverage is incomplete; fell back to scalar vector scan"
1215            }
1216            .to_string())
1217        }
1218        _ => None,
1219    }
1220}
1221
1222fn recall_validation_hit_ids(
1223    result: &SearchResultSet,
1224    sampled_document_id: &str,
1225    top_k: usize,
1226) -> Vec<String> {
1227    result
1228        .hits
1229        .iter()
1230        .filter(|hit| hit.id != sampled_document_id)
1231        .take(top_k)
1232        .map(|hit| hit.id.clone())
1233        .collect()
1234}
1235
1236fn recall_validation_candidate_ids(
1237    candidate_ids: &[String],
1238    sampled_document_id: &str,
1239    candidate_limit: usize,
1240) -> Vec<String> {
1241    candidate_ids
1242        .iter()
1243        .filter(|id| id.as_str() != sampled_document_id)
1244        .take(candidate_limit)
1245        .cloned()
1246        .collect()
1247}
1248
1249#[derive(Clone, Copy)]
1250enum VectorSearchBackend<'a> {
1251    Scalar,
1252    #[cfg(feature = "vector-search")]
1253    DiskAnn {
1254        index: &'a SearchIndex,
1255    },
1256    CompressedRequiredUnavailable,
1257    #[cfg(not(feature = "vector-search"))]
1258    _Lifetime(std::marker::PhantomData<&'a ()>),
1259    #[cfg(feature = "vector-search")]
1260    RaBitQ {
1261        projection: &'a RaBitQCandidateProjection,
1262        required: bool,
1263    },
1264    #[cfg(feature = "qualification")]
1265    ExternalValidation {
1266        candidates: &'a [(String, f64)],
1267        indexed_document_ids: &'a BTreeSet<String>,
1268    },
1269}
1270
1271#[derive(Clone, Copy)]
1272enum SearchPayloadAccess {
1273    InMemory,
1274    PrunedRanges,
1275}
1276
1277struct SearchExecutionStrategy<'a> {
1278    vector_backend: VectorSearchBackendRequest<'a>,
1279    vector_backend_fallback_reason: Option<String>,
1280    payload_access: SearchPayloadAccess,
1281    capture_candidate_ids: bool,
1282    vector_execution_options: VectorSearchExecutionOptions<'a>,
1283}
1284
1285#[derive(Clone, Copy)]
1286struct AdaptiveVectorExecutionControls<'a> {
1287    use_physical_range_reads: bool,
1288    capture_candidate_ids: bool,
1289    vector_execution_options: VectorSearchExecutionOptions<'a>,
1290}
1291
1292impl<'a> AdaptiveVectorExecutionControls<'a> {
1293    const IN_MEMORY: Self = Self {
1294        use_physical_range_reads: false,
1295        capture_candidate_ids: false,
1296        vector_execution_options: VectorSearchExecutionOptions {
1297            max_parallelism: NonZeroUsize::MIN,
1298            max_working_bytes: DEFAULT_VECTOR_SEARCH_WORKING_BYTES,
1299            kernel: VectorSearchKernelPreference::Auto,
1300            task_context: None,
1301            capture_candidate_ids: false,
1302            exact: false,
1303            navigation_beam: None,
1304            candidate_window: None,
1305        },
1306    };
1307    const PERSISTED: Self = Self {
1308        use_physical_range_reads: true,
1309        capture_candidate_ids: false,
1310        vector_execution_options: VectorSearchExecutionOptions {
1311            max_parallelism: NonZeroUsize::MIN,
1312            max_working_bytes: DEFAULT_VECTOR_SEARCH_WORKING_BYTES,
1313            kernel: VectorSearchKernelPreference::Auto,
1314            task_context: None,
1315            capture_candidate_ids: false,
1316            exact: false,
1317            navigation_beam: None,
1318            candidate_window: None,
1319        },
1320    };
1321    const RECALL_CANDIDATES: Self = Self {
1322        use_physical_range_reads: false,
1323        capture_candidate_ids: true,
1324        vector_execution_options: VectorSearchExecutionOptions {
1325            max_parallelism: NonZeroUsize::MIN,
1326            max_working_bytes: DEFAULT_VECTOR_SEARCH_WORKING_BYTES,
1327            kernel: VectorSearchKernelPreference::Auto,
1328            task_context: None,
1329            capture_candidate_ids: true,
1330            exact: false,
1331            navigation_beam: None,
1332            candidate_window: None,
1333        },
1334    };
1335
1336    fn persisted(vector_execution_options: VectorSearchExecutionOptions<'a>) -> Self {
1337        Self {
1338            use_physical_range_reads: true,
1339            capture_candidate_ids: vector_execution_options.capture_candidate_ids,
1340            vector_execution_options,
1341        }
1342    }
1343}
1344
1345#[derive(Clone, Copy)]
1346enum VectorSearchBackendRequest<'a> {
1347    Default,
1348    Fixed(VectorSearchBackend<'a>),
1349    Adaptive(AdaptiveVectorSearchRequest),
1350}
1351
1352#[derive(Clone, Copy)]
1353struct AdaptiveVectorSearchRequest {
1354    compression_preference: VectorCompressionPreference,
1355    policy: AdaptiveVectorBackendPolicy,
1356    recall_validation_probe: bool,
1357}
1358
1359struct PreparedAdaptiveVectorBackend {
1360    decision: AdaptiveVectorBackendDecision,
1361    fallback_reason: Option<String>,
1362    #[cfg(feature = "vector-search")]
1363    projection: Option<Arc<RaBitQCandidateProjection>>,
1364}
1365
1366impl<'a> SearchExecutionStrategy<'a> {
1367    fn default_vector(
1368        use_physical_range_reads: bool,
1369        options: VectorSearchExecutionOptions<'a>,
1370    ) -> Self {
1371        let mut strategy = Self::fixed(VectorSearchBackend::Scalar, None, use_physical_range_reads);
1372        strategy.vector_backend = VectorSearchBackendRequest::Default;
1373        strategy.capture_candidate_ids = options.capture_candidate_ids;
1374        strategy.vector_execution_options = options;
1375        strategy
1376    }
1377
1378    fn fixed(
1379        vector_backend: VectorSearchBackend<'a>,
1380        vector_backend_fallback_reason: Option<String>,
1381        use_physical_range_reads: bool,
1382    ) -> Self {
1383        Self {
1384            vector_backend: VectorSearchBackendRequest::Fixed(vector_backend),
1385            vector_backend_fallback_reason,
1386            payload_access: if use_physical_range_reads {
1387                SearchPayloadAccess::PrunedRanges
1388            } else {
1389                SearchPayloadAccess::InMemory
1390            },
1391            capture_candidate_ids: false,
1392            vector_execution_options: VectorSearchExecutionOptions::default(),
1393        }
1394    }
1395
1396    fn adaptive(
1397        compression_preference: VectorCompressionPreference,
1398        policy: AdaptiveVectorBackendPolicy,
1399        recall_validation_probe: bool,
1400        controls: AdaptiveVectorExecutionControls<'a>,
1401    ) -> Self {
1402        Self {
1403            vector_backend: VectorSearchBackendRequest::Adaptive(AdaptiveVectorSearchRequest {
1404                compression_preference,
1405                policy,
1406                recall_validation_probe,
1407            }),
1408            vector_backend_fallback_reason: None,
1409            payload_access: if controls.use_physical_range_reads {
1410                SearchPayloadAccess::PrunedRanges
1411            } else {
1412                SearchPayloadAccess::InMemory
1413            },
1414            capture_candidate_ids: controls.capture_candidate_ids,
1415            vector_execution_options: controls.vector_execution_options,
1416        }
1417    }
1418}
1419
1420impl PreparedAdaptiveVectorBackend {
1421    fn backend(&self) -> VectorSearchBackend<'_> {
1422        match self.decision.backend {
1423            AdaptiveVectorBackend::ScalarFlat => VectorSearchBackend::Scalar,
1424            AdaptiveVectorBackend::RequiredProjectionUnavailable => {
1425                VectorSearchBackend::CompressedRequiredUnavailable
1426            }
1427            AdaptiveVectorBackend::QuantizedProjection => {
1428                #[cfg(feature = "vector-search")]
1429                {
1430                    VectorSearchBackend::RaBitQ {
1431                        projection: self
1432                            .projection
1433                            .as_ref()
1434                            .expect("quantized backend requires a loaded projection"),
1435                        required: self.decision.reason
1436                            == VectorBackendSelectionReason::QuantizedRequired,
1437                    }
1438                }
1439                #[cfg(not(feature = "vector-search"))]
1440                {
1441                    unreachable!("quantized backend is unavailable without vector-search")
1442                }
1443            }
1444        }
1445    }
1446}
1447
1448impl VectorSearchBackend<'_> {
1449    fn report_name(self) -> &'static str {
1450        match self {
1451            Self::Scalar => "scalar_vector_scan",
1452            #[cfg(feature = "vector-search")]
1453            Self::DiskAnn { .. } => DISKANN_CANDIDATE_BACKEND,
1454            Self::CompressedRequiredUnavailable => "compressed_vector_projection_required",
1455            #[cfg(not(feature = "vector-search"))]
1456            Self::_Lifetime(_) => "scalar_vector_scan",
1457            #[cfg(feature = "vector-search")]
1458            Self::RaBitQ { .. } => RABITQ_CANDIDATE_BACKEND,
1459            #[cfg(feature = "qualification")]
1460            Self::ExternalValidation { .. } => "external_validation_candidate_projection",
1461        }
1462    }
1463
1464    fn candidate_source(self) -> VectorCandidateSource {
1465        match self {
1466            Self::Scalar | Self::CompressedRequiredUnavailable => VectorCandidateSource::Scalar,
1467            #[cfg(feature = "vector-search")]
1468            Self::DiskAnn { .. } => VectorCandidateSource::Ann,
1469            #[cfg(not(feature = "vector-search"))]
1470            Self::_Lifetime(_) => VectorCandidateSource::Scalar,
1471            #[cfg(feature = "vector-search")]
1472            Self::RaBitQ { .. } => VectorCandidateSource::Quantized,
1473            #[cfg(feature = "qualification")]
1474            Self::ExternalValidation { .. } => VectorCandidateSource::Quantized,
1475        }
1476    }
1477
1478    fn index_coverage(self, documents: &[&SearchDocument]) -> (usize, usize) {
1479        let candidate_count = documents
1480            .iter()
1481            .filter(|document| document.embedding.is_some())
1482            .count();
1483        let covered_count = match self {
1484            Self::Scalar => candidate_count,
1485            #[cfg(feature = "vector-search")]
1486            Self::DiskAnn { .. } => candidate_count,
1487            Self::CompressedRequiredUnavailable => 0,
1488            #[cfg(not(feature = "vector-search"))]
1489            Self::_Lifetime(_) => candidate_count,
1490            #[cfg(feature = "vector-search")]
1491            Self::RaBitQ { projection, .. } => documents
1492                .iter()
1493                .filter(|document| {
1494                    document.embedding.is_some()
1495                        && projection.contains_document_id(document.id.as_str())
1496                })
1497                .count(),
1498            #[cfg(feature = "qualification")]
1499            Self::ExternalValidation {
1500                indexed_document_ids,
1501                ..
1502            } => documents
1503                .iter()
1504                .filter(|document| {
1505                    document.embedding.is_some()
1506                        && indexed_document_ids.contains(document.id.as_str())
1507                })
1508                .count(),
1509        };
1510        (covered_count, candidate_count)
1511    }
1512}
1513
1514#[derive(Debug, Clone, PartialEq, Eq)]
1515pub struct SearchAnalyzerLexicon {
1516    alias_rules: Vec<SearchAnalyzerAliasRule>,
1517    stopwords: BTreeSet<String>,
1518}
1519
1520impl SearchAnalyzerLexicon {
1521    /// Distinct analyzed terms `text` produces as a lexical query.
1522    ///
1523    /// Hosts can compare this with the analyzed-term cap (default 1024) before
1524    /// submitting a query. Unlike query admission, it analyzes all of `text`
1525    /// without that cap, so its cost grows with the input.
1526    pub fn analyzed_query_term_count(&self, text: &str) -> usize {
1527        tokenize(text, self).len()
1528    }
1529
1530    pub fn empty() -> Self {
1531        Self {
1532            alias_rules: Vec::new(),
1533            stopwords: BTreeSet::new(),
1534        }
1535    }
1536
1537    pub fn with_alias_rule<I, A, S, T>(mut self, inputs: I, aliases: A) -> Self
1538    where
1539        I: IntoIterator<Item = S>,
1540        A: IntoIterator<Item = T>,
1541        S: Into<String>,
1542        T: Into<String>,
1543    {
1544        let inputs = inputs
1545            .into_iter()
1546            .map(Into::into)
1547            .filter(|input: &String| !input.is_empty())
1548            .collect::<Vec<_>>();
1549        let aliases = aliases
1550            .into_iter()
1551            .map(Into::into)
1552            .filter(|alias: &String| !alias.is_empty())
1553            .collect::<Vec<_>>();
1554        if !inputs.is_empty() && !aliases.is_empty() {
1555            self.alias_rules
1556                .push(SearchAnalyzerAliasRule { inputs, aliases });
1557        }
1558        self
1559    }
1560
1561    pub fn with_normalized_alias_rule<I, A, S, T>(self, inputs: I, aliases: A) -> Self
1562    where
1563        I: IntoIterator<Item = S>,
1564        A: IntoIterator<Item = T>,
1565        S: AsRef<str>,
1566        T: AsRef<str>,
1567    {
1568        self.with_alias_rule(
1569            inputs
1570                .into_iter()
1571                .flat_map(|input| normalized_alias_rule_terms(input.as_ref())),
1572            aliases
1573                .into_iter()
1574                .flat_map(|alias| normalized_alias_rule_terms(alias.as_ref())),
1575        )
1576    }
1577
1578    pub fn with_stopwords<I, S>(mut self, stopwords: I) -> Self
1579    where
1580        I: IntoIterator<Item = S>,
1581        S: AsRef<str>,
1582    {
1583        self.stopwords.extend(
1584            stopwords
1585                .into_iter()
1586                .flat_map(|stopword| normalized_stopword_terms(stopword.as_ref())),
1587        );
1588        self
1589    }
1590
1591    pub fn nowledge_memory() -> Self {
1592        Self::default().with_nowledge_memory_aliases()
1593    }
1594
1595    pub fn with_nowledge_memory_aliases(self) -> Self {
1596        NOWLEDGE_MEMORY_SEMANTIC_ALIAS_RULES
1597            .iter()
1598            .fold(self, |lexicon, (inputs, aliases)| {
1599                lexicon.with_normalized_alias_rule(inputs.iter().copied(), aliases.iter().copied())
1600            })
1601    }
1602
1603    fn is_stopword(&self, token: &str) -> bool {
1604        is_core_search_stopword(token) || self.stopwords.contains(token)
1605    }
1606
1607    #[cfg(test)]
1608    fn semantic_aliases(&self, token: &str) -> Vec<String> {
1609        self.alias_rules
1610            .iter()
1611            .filter(|rule| rule.inputs.iter().any(|input| input == token))
1612            .flat_map(|rule| rule.aliases.iter().cloned())
1613            .collect()
1614    }
1615
1616    fn semantic_alias_slices<'a>(&'a self, token: &str) -> impl Iterator<Item = &'a str> {
1617        self.alias_rules
1618            .iter()
1619            .filter(move |rule| rule.inputs.iter().any(|input| input == token))
1620            .flat_map(|rule| rule.aliases.iter().map(String::as_str))
1621    }
1622}
1623
1624impl Default for SearchAnalyzerLexicon {
1625    fn default() -> Self {
1626        CORE_SEMANTIC_ALIAS_RULES
1627            .iter()
1628            .fold(Self::empty(), |lexicon, (inputs, aliases)| {
1629                lexicon.with_alias_rule(inputs.iter().copied(), aliases.iter().copied())
1630            })
1631    }
1632}
1633
1634#[derive(Debug, Clone, PartialEq, Eq)]
1635struct SearchAnalyzerAliasRule {
1636    inputs: Vec<String>,
1637    aliases: Vec<String>,
1638}
1639
1640#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1641pub struct SearchRebuildOptions {
1642    pub max_rows: Option<usize>,
1643}
1644
1645#[derive(Debug, Clone, PartialEq, Eq)]
1646pub struct SearchRebuildSummary {
1647    pub scanned_nodes: usize,
1648    pub indexed_documents: usize,
1649}
1650
1651#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1652pub struct MetadataRepairOptions {
1653    pub max_rows: Option<usize>,
1654}
1655
1656#[derive(Debug, Clone, PartialEq, Eq)]
1657pub struct MetadataRepairSummary {
1658    pub scanned_nodes: usize,
1659    pub repaired_documents: usize,
1660    pub missing_documents: usize,
1661}
1662
1663#[derive(Debug, Clone, PartialEq, Eq)]
1664pub struct SearchDerivedArtifactReport {
1665    pub artifact_type: String,
1666    pub name: String,
1667    pub action: String,
1668    pub before_document_count: usize,
1669    pub after_document_count: usize,
1670    pub scanned_nodes: usize,
1671    pub indexed_documents: usize,
1672    pub full_reindex_needed: bool,
1673    pub full_reindex_reasons: Vec<String>,
1674    pub metadata_repair_needed: bool,
1675    pub metadata_repair_reasons: Vec<String>,
1676}
1677
1678#[derive(Debug, Clone, Default, PartialEq)]
1679pub struct SearchProjectionDelta {
1680    pub upserts: Vec<SearchProjectionRow>,
1681    pub deletes: Vec<String>,
1682    pub max_operations: Option<usize>,
1683    pub source_graph_commit_epoch: Option<u64>,
1684}
1685
1686impl SearchProjectionDelta {
1687    pub fn operation_count(&self) -> usize {
1688        self.upserts.len() + self.deletes.len()
1689    }
1690
1691    pub fn background_work_request(&self) -> WorkRequest {
1692        WorkRequest::background(WorkClass::Projection, self.operation_count())
1693    }
1694
1695    pub fn background_work_plan(&self, hint: BackgroundWorkHint) -> Option<BackgroundWorkPlan> {
1696        let operation_count = self.operation_count();
1697        if operation_count == 0 {
1698            return None;
1699        }
1700        Some(BackgroundWorkPlan::background(
1701            WorkClass::Projection,
1702            operation_count,
1703            hint,
1704        ))
1705    }
1706}
1707
1708#[derive(Debug, Clone, PartialEq, Eq)]
1709pub struct SearchProjectionDeltaReport {
1710    pub artifact_type: String,
1711    pub name: String,
1712    pub action: String,
1713    pub before_document_count: usize,
1714    pub after_document_count: usize,
1715    pub upserted_documents: usize,
1716    pub deleted_documents: usize,
1717    pub operation_count: usize,
1718    pub source_graph_commit_epoch_before: Option<u64>,
1719    pub source_graph_commit_epoch_after: Option<u64>,
1720    pub source_graph_commit_epoch_updated: bool,
1721    /// Generation cleanup after the publication that made this delta
1722    /// durable; `None` when the call published nothing.
1723    pub projection_cleanup: Option<SearchProjectionCleanupOutcome>,
1724}
1725
1726#[derive(Debug)]
1727pub struct SearchIndex {
1728    read_generation: Mutex<std::sync::Weak<resident_snapshot::ReadGeneration>>,
1729    read_freshness: Option<Arc<SearchProjectionFreshness>>,
1730    documents: ResidentDocuments,
1731    vector_index_descriptor: Option<hawdb_core::VectorIndexDescriptor>,
1732    vector_scoring: SearchVectorScoring,
1733    vector_document_summary: Option<vector_index::VectorDocumentSummary>,
1734    canonical_vector_source_epoch: Option<u64>,
1735    canonical_vector_delta: Option<vector_index::CanonicalVectorDelta>,
1736    consumer_binding: Option<consumer::ConsumerBinding>,
1737    consumer_binding_valid: bool,
1738    consumer_owner: std::sync::Weak<consumer::MutationOwner>,
1739    consumer_mutation_generation: Option<u64>,
1740    consumer_receipt: Mutex<Option<consumer::CheckpointReceipt>>,
1741    path: Option<PathBuf>,
1742    _project_files: Option<hawdb_storage::file_descriptors::ProjectFileDescriptors>,
1743    embedding_dimension: Option<usize>,
1744    rabitq_checkpoint: Option<(u8, usize, u64)>,
1745    embedding_manifest: Option<SearchEmbeddingManifest>,
1746    import_source_graph_commit_epoch: Option<u64>,
1747    source_graph_commit_epoch: Option<u64>,
1748    durable_source_graph_commit_epoch: Mutex<Option<u64>>,
1749    /// The epoch the loaded snapshot, lexical and vector artifacts are stamped
1750    /// with, when a verified metadata-only advance (#1756) moved
1751    /// `source_graph_commit_epoch` past it. Cleared by the next checkpoint,
1752    /// which restamps every artifact.
1753    artifact_source_graph_commit_epoch: Mutex<Option<u64>>,
1754    marker_lines: Mutex<BTreeMap<String, Vec<String>>>,
1755    analyzer_lexicon: Arc<SearchAnalyzerLexicon>,
1756    lexical_projection: Mutex<Option<Arc<LexicalProjectionReader>>>,
1757    lexical_delta: Mutex<Arc<LexicalMiniDelta>>,
1758    lexical_config: LexicalProjectionConfig,
1759    #[cfg(feature = "vector-search")]
1760    rabitq_projection: Mutex<Option<Arc<RaBitQCandidateProjection>>>,
1761    #[cfg(feature = "vector-search")]
1762    rabitq_build_options: RaBitQCandidateProjectionBuildOptions,
1763    #[cfg(feature = "vector-search")]
1764    resident_diskann: resident_diskann::ResidentDiskAnn,
1765    segment_descriptor: Option<Arc<SearchSegmentDescriptor>>,
1766    segment_payload_reader: Option<Arc<hawdb_storage::scan::FileSegmentRangeReader>>,
1767    range_read_config: SearchRangeReadConfig,
1768    cleanup_state: Mutex<SearchProjectionCleanupState>,
1769    cleanup_options: SearchProjectionCleanupOptions,
1770    runtime_capabilities: RuntimeCapabilities,
1771    telemetry: Option<Arc<dyn TelemetrySink>>,
1772    /// Kinds whose documents only the host writes (#1814). Runtime policy,
1773    /// never persisted here; see [`Self::set_externally_owned_kinds`].
1774    externally_owned_kinds: BTreeSet<SearchProjectionKind>,
1775}
1776
1777impl SearchIndex {
1778    pub fn in_memory() -> Self {
1779        Self::default()
1780    }
1781
1782    pub fn is_persistent(&self) -> bool {
1783        self.path.is_some()
1784    }
1785
1786    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
1787        let project_files =
1788            hawdb_storage::file_descriptors::ProjectFileDescriptors::acquire_component(
1789                path.as_ref(),
1790                true,
1791            )?;
1792        fs::create_dir_all(path.as_ref())?;
1793        let _lease = out_of_core::SearchProjectionPublishLease::acquire(path.as_ref())?;
1794        let mut index = Self::open_under_lease(path.as_ref(), false, &_lease)?;
1795        index._project_files = Some(project_files);
1796        Ok(index)
1797    }
1798
1799    fn open_under_lease(
1800        path: &Path,
1801        registered: bool,
1802        publication: &out_of_core::SearchProjectionPublishLease,
1803    ) -> Result<Self> {
1804        let mut index = Self {
1805            path: Some(path.to_path_buf()),
1806            _project_files: Some(if registered {
1807                publication.with_captured_directory(|directory| {
1808                    hawdb_storage::file_descriptors::ProjectFileDescriptors::from_open_context(
1809                        &directory.operation_context(),
1810                    )
1811                })
1812            } else {
1813                hawdb_storage::file_descriptors::ProjectFileDescriptors::acquire_component(
1814                    path, false,
1815                )?
1816            }),
1817            ..Self::default()
1818        };
1819        let loaded = if registered {
1820            index.load_snapshot_from_publication(publication)
1821        } else {
1822            out_of_core::recover_resident_aliases(path).and_then(|()| index.load_snapshot())
1823        };
1824        loaded.map_err(|error| {
1825            if registered && !matches!(error, HawDBError::FileDescriptors(_)) {
1826                HawDBError::StorageIntegrity(error.to_string())
1827            } else {
1828                error
1829            }
1830        })?;
1831        if index.vector_document_summary.is_some() {
1832            return Err(HawDBError::Storage(
1833                "metadata-only vector Consumers require registered native reopen".into(),
1834            ));
1835        }
1836        let advanced_source_epoch = if registered {
1837            out_of_core::validate_captured_resident_snapshot_identity(&index, publication)?
1838        } else {
1839            out_of_core::validate_resident_snapshot_identity(&index, path)?
1840        };
1841        if index.consumer_binding.is_some() != registered {
1842            return Err(HawDBError::Storage(
1843                "projection consumer lifecycle does not match snapshot binding".into(),
1844            ));
1845        }
1846        if registered {
1847            index
1848                .validate_registered_artifacts(publication)
1849                .map_err(|error| match error {
1850                    HawDBError::FileDescriptors(_) => error,
1851                    _ => HawDBError::StorageIntegrity(error.to_string()),
1852                })?;
1853        } else {
1854            index.load_or_rebuild_segment_descriptor()?;
1855            index.load_lexical_projection()?;
1856        }
1857        #[cfg(feature = "vector-search")]
1858        if registered {
1859            index.load_registered_rabitq_projection(publication)?;
1860        } else {
1861            index.load_rabitq_projection()?;
1862        }
1863        // Every artifact above was validated against its content stamp. Only
1864        // now report the epoch the selector advanced to (#1756).
1865        if let Some(epoch) = advanced_source_epoch {
1866            index.apply_published_epoch_advance(epoch);
1867        }
1868        index.capture_segment_payload_reader(publication)?;
1869        for marker in [FULL_REINDEX_MARKER, METADATA_REPAIR_MARKER] {
1870            let lines = index.read_marker_lines(marker)?;
1871            index
1872                .marker_lines
1873                .get_mut()
1874                .unwrap_or_else(|error| error.into_inner())
1875                .insert(marker.into(), lines);
1876        }
1877        index.retry_projection_cleanup_under_publication(
1878            SearchProjectionCleanupOptions::default(),
1879            publication,
1880        );
1881        Ok(index)
1882    }
1883
1884    /// What a lexical query above the scored-term cap does on this resident
1885    /// index; [`LexicalQueryTermPolicy::Exact`] by default. Under `Exact`,
1886    /// projection-backed search and text seeds refuse such a query, while
1887    /// snapshot-free search scores every analyzed term. Not persisted.
1888    pub fn with_lexical_query_term_policy(mut self, policy: LexicalQueryTermPolicy) -> Self {
1889        self.lexical_config.query_term_policy = policy;
1890        self
1891    }
1892
1893    /// Sets the resident policy in place. Like [`Self::with_lexical_query_term_policy`]
1894    /// it is not persisted: a reopened index starts at `Exact`.
1895    pub fn set_lexical_query_term_policy(&mut self, policy: LexicalQueryTermPolicy) {
1896        self.lexical_config.query_term_policy = policy;
1897    }
1898
1899    pub fn with_analyzer_lexicon(mut self, analyzer_lexicon: SearchAnalyzerLexicon) -> Self {
1900        let _consumer_mutation = self.mark_untracked_consumer_mutation();
1901        self.analyzer_lexicon = Arc::new(analyzer_lexicon);
1902        self.invalidate_lexical_projection();
1903        self
1904    }
1905
1906    pub fn set_analyzer_lexicon(&mut self, analyzer_lexicon: SearchAnalyzerLexicon) {
1907        let _consumer_mutation = self.mark_untracked_consumer_mutation();
1908        self.analyzer_lexicon = Arc::new(analyzer_lexicon);
1909        self.invalidate_lexical_projection();
1910    }
1911
1912    fn lexical_snapshot(&self) -> Option<(Arc<LexicalProjectionReader>, Arc<LexicalMiniDelta>)> {
1913        let projection = self
1914            .lexical_projection
1915            .lock()
1916            .unwrap_or_else(|poisoned| poisoned.into_inner());
1917        let reader = projection.as_ref()?;
1918        // Keep the reader locked until its delta is captured: checkpoint replaces both.
1919        let delta = self
1920            .lexical_delta
1921            .lock()
1922            .unwrap_or_else(|poisoned| poisoned.into_inner())
1923            .clone();
1924        Some((Arc::clone(reader), delta))
1925    }
1926
1927    fn replace_lexical_projection(&self, projection: Option<Arc<LexicalProjectionReader>>) {
1928        // Match snapshot acquisition order and publish the reader and reset together.
1929        let mut current = self
1930            .lexical_projection
1931            .lock()
1932            .unwrap_or_else(|poisoned| poisoned.into_inner());
1933        let mut delta = self
1934            .lexical_delta
1935            .lock()
1936            .unwrap_or_else(|poisoned| poisoned.into_inner());
1937        *current = projection;
1938        *delta = Arc::default();
1939    }
1940
1941    fn invalidate_lexical_projection(&self) {
1942        self.replace_lexical_projection(None);
1943    }
1944
1945    fn load_lexical_projection(&self) -> Result<()> {
1946        let Some(path) = &self.path else {
1947            return Ok(());
1948        };
1949        let projection = LexicalProjectionReader::load(
1950            path,
1951            self.source_graph_commit_epoch,
1952            lexical_analyzer_digest(&self.analyzer_lexicon),
1953            lexical_documents_digest(&self.documents),
1954            self.lexical_config,
1955        )?;
1956        self.replace_lexical_projection(projection);
1957        Ok(())
1958    }
1959
1960    fn load_lexical_projection_under_publication(
1961        &self,
1962        publication: &out_of_core::SearchProjectionPublishLease,
1963    ) -> Result<()> {
1964        let projection = LexicalProjectionReader::load_under_publication(
1965            publication,
1966            self.source_graph_commit_epoch,
1967            lexical_analyzer_digest(&self.analyzer_lexicon),
1968            lexical_documents_digest(&self.documents),
1969            self.lexical_config,
1970        )?;
1971        self.replace_lexical_projection(projection);
1972        Ok(())
1973    }
1974
1975    #[cfg(feature = "vector-search")]
1976    pub fn set_rabitq_projection_build_options(
1977        &mut self,
1978        options: RaBitQCandidateProjectionBuildOptions,
1979    ) {
1980        let _consumer_mutation = self.mark_untracked_consumer_mutation();
1981        self.rabitq_checkpoint = Some((
1982            options.bit_width.bits(),
1983            options.segment_rows,
1984            options.transform_seed,
1985        ));
1986        self.rabitq_build_options = options;
1987        self.invalidate_rabitq_projection();
1988    }
1989
1990    #[cfg(feature = "vector-search")]
1991    fn invalidate_rabitq_projection(&self) {
1992        *self
1993            .rabitq_projection
1994            .lock()
1995            .unwrap_or_else(|poisoned| poisoned.into_inner()) = None;
1996    }
1997
1998    #[cfg(feature = "vector-search")]
1999    fn load_rabitq_projection(&self) -> Result<()> {
2000        let Some(path) = &self.path else {
2001            return Ok(());
2002        };
2003        let artifacts = match rabitq_artifacts_descending(path) {
2004            Ok(artifacts) => artifacts,
2005            Err(error @ HawDBError::FileDescriptors(_)) => return Err(error),
2006            // An optional resident projection can be rebuilt or served by the
2007            // existing exact path. Keep its historical non-resource fallback.
2008            Err(_) => return Ok(()),
2009        };
2010        for (generation, artifact_path) in artifacts {
2011            match resident_diskann::artifact::validate_file(self, &artifact_path, generation) {
2012                Ok(resident_diskann::artifact::Restore::Ready) => return Ok(()),
2013                Ok(resident_diskann::artifact::Restore::Skip) => continue,
2014                Ok(resident_diskann::artifact::Restore::Other) => {}
2015                Err(HawDBError::StorageIntegrity(_)) => {
2016                    if let Some(name) = artifact_path.file_name().and_then(|name| name.to_str()) {
2017                        quarantine_rebuildable_artifact(path, name);
2018                    }
2019                    continue;
2020                }
2021                Err(error) => return Err(error),
2022            }
2023            let identity = self.rabitq_projection_identity(generation);
2024            match RaBitQCandidateProjection::load_from_path_classified(
2025                &artifact_path,
2026                &self.documents,
2027                &identity,
2028            ) {
2029                Ok(projection) => {
2030                    if projection.manifest().metric != self.vector_metric().into() {
2031                        return Err(HawDBError::StorageIntegrity(
2032                            "RaBitQ artifact metric differs from its projection".into(),
2033                        ));
2034                    }
2035                    if let Some(binding) = &self.vector_index_descriptor {
2036                        vector_index::validate_projection(binding, projection.manifest())?;
2037                    }
2038                    *self
2039                        .rabitq_projection
2040                        .lock()
2041                        .unwrap_or_else(|poisoned| poisoned.into_inner()) =
2042                        Some(Arc::new(projection));
2043                    return Ok(());
2044                }
2045                Err(error) if error.should_quarantine() => {
2046                    if let Some(name) = artifact_path.file_name().and_then(|name| name.to_str()) {
2047                        quarantine_rebuildable_artifact(path, name);
2048                    }
2049                }
2050                Err(rabitq_projection::RaBitQCandidateProjectionLoadError::Resource(error)) => {
2051                    return Err(error);
2052                }
2053                Err(_) => {}
2054            }
2055        }
2056        Ok(())
2057    }
2058
2059    #[cfg(feature = "vector-search")]
2060    fn rabitq_projection_identity(
2061        &self,
2062        generation: u64,
2063    ) -> hawdb_vector_projection::ProjectionIdentity {
2064        hawdb_vector_projection::ProjectionIdentity {
2065            generation,
2066            source_epoch: self.source_graph_commit_epoch,
2067            embedding_model: self
2068                .embedding_manifest
2069                .as_ref()
2070                .map(|manifest| manifest.model.clone()),
2071            embedding_version: self
2072                .embedding_manifest
2073                .as_ref()
2074                .and_then(|manifest| manifest.version.clone()),
2075        }
2076    }
2077
2078    #[cfg(feature = "vector-search")]
2079    fn rabitq_projection(&self) -> Option<Arc<RaBitQCandidateProjection>> {
2080        self.rabitq_projection
2081            .lock()
2082            .unwrap_or_else(|poisoned| poisoned.into_inner())
2083            .clone()
2084    }
2085
2086    #[cfg(feature = "vector-search")]
2087    fn rabitq_backend_selected(&self) -> bool {
2088        self.vector_index_descriptor.as_ref().map_or_else(
2089            || self.rabitq_checkpoint.is_some(),
2090            |definition| {
2091                matches!(
2092                    definition.backend(),
2093                    hawdb_core::VectorIndexBackend::RaBitQ { .. }
2094                )
2095            },
2096        )
2097    }
2098
2099    #[cfg(feature = "vector-search")]
2100    fn build_in_memory_rabitq_projection(&self) -> Result<Option<Arc<RaBitQCandidateProjection>>> {
2101        self.build_in_memory_rabitq_projection_with_context(None, None)
2102    }
2103
2104    #[cfg(feature = "vector-search")]
2105    fn lock_rabitq_projection(
2106        &self,
2107        task: Option<&RuntimeTaskContext>,
2108    ) -> Result<std::sync::MutexGuard<'_, Option<Arc<RaBitQCandidateProjection>>>> {
2109        if task.is_none() {
2110            return Ok(self
2111                .rabitq_projection
2112                .lock()
2113                .unwrap_or_else(|error| error.into_inner()));
2114        }
2115        loop {
2116            task.map_or(Ok(()), crate::build_control::checkpoint)?;
2117            match self.rabitq_projection.try_lock() {
2118                Ok(guard) => return Ok(guard),
2119                Err(std::sync::TryLockError::Poisoned(error)) => return Ok(error.into_inner()),
2120                Err(std::sync::TryLockError::WouldBlock) => {
2121                    std::thread::sleep(std::time::Duration::from_millis(1));
2122                }
2123            }
2124        }
2125    }
2126
2127    #[cfg(feature = "vector-search")]
2128    fn build_in_memory_rabitq_projection_with_context(
2129        &self,
2130        task: Option<&RuntimeTaskContext>,
2131        max_working_bytes: Option<usize>,
2132    ) -> Result<Option<Arc<RaBitQCandidateProjection>>> {
2133        task.map_or(Ok(()), crate::build_control::checkpoint)?;
2134        self.vector_scoring
2135            .validate(self.vector_index_descriptor.is_some())?;
2136        // Serialize the first build within a generation. Captured generations
2137        // reserve its complete build/cache capacity before a governed lease is
2138        // returned; concurrent readers must not allocate duplicate projections.
2139        let mut cached = self.lock_rabitq_projection(task)?;
2140        task.map_or(Ok(()), crate::build_control::checkpoint)?;
2141        if let Some(projection) = cached.as_ref() {
2142            return Ok(Some(Arc::clone(projection)));
2143        }
2144        if let Some(available) = max_working_bytes {
2145            let required = RaBitQCandidateProjection::in_memory_capacity_bound_with_context(
2146                &self.documents,
2147                self.rabitq_projection_identity(0),
2148                self.rabitq_build_options,
2149                task,
2150            )?;
2151            task.map_or(Ok(()), crate::build_control::checkpoint)?;
2152            if required > available {
2153                return Err(rabitq_projection::map_projection_error(
2154                    hawdb_vector_projection::ProjectionError::ResourceBudgetExceeded {
2155                        required,
2156                        available,
2157                    },
2158                    "resident RaBitQ build/cache admission",
2159                ));
2160            }
2161        }
2162        let projection = RaBitQCandidateProjection::build_from_view(
2163            &self.documents,
2164            self.rabitq_projection_identity(0),
2165            self.rabitq_build_options,
2166            self.vector_metric(),
2167            task,
2168        )?
2169        .map(Arc::new);
2170        task.map_or(Ok(()), crate::build_control::checkpoint)?;
2171        *cached = projection.clone();
2172        Ok(projection)
2173    }
2174
2175    fn record_lexical_upsert(&self, document: &SearchDocument) {
2176        if self
2177            .lexical_projection
2178            .lock()
2179            .unwrap_or_else(|poisoned| poisoned.into_inner())
2180            .is_none()
2181        {
2182            return;
2183        }
2184        let result = {
2185            let mut delta = self
2186                .lexical_delta
2187                .lock()
2188                .unwrap_or_else(|poisoned| poisoned.into_inner());
2189            delta.upsert(
2190                document,
2191                self.documents.get(&document.id),
2192                &self.analyzer_lexicon,
2193                self.lexical_config,
2194            )
2195        };
2196        if result.is_err() {
2197            self.invalidate_lexical_projection();
2198        }
2199    }
2200
2201    fn record_lexical_delete(&self, document_id: &str) {
2202        if self
2203            .lexical_projection
2204            .lock()
2205            .unwrap_or_else(|poisoned| poisoned.into_inner())
2206            .is_none()
2207        {
2208            return;
2209        }
2210        let admitted = {
2211            let mut delta = self
2212                .lexical_delta
2213                .lock()
2214                .unwrap_or_else(|poisoned| poisoned.into_inner());
2215            delta.delete(
2216                document_id,
2217                self.documents.get(document_id),
2218                &self.analyzer_lexicon,
2219                self.lexical_config,
2220            )
2221        };
2222        if !matches!(admitted, Ok(true)) {
2223            self.invalidate_lexical_projection();
2224        }
2225    }
2226
2227    pub fn set_telemetry_sink(&mut self, telemetry: Option<Arc<dyn TelemetrySink>>) {
2228        let _consumer_mutation = self.mark_untracked_consumer_mutation();
2229        self.telemetry = telemetry;
2230    }
2231
2232    pub fn telemetry_sink_configured(&self) -> bool {
2233        self.telemetry.is_some()
2234    }
2235
2236    pub fn set_range_read_config(&mut self, config: SearchRangeReadConfig) {
2237        let _consumer_mutation = self.mark_untracked_consumer_mutation();
2238        self.range_read_config = config;
2239    }
2240
2241    pub fn range_read_config(&self) -> SearchRangeReadConfig {
2242        self.range_read_config
2243    }
2244
2245    pub fn set_runtime_capabilities(&mut self, capabilities: RuntimeCapabilities) {
2246        let _consumer_mutation = self.mark_untracked_consumer_mutation();
2247        self.runtime_capabilities =
2248            crate::compiled_capabilities::effective_runtime_capabilities(capabilities);
2249    }
2250
2251    pub fn runtime_capabilities(&self) -> RuntimeCapabilities {
2252        self.runtime_capabilities
2253    }
2254
2255    /// Declares kinds whose documents the host supplies itself (#1814).
2256    ///
2257    /// Graph changefeed catch-up applied to this index then derives no rows
2258    /// for nodes of these kinds: their documents are written only by host
2259    /// deltas, and are removed only when the graph node is deleted (or the
2260    /// host deletes them). Graph-derived rows of other kinds and every host
2261    /// delta are unaffected. A full rebuild from the graph carries the current
2262    /// document of every live node of these kinds over unchanged, dropping
2263    /// documents whose node no longer exists, and metadata repair leaves them
2264    /// untouched. Both raise the persisted rows-required fence of a
2265    /// persistent index, so the host re-pushes its rows. The set is not
2266    /// persisted by the index; an embedded store records it with
2267    /// `EmbeddedStoreOpenOptions::with_externally_owned_search_kinds`.
2268    pub fn set_externally_owned_kinds(&mut self, kinds: BTreeSet<SearchProjectionKind>) {
2269        self.externally_owned_kinds = kinds;
2270    }
2271
2272    pub fn externally_owned_kinds(&self) -> &BTreeSet<SearchProjectionKind> {
2273        &self.externally_owned_kinds
2274    }
2275
2276    /// Raises the persisted rows-required fence before a rebuild or metadata
2277    /// repair of a projection with externally owned kinds (#1814).
2278    ///
2279    /// Carry-over keeps the documents the index holds, but host writes that
2280    /// have not reached this index (for example to another directory during
2281    /// an out-of-core rebuild) cannot be proven present, so the host always
2282    /// re-pushes after maintenance. Raising first keeps a failed rebuild
2283    /// fail-safe. An unreadable state fails closed; if a valid state disappears
2284    /// after open, the raise creates a fresh incarnation that rejects retained
2285    /// acknowledgements from the removed state.
2286    fn raise_externally_owned_rows_required(&self) -> Result<()> {
2287        if self.externally_owned_kinds.is_empty() {
2288            return Ok(());
2289        }
2290        let Some(path) = self.path.as_deref() else {
2291            return Ok(());
2292        };
2293        projection_ownership::raise_rows_required(path).map(|_| ())
2294    }
2295
2296    pub fn upsert(&mut self, document: SearchDocument) -> Result<()> {
2297        let _consumer_mutation = self.require_owned_mutation_or_unregistered()?;
2298        if let Some(embedding) = &document.embedding {
2299            vector_index::validate_embedding(
2300                self.vector_index_descriptor.as_ref(),
2301                embedding,
2302                || Ok(()),
2303            )?;
2304            self.validate_or_set_dimension(embedding.len())?;
2305        }
2306        #[cfg(feature = "vector-search")]
2307        self.resident_diskann.record_change(&document.id);
2308        self.record_lexical_upsert(&document);
2309        self.documents.insert(document.id.clone(), document);
2310        #[cfg(feature = "vector-search")]
2311        self.invalidate_rabitq_projection();
2312        self.segment_descriptor = None;
2313        self.segment_payload_reader = None;
2314        Ok(())
2315    }
2316
2317    pub fn upsert_projection_row(&mut self, row: SearchProjectionRow) -> Result<()> {
2318        self.upsert(row.into_document())
2319    }
2320
2321    pub fn delete(&mut self, id: &str) {
2322        let _consumer_mutation = self.mark_untracked_consumer_mutation();
2323        #[cfg(feature = "vector-search")]
2324        self.resident_diskann.record_change(id);
2325        self.record_lexical_delete(id);
2326        self.documents.remove(id);
2327        #[cfg(feature = "vector-search")]
2328        self.invalidate_rabitq_projection();
2329        self.segment_descriptor = None;
2330        self.segment_payload_reader = None;
2331    }
2332
2333    pub fn apply_projection_delta(
2334        &mut self,
2335        delta: SearchProjectionDelta,
2336    ) -> Result<SearchProjectionDeltaReport> {
2337        let _consumer_mutation = self.require_owned_mutation_or_unregistered()?;
2338        let operation_count = delta.operation_count();
2339        if let Some(limit) = delta.max_operations
2340            && operation_count > limit
2341        {
2342            // A per-batch budget refusal, not storage damage (#1924).
2343            return Err(HawDBError::SearchProjectionBatchBudgetExceeded {
2344                budget: hawdb_core::SearchProjectionBatchBudget::ProjectionDelta,
2345                commit_epoch: None,
2346                required_operations: operation_count,
2347                limit,
2348            });
2349        }
2350
2351        let mut next_embedding_dimension = self.embedding_dimension;
2352        for row in &delta.upserts {
2353            let Some(embedding) = &row.embedding else {
2354                continue;
2355            };
2356            let dimension = embedding.len();
2357            vector_index::validate_embedding(
2358                self.vector_index_descriptor.as_ref(),
2359                embedding,
2360                || Ok(()),
2361            )?;
2362            if let Some(manifest) = &self.embedding_manifest
2363                && manifest.dimension != dimension
2364            {
2365                return Err(HawDBError::Storage(format!(
2366                    "embedding dimension mismatch: manifest expects {}, row has {dimension}",
2367                    manifest.dimension
2368                )));
2369            }
2370            match next_embedding_dimension {
2371                Some(existing) if existing != dimension => {
2372                    return Err(HawDBError::Storage(format!(
2373                        "embedding dimension mismatch: index has {existing}, row has {dimension}"
2374                    )));
2375                }
2376                Some(_) => {}
2377                None => next_embedding_dimension = Some(dimension),
2378            }
2379        }
2380
2381        let SearchProjectionDelta {
2382            upserts,
2383            deletes,
2384            max_operations: _,
2385            source_graph_commit_epoch,
2386        } = delta;
2387        let before_document_count = self.documents.len();
2388        let source_graph_commit_epoch_before = self.source_graph_commit_epoch;
2389        let mut deleted_documents = 0;
2390        for id in deletes {
2391            #[cfg(feature = "vector-search")]
2392            self.resident_diskann.record_change(&id);
2393            self.record_lexical_delete(&id);
2394            if self.documents.remove(&id).is_some() {
2395                deleted_documents += 1;
2396            }
2397        }
2398        let upserted_documents = upserts.len();
2399        for row in upserts {
2400            let document = row.into_document();
2401            #[cfg(feature = "vector-search")]
2402            self.resident_diskann.record_change(&document.id);
2403            self.record_lexical_upsert(&document);
2404            self.documents.insert(document.id.clone(), document);
2405        }
2406
2407        #[cfg(feature = "vector-search")]
2408        self.invalidate_rabitq_projection();
2409
2410        self.segment_descriptor = None;
2411        self.segment_payload_reader = None;
2412        self.embedding_dimension = next_embedding_dimension;
2413        let source_graph_commit_epoch_updated = source_graph_commit_epoch.is_some();
2414        if let Some(epoch) = source_graph_commit_epoch {
2415            self.source_graph_commit_epoch = Some(epoch);
2416        }
2417        let source_graph_commit_epoch_after = self.source_graph_commit_epoch;
2418        Ok(SearchProjectionDeltaReport {
2419            artifact_type: "search_projection".to_string(),
2420            name: "search_projection".to_string(),
2421            action: "incremental_update".to_string(),
2422            before_document_count,
2423            after_document_count: self.documents.len(),
2424            upserted_documents,
2425            deleted_documents,
2426            operation_count,
2427            source_graph_commit_epoch_before,
2428            source_graph_commit_epoch_after,
2429            source_graph_commit_epoch_updated,
2430            projection_cleanup: None,
2431        })
2432    }
2433
2434    pub fn apply_background_projection_delta(
2435        &mut self,
2436        policy: &LocalQosPolicy,
2437        state: &LocalQosState,
2438        delta: SearchProjectionDelta,
2439    ) -> Result<SearchProjectionDeltaReport> {
2440        self.runtime_capabilities
2441            .require(RuntimeCapability::BackgroundMaintenance)?;
2442        policy.admit_or_refuse(state, &delta.background_work_request())?;
2443        self.apply_projection_delta(delta)
2444    }
2445
2446    pub fn apply_scheduled_background_projection_delta(
2447        &mut self,
2448        scheduler: &LocalQosScheduler,
2449        delta: SearchProjectionDelta,
2450    ) -> Result<SearchProjectionDeltaReport> {
2451        self.runtime_capabilities
2452            .require(RuntimeCapability::BackgroundMaintenance)?;
2453        let permit = scheduler.try_start_or_refuse(delta.background_work_request())?;
2454
2455        let result = self.apply_projection_delta(delta);
2456        permit.finish_with_outcome(result.is_ok());
2457        result
2458    }
2459
2460    pub fn document(&self, id: &str) -> Option<&SearchDocument> {
2461        self.documents.get(id)
2462    }
2463
2464    pub fn document_count(&self) -> usize {
2465        self.vector_document_summary
2466            .map_or(self.documents.len(), |summary| summary.document_count)
2467    }
2468
2469    /// The largest eligible-set size an exact vector-only read of this
2470    /// resident index under `working_bytes` is guaranteed to serve, for
2471    /// eligible document IDs of at most `max_document_id_bytes` bytes. Raw
2472    /// candidates retain a geometrically grown vector (at most two slots per
2473    /// candidate) plus their IDs; a raw rerank also keeps a lookup over every
2474    /// indexed document and two ID copies per candidate. A larger read may be
2475    /// refused; it is never truncated.
2476    pub fn exact_vector_search_capacity(
2477        &self,
2478        working_bytes: usize,
2479        max_document_id_bytes: usize,
2480    ) -> usize {
2481        resident_exact_vector_search_capacity(
2482            self.document_count(),
2483            working_bytes,
2484            max_document_id_bytes,
2485        )
2486    }
2487
2488    /// Returns vector-bearing document IDs accepted by HawDB's metadata
2489    /// predicate implementation. This validation surface keeps differential
2490    /// oracles aligned with serving filter semantics.
2491    #[cfg(feature = "qualification")]
2492    #[doc(hidden)]
2493    pub fn vector_document_ids_matching_filters_for_validation(
2494        &self,
2495        filters: &BTreeMap<String, String>,
2496    ) -> BTreeSet<String> {
2497        let predicate_pushdown = search_metadata_predicate_pushdown(filters);
2498        self.documents
2499            .values()
2500            .filter(|document| {
2501                document.embedding.is_some()
2502                    && search_document_matches_predicates(document, &predicate_pushdown.predicates)
2503            })
2504            .map(|document| document.id.clone())
2505            .collect()
2506    }
2507
2508    pub fn embedding_manifest(&self) -> Option<&SearchEmbeddingManifest> {
2509        self.embedding_manifest.as_ref()
2510    }
2511
2512    pub fn projection_freshness(&self) -> SearchProjectionFreshness {
2513        if let Some(freshness) = &self.read_freshness {
2514            return freshness.as_ref().clone();
2515        }
2516        let full_reindex_reasons = self
2517            .read_marker_lines(FULL_REINDEX_MARKER)
2518            .unwrap_or_default();
2519        let metadata_repair_reasons = self
2520            .read_marker_lines(METADATA_REPAIR_MARKER)
2521            .unwrap_or_default();
2522        self.freshness_with_reasons(full_reindex_reasons, metadata_repair_reasons)
2523    }
2524
2525    fn freshness_with_reasons(
2526        &self,
2527        full_reindex_reasons: Vec<String>,
2528        metadata_repair_reasons: Vec<String>,
2529    ) -> SearchProjectionFreshness {
2530        let durable_source_graph_commit_epoch = *self
2531            .durable_source_graph_commit_epoch
2532            .lock()
2533            .unwrap_or_else(|poisoned| poisoned.into_inner());
2534        SearchProjectionFreshness {
2535            document_count: self.document_count(),
2536            import_source_graph_commit_epoch: self.import_source_graph_commit_epoch,
2537            source_graph_commit_epoch: self.source_graph_commit_epoch,
2538            durable_source_graph_commit_epoch,
2539            has_uncheckpointed_changes: self.source_graph_commit_epoch
2540                != durable_source_graph_commit_epoch,
2541            full_reindex_needed: !full_reindex_reasons.is_empty(),
2542            full_reindex_reasons,
2543            metadata_repair_needed: !metadata_repair_reasons.is_empty(),
2544            metadata_repair_reasons,
2545            embedding_model: self
2546                .embedding_manifest
2547                .as_ref()
2548                .map(|manifest| manifest.model.clone()),
2549            embedding_version: self
2550                .embedding_manifest
2551                .as_ref()
2552                .and_then(|manifest| manifest.version.clone()),
2553            embedding_dimension: self
2554                .embedding_manifest
2555                .as_ref()
2556                .map(|manifest| manifest.dimension)
2557                .or(self.embedding_dimension),
2558        }
2559    }
2560
2561    /// Records immutable provenance for an external graph bootstrap. The
2562    /// mutable local projection cursor remains independent.
2563    pub fn record_import_source_graph_commit_epoch(&mut self, epoch: u64) -> Result<()> {
2564        let _consumer_mutation = self.require_owned_mutation_or_unregistered()?;
2565        self.validate_import_source_graph_commit_epoch(epoch)?;
2566        self.import_source_graph_commit_epoch = Some(epoch);
2567        Ok(())
2568    }
2569
2570    /// Verifies that an import retry still belongs to the same frozen legacy
2571    /// source without changing the in-memory projection state.
2572    pub fn validate_import_source_graph_commit_epoch(&self, epoch: u64) -> Result<()> {
2573        match self.import_source_graph_commit_epoch {
2574            Some(existing) if existing != epoch => Err(HawDBError::Storage(
2575                "search projection import provenance conflicts with existing source".to_string(),
2576            )),
2577            Some(_) | None => Ok(()),
2578        }
2579    }
2580
2581    pub fn nowledge_search_projection_probe_json(
2582        &self,
2583        options: SearchProjectionProbeOptions,
2584    ) -> serde_json::Value {
2585        let freshness = self.projection_freshness();
2586        let table_reports =
2587            search_projection_probe_table_reports(&self.documents, freshness.embedding_dimension);
2588        let manifest = self.embedding_manifest.as_ref();
2589        let model = manifest.map(|manifest| manifest.model.as_str());
2590        let dimension = manifest
2591            .map(|manifest| manifest.dimension)
2592            .or(freshness.embedding_dimension);
2593        let active_model = options.active_embedding_model.as_deref().or(model);
2594        let active_dimension = options.active_embedding_dimension.or(dimension);
2595        let model_matches = model.is_some() && model == active_model;
2596        let dimension_matches = dimension.is_some() && dimension == active_dimension;
2597        let has_documents = !self.documents.is_empty();
2598        let has_text = self
2599            .documents
2600            .values()
2601            .any(|document| !document.title.is_empty() || !document.content.is_empty());
2602        let has_vector = self
2603            .documents
2604            .values()
2605            .any(|document| document.embedding.is_some());
2606        let predicate_pushdown = search_projection_probe_predicate_pushdown_report(self);
2607        let production_filter_pruning =
2608            search_projection_probe_production_filter_pruning_report(self);
2609        let compressed_vector_projection =
2610            search_projection_probe_compressed_vector_projection_report(self);
2611        let generation_cleanup = self.projection_cleanup_report();
2612        let mut blocker_codes = search_projection_probe_blocker_codes(
2613            has_documents,
2614            has_text,
2615            has_vector,
2616            manifest.is_some(),
2617            model_matches,
2618            dimension_matches,
2619            &freshness,
2620        );
2621        if generation_cleanup.retry_required {
2622            blocker_codes.push("projection_generation_cleanup_pending".to_string());
2623            blocker_codes.sort();
2624        }
2625
2626        serde_json::json!({
2627            "protocol": "hawdb-nowledge-search-projection-probe",
2628            "derived_projection": true,
2629            "document_count": self.documents.len(),
2630            "document_identity": search_projection_probe_document_identity_report(&self.documents),
2631            "tables": table_reports,
2632            "embedding_manifest": {
2633                "model": model,
2634                "version": manifest.and_then(|manifest| manifest.version.as_deref()),
2635                "dimension": dimension,
2636                "active_model": active_model,
2637                "active_dimension": active_dimension,
2638                "model_matches": model_matches,
2639                "dimension_matches": dimension_matches,
2640            },
2641            "fail_soft": {
2642                "fts_to_vector_ready": has_vector,
2643                "vector_to_fts_ready": has_text,
2644                "no_500_on_leg_failure": has_documents,
2645            },
2646            "lifecycle": {
2647                "rebuild_marker_ready": !freshness.full_reindex_needed,
2648                "metadata_repair_marker_ready": !freshness.metadata_repair_needed,
2649                "generation_cleanup_ready": !generation_cleanup.retry_required,
2650                "full_reindex_needed": freshness.full_reindex_needed,
2651                "full_reindex_reasons": freshness.full_reindex_reasons,
2652                "metadata_repair_needed": freshness.metadata_repair_needed,
2653                "metadata_repair_reasons": freshness.metadata_repair_reasons,
2654                "source_graph_commit_epoch": freshness.source_graph_commit_epoch,
2655            },
2656            "generation_cleanup": generation_cleanup.json(),
2657            "incremental_update": {
2658                "ready": has_documents && freshness.durable_source_graph_commit_epoch.is_some(),
2659                "upsert_ready": has_documents,
2660                "delete_ready": has_documents,
2661                "watermark_ready": freshness.durable_source_graph_commit_epoch.is_some(),
2662                "source_graph_commit_epoch": freshness.source_graph_commit_epoch,
2663                "durable_source_graph_commit_epoch": freshness.durable_source_graph_commit_epoch,
2664                "has_uncheckpointed_changes": freshness.has_uncheckpointed_changes,
2665            },
2666            "compressed_vector_projection": compressed_vector_projection,
2667            "predicate_pushdown": predicate_pushdown,
2668            "production_filter_pruning": production_filter_pruning,
2669            "blocker_codes": blocker_codes,
2670        })
2671    }
2672
2673    pub fn apply_embedding_manifest(&mut self, manifest: SearchEmbeddingManifest) -> Result<()> {
2674        let _consumer_mutation = self.require_owned_mutation_or_unregistered()?;
2675        if let Some(existing) = &self.embedding_manifest {
2676            if existing == &manifest {
2677                return Ok(());
2678            }
2679            self.mark_full_reindex_needed(&format!(
2680                "embedding manifest changed from {} to {}",
2681                format_embedding_manifest(existing),
2682                format_embedding_manifest(&manifest)
2683            ))?;
2684        } else if !self.documents.is_empty() {
2685            self.mark_full_reindex_needed(&format!(
2686                "embedding manifest initialized as {} for existing projection",
2687                format_embedding_manifest(&manifest)
2688            ))?;
2689        }
2690        self.embedding_dimension = Some(manifest.dimension);
2691        self.embedding_manifest = Some(manifest);
2692        #[cfg(feature = "vector-search")]
2693        self.resident_diskann.reset();
2694        #[cfg(feature = "vector-search")]
2695        self.invalidate_rabitq_projection();
2696        Ok(())
2697    }
2698
2699    pub fn rebuild_from_graph<S: SearchProjectionSource + ?Sized>(
2700        &mut self,
2701        catalog: &Catalog,
2702        store: &S,
2703        options: SearchRebuildOptions,
2704    ) -> Result<SearchRebuildSummary> {
2705        let _consumer_mutation = self.require_owned_mutation_or_unregistered()?;
2706        self.raise_externally_owned_rows_required()?;
2707        let started = hawdb_core::time::Instant::now();
2708        let mut next_documents = BTreeMap::new();
2709        let mut scanned_nodes = 0;
2710
2711        let result = (|| {
2712            let business_labels_by_node = store.projection_business_labels_by_node(catalog)?;
2713            store.visit_projection_nodes(&mut |node| {
2714                scanned_nodes += 1;
2715                let Some(row) = projection_row_from_node_with_business_labels(
2716                    catalog,
2717                    &node,
2718                    business_labels_by_node
2719                        .get(&node.id)
2720                        .map(Vec::as_slice)
2721                        .unwrap_or_default(),
2722                ) else {
2723                    return Ok(());
2724                };
2725                // The host is the only writer of owned kinds: carry its
2726                // current document over for a live node instead of deriving
2727                // one. Documents of nodes that no longer exist are dropped.
2728                let owned = self.externally_owned_kinds.contains(&row.kind);
2729                let carried = owned
2730                    .then(|| {
2731                        self.documents
2732                            .get(&format!("{}:{}", row.kind.as_str(), row.external_id))
2733                            .cloned()
2734                    })
2735                    .flatten();
2736                if owned && carried.is_none() {
2737                    return Ok(());
2738                }
2739                if options
2740                    .max_rows
2741                    .map(|limit| next_documents.len() >= limit)
2742                    .unwrap_or(false)
2743                {
2744                    self.mark_full_reindex_needed("full rebuild exceeded configured row limit")?;
2745                    return Err(HawDBError::Storage(format!(
2746                        "full rebuild exceeded configured row limit after {} documents",
2747                        next_documents.len()
2748                    )));
2749                }
2750                let document = carried.unwrap_or_else(|| row.into_document());
2751                next_documents.insert(document.id.clone(), document);
2752                Ok(())
2753            })?;
2754
2755            self.documents = next_documents.into();
2756            self.segment_descriptor = None;
2757            self.segment_payload_reader = None;
2758            #[cfg(feature = "vector-search")]
2759            self.resident_diskann.reset();
2760            self.invalidate_lexical_projection();
2761            #[cfg(feature = "vector-search")]
2762            self.invalidate_rabitq_projection();
2763            self.source_graph_commit_epoch = Some(store.source_graph_commit_epoch());
2764            self.embedding_dimension = self
2765                .embedding_manifest
2766                .as_ref()
2767                .map(|manifest| manifest.dimension);
2768            self.clear_marker(FULL_REINDEX_MARKER)?;
2769            self.clear_marker(METADATA_REPAIR_MARKER)?;
2770            Ok(SearchRebuildSummary {
2771                scanned_nodes,
2772                indexed_documents: self.documents.len(),
2773            })
2774        })();
2775        if let Some(telemetry) = &self.telemetry {
2776            telemetry.record_kernel(KernelTelemetry {
2777                operation: KernelTelemetryOperation::IndexMaintenance,
2778                success: result.is_ok(),
2779                elapsed_micros: elapsed_micros(started),
2780                item_count: scanned_nodes,
2781                byte_count: 0,
2782                fsync_micros: 0,
2783                generation: None,
2784            });
2785        }
2786        result
2787    }
2788
2789    pub fn rebuild_derived_artifacts<S: SearchProjectionSource + ?Sized>(
2790        &mut self,
2791        catalog: &Catalog,
2792        store: &S,
2793        options: SearchRebuildOptions,
2794    ) -> Result<SearchDerivedArtifactReport> {
2795        let before_document_count = self.documents.len();
2796        let summary = self.rebuild_from_graph(catalog, store, options)?;
2797        let freshness = self.projection_freshness();
2798        Ok(SearchDerivedArtifactReport {
2799            artifact_type: "search_projection".to_string(),
2800            name: "search_projection".to_string(),
2801            action: "rebuilt".to_string(),
2802            before_document_count,
2803            after_document_count: self.documents.len(),
2804            scanned_nodes: summary.scanned_nodes,
2805            indexed_documents: summary.indexed_documents,
2806            full_reindex_needed: freshness.full_reindex_needed,
2807            full_reindex_reasons: freshness.full_reindex_reasons,
2808            metadata_repair_needed: freshness.metadata_repair_needed,
2809            metadata_repair_reasons: freshness.metadata_repair_reasons,
2810        })
2811    }
2812
2813    pub fn rebuild_background_work_plan<S: SearchProjectionSource + ?Sized>(
2814        &self,
2815        store: &S,
2816        hint: BackgroundWorkHint,
2817    ) -> Option<BackgroundWorkPlan> {
2818        let estimated_operations = self.rebuild_estimated_operations(store);
2819        if estimated_operations == 0 {
2820            return None;
2821        }
2822        Some(BackgroundWorkPlan::background(
2823            WorkClass::Projection,
2824            estimated_operations,
2825            hint,
2826        ))
2827    }
2828
2829    pub fn rebuild_background_derived_artifacts<S: SearchProjectionSource + ?Sized>(
2830        &mut self,
2831        policy: &LocalQosPolicy,
2832        state: &LocalQosState,
2833        catalog: &Catalog,
2834        store: &S,
2835        options: SearchRebuildOptions,
2836    ) -> Result<SearchDerivedArtifactReport> {
2837        self.runtime_capabilities
2838            .require(RuntimeCapability::BackgroundMaintenance)?;
2839        let request = WorkRequest::background(
2840            WorkClass::Projection,
2841            self.rebuild_estimated_operations(store),
2842        );
2843        policy.admit_or_refuse(state, &request)?;
2844        self.rebuild_derived_artifacts(catalog, store, options)
2845    }
2846
2847    pub fn rebuild_scheduled_background_derived_artifacts<S: SearchProjectionSource + ?Sized>(
2848        &mut self,
2849        scheduler: &LocalQosScheduler,
2850        catalog: &Catalog,
2851        store: &S,
2852        options: SearchRebuildOptions,
2853    ) -> Result<SearchDerivedArtifactReport> {
2854        self.runtime_capabilities
2855            .require(RuntimeCapability::BackgroundMaintenance)?;
2856        let request = WorkRequest::background(
2857            WorkClass::Projection,
2858            self.rebuild_estimated_operations(store),
2859        );
2860        let permit = scheduler.try_start_or_refuse(request)?;
2861
2862        let result = self.rebuild_derived_artifacts(catalog, store, options);
2863        permit.finish_with_outcome(result.is_ok());
2864        result
2865    }
2866
2867    pub fn repair_metadata_from_graph<S: SearchProjectionSource + ?Sized>(
2868        &mut self,
2869        catalog: &Catalog,
2870        store: &S,
2871        options: MetadataRepairOptions,
2872    ) -> Result<MetadataRepairSummary> {
2873        let _consumer_mutation = self.require_owned_mutation_or_unregistered()?;
2874        self.raise_externally_owned_rows_required()?;
2875        let started = hawdb_core::time::Instant::now();
2876        let mut repairs = Vec::new();
2877        let mut scanned_nodes = 0;
2878        let mut missing_documents = 0;
2879
2880        let result = (|| {
2881            let business_labels_by_node = store.projection_business_labels_by_node(catalog)?;
2882            store.visit_projection_nodes(&mut |node| {
2883                scanned_nodes += 1;
2884                let Some(row) = projection_row_from_node_with_business_labels(
2885                    catalog,
2886                    &node,
2887                    business_labels_by_node
2888                        .get(&node.id)
2889                        .map(Vec::as_slice)
2890                        .unwrap_or_default(),
2891                ) else {
2892                    return Ok(());
2893                };
2894                // The host owns these documents' metadata as well.
2895                if self.externally_owned_kinds.contains(&row.kind) {
2896                    return Ok(());
2897                }
2898                let document = row.into_document();
2899                if !self.documents.contains_key(&document.id) {
2900                    missing_documents += 1;
2901                    return Ok(());
2902                }
2903                if options
2904                    .max_rows
2905                    .map(|limit| repairs.len() >= limit)
2906                    .unwrap_or(false)
2907                {
2908                    self.mark_metadata_repair_needed(
2909                        "metadata repair exceeded configured row limit",
2910                    )?;
2911                    return Err(HawDBError::Storage(format!(
2912                        "metadata repair exceeded configured row limit after {} documents",
2913                        repairs.len()
2914                    )));
2915                }
2916                repairs.push((document.id, document.metadata));
2917                Ok(())
2918            })?;
2919
2920            let repaired_documents = repairs.len();
2921            let mut repaired_projection_documents = Vec::with_capacity(repaired_documents);
2922            for (id, metadata) in repairs {
2923                if let Some(existing) = self.documents.get(&id) {
2924                    let mut repaired = existing.clone();
2925                    repaired.metadata = metadata;
2926                    repaired_projection_documents.push(repaired);
2927                }
2928            }
2929            for document in &repaired_projection_documents {
2930                self.record_lexical_upsert(document);
2931            }
2932            for document in repaired_projection_documents {
2933                self.documents.insert(document.id.clone(), document);
2934            }
2935            self.segment_descriptor = None;
2936            self.segment_payload_reader = None;
2937            if missing_documents > 0 {
2938                self.mark_full_reindex_needed("metadata repair found missing projection rows")?;
2939            }
2940            self.clear_marker(METADATA_REPAIR_MARKER)?;
2941            Ok(MetadataRepairSummary {
2942                scanned_nodes,
2943                repaired_documents,
2944                missing_documents,
2945            })
2946        })();
2947        if let Some(telemetry) = &self.telemetry {
2948            telemetry.record_kernel(KernelTelemetry {
2949                operation: KernelTelemetryOperation::IndexMaintenance,
2950                success: result.is_ok(),
2951                elapsed_micros: elapsed_micros(started),
2952                item_count: scanned_nodes,
2953                byte_count: 0,
2954                fsync_micros: 0,
2955                generation: None,
2956            });
2957        }
2958        result
2959    }
2960
2961    pub fn metadata_repair_background_work_plan<S: SearchProjectionSource + ?Sized>(
2962        &self,
2963        store: &S,
2964        hint: BackgroundWorkHint,
2965    ) -> Option<BackgroundWorkPlan> {
2966        let estimated_operations = store.estimated_projection_node_count();
2967        if estimated_operations == 0 {
2968            return None;
2969        }
2970        Some(BackgroundWorkPlan::background(
2971            WorkClass::Projection,
2972            estimated_operations,
2973            hint,
2974        ))
2975    }
2976
2977    pub fn repair_background_metadata_from_graph<S: SearchProjectionSource + ?Sized>(
2978        &mut self,
2979        policy: &LocalQosPolicy,
2980        state: &LocalQosState,
2981        catalog: &Catalog,
2982        store: &S,
2983        options: MetadataRepairOptions,
2984        estimated_operations: usize,
2985    ) -> Result<MetadataRepairSummary> {
2986        self.runtime_capabilities
2987            .require(RuntimeCapability::BackgroundMaintenance)?;
2988        let request = WorkRequest::background(WorkClass::Projection, estimated_operations);
2989        policy.admit_or_refuse(state, &request)?;
2990        self.repair_metadata_from_graph(catalog, store, options)
2991    }
2992
2993    pub fn repair_scheduled_background_metadata_from_graph<S: SearchProjectionSource + ?Sized>(
2994        &mut self,
2995        scheduler: &LocalQosScheduler,
2996        catalog: &Catalog,
2997        store: &S,
2998        options: MetadataRepairOptions,
2999        estimated_operations: usize,
3000    ) -> Result<MetadataRepairSummary> {
3001        self.runtime_capabilities
3002            .require(RuntimeCapability::BackgroundMaintenance)?;
3003        let request = WorkRequest::background(WorkClass::Projection, estimated_operations);
3004        let permit = scheduler.try_start_or_refuse(request)?;
3005
3006        let result = self.repair_metadata_from_graph(catalog, store, options);
3007        permit.finish_with_outcome(result.is_ok());
3008        result
3009    }
3010
3011    fn rebuild_estimated_operations<S: SearchProjectionSource + ?Sized>(&self, store: &S) -> usize {
3012        store
3013            .estimated_projection_node_count()
3014            .max(self.documents.len())
3015    }
3016
3017    /// Limits for the generation cleanup that runs after every checkpoint.
3018    /// Not persisted: a reopened index starts at the defaults.
3019    pub fn set_projection_cleanup_options(&mut self, options: SearchProjectionCleanupOptions) {
3020        self.cleanup_options = options;
3021    }
3022
3023    pub fn projection_cleanup_options(&self) -> SearchProjectionCleanupOptions {
3024        self.cleanup_options
3025    }
3026
3027    pub fn projection_cleanup_report(&self) -> SearchProjectionCleanupReport {
3028        self.cleanup_state
3029            .lock()
3030            .unwrap_or_else(|poisoned| poisoned.into_inner())
3031            .report()
3032    }
3033
3034    pub fn retry_projection_cleanup(
3035        &self,
3036        options: SearchProjectionCleanupOptions,
3037    ) -> SearchProjectionCleanupReport {
3038        let Some(path) = &self.path else {
3039            return self.projection_cleanup_report();
3040        };
3041        if self.consumer_binding_valid
3042            && self.consumer_binding.is_some()
3043            && let Ok(consumer_mutation) = self.borrow_consumer_mutation()
3044        {
3045            return self.retry_projection_cleanup_under_publication(
3046                options,
3047                consumer_mutation.publication(),
3048            );
3049        }
3050        let Ok(_publication) = out_of_core::SearchProjectionPublishLease::acquire_for_cleanup(path)
3051        else {
3052            return self
3053                .cleanup_state
3054                .lock()
3055                .unwrap_or_else(|poisoned| poisoned.into_inner())
3056                .defer_for_publication(options);
3057        };
3058        self.retry_projection_cleanup_under_publication(options, &_publication)
3059    }
3060
3061    // Caller retains the same root's publication authority through discovery
3062    // and sweep. Checkpoint already owns that authority and must not reacquire.
3063    fn retry_projection_cleanup_under_publication(
3064        &self,
3065        options: SearchProjectionCleanupOptions,
3066        publication: &out_of_core::SearchProjectionPublishLease,
3067    ) -> SearchProjectionCleanupReport {
3068        let Some(path) = &self.path else {
3069            return self.projection_cleanup_report();
3070        };
3071        self.cleanup_state
3072            .lock()
3073            .unwrap_or_else(|poisoned| poisoned.into_inner())
3074            .run_under_publication(path, options, publication, &self.analyzer_lexicon, None)
3075    }
3076
3077    pub fn checkpoint(&self) -> Result<()> {
3078        self.checkpoint_with_report().map(|_| ())
3079    }
3080
3081    pub fn checkpoint_with_report(&self) -> Result<SearchCheckpointReport> {
3082        self.require_unregistered_publication()?;
3083        self.checkpoint_with_lease(None)
3084    }
3085
3086    fn checkpoint_with_lease(
3087        &self,
3088        publication: Option<&out_of_core::SearchProjectionPublishLease>,
3089    ) -> Result<SearchCheckpointReport> {
3090        self.checkpoint_with_task(publication, &RuntimeTaskContext::default())
3091    }
3092
3093    fn checkpoint_with_task(
3094        &self,
3095        publication: Option<&out_of_core::SearchProjectionPublishLease>,
3096        task: &RuntimeTaskContext,
3097    ) -> Result<SearchCheckpointReport> {
3098        self.vector_scoring
3099            .validate(self.vector_index_descriptor.is_some())?;
3100        let Some(path) = &self.path else {
3101            return Ok(SearchCheckpointReport::in_memory(self.documents.len()));
3102        };
3103        task.checkpoint().map_err(HawDBError::RuntimeTaskStopped)?;
3104        let _io = task
3105            .acquire_io_wave(NonZeroUsize::MIN)
3106            .map_err(HawDBError::from_execution_error)?;
3107        let memory = build_memory::BuildMemory::new(task)?;
3108        let started = hawdb_core::time::Instant::now();
3109        let result = (|| {
3110            let owned_publication = if publication.is_some() {
3111                None
3112            } else {
3113                Some(out_of_core::SearchProjectionPublishLease::acquire(path)?)
3114            };
3115            let publication_lease = publication
3116                .or(owned_publication.as_ref())
3117                .expect("checkpoint retains publication authority");
3118            // Unregistered resident checkpoints write every artifact under a
3119            // generation name and commit with the manifest rename. Registered
3120            // Consumers keep their legacy order; their own publication record
3121            // selects the producer closure.
3122            let deferred_aliases = self.consumer_binding.is_none();
3123            if deferred_aliases {
3124                // `open` may have created this directory without persisting
3125                // its entry; a durable selector inside it must not vanish.
3126                hawdb_storage::durability::sync_directory_ancestors(path)?;
3127            }
3128            let write_snapshot = |target: &Path| {
3129                snapshot_writer::write_search_snapshot_with_context(
3130                    target,
3131                    snapshot_writer::SearchSnapshotMetadata {
3132                        source_graph_commit_epoch: self.source_graph_commit_epoch,
3133                        import_source_graph_commit_epoch: self.import_source_graph_commit_epoch,
3134                        embedding_manifest: self.embedding_manifest.as_ref(),
3135                        embedding_dimension: self.embedding_dimension,
3136                        consumer_binding: self.consumer_binding.as_ref(),
3137                        vector_index_descriptor: self.vector_index_descriptor.as_ref(),
3138                        vector_scoring: self.vector_scoring,
3139                        vector_document_summary: None,
3140                        canonical_vector_source_epoch: None,
3141                        rabitq_checkpoint: self.rabitq_checkpoint,
3142                    },
3143                    self.documents.values(),
3144                    &memory,
3145                    task,
3146                )
3147            };
3148            let legacy_snapshot = if deferred_aliases {
3149                None
3150            } else {
3151                Some(write_snapshot(&path.join(SEARCH_SNAPSHOT_FILE))?)
3152            };
3153            let generation =
3154                out_of_core::next_generation(path, self.lexical_config.max_manifest_bytes.get())?;
3155            #[cfg(feature = "vector-search")]
3156            let (generation, rabitq_bytes_written, rabitq) =
3157                self.write_rabitq_projection(path, generation, task, publication_lease)?;
3158            #[cfg(not(feature = "vector-search"))]
3159            let rabitq_bytes_written = 0;
3160            #[cfg(test)]
3161            out_of_core::resident_checkpoint_fault(out_of_core::ResidentCheckpointStep::RaBitQ)?;
3162            let snapshot = match legacy_snapshot {
3163                Some(snapshot) => snapshot,
3164                None => write_snapshot(&path.join(resident_snapshot_file(generation)))?,
3165            };
3166            #[cfg(test)]
3167            out_of_core::resident_checkpoint_fault(out_of_core::ResidentCheckpointStep::Snapshot)?;
3168            let publication = out_of_core::write_resident_artifacts(
3169                self,
3170                path,
3171                &snapshot,
3172                out_of_core::ResidentPublicationPlan {
3173                    generation,
3174                    deferred_aliases,
3175                    #[cfg(feature = "vector-search")]
3176                    rabitq,
3177                },
3178                task,
3179            )?;
3180            let projection_bytes_written = publication
3181                .bytes_written
3182                .saturating_add(rabitq_bytes_written);
3183            *self
3184                .durable_source_graph_commit_epoch
3185                .lock()
3186                .unwrap_or_else(|poisoned| poisoned.into_inner()) = self.source_graph_commit_epoch;
3187            // Every published artifact now carries the current epoch.
3188            *self
3189                .artifact_source_graph_commit_epoch
3190                .lock()
3191                .unwrap_or_else(|poisoned| poisoned.into_inner()) = None;
3192            #[cfg(test)]
3193            out_of_core::resident_checkpoint_fault(out_of_core::ResidentCheckpointStep::Cleanup)?;
3194            let cleanup = self.retry_projection_cleanup_under_publication(
3195                self.cleanup_options,
3196                publication_lease,
3197            );
3198            if let Some(binding) = &self.consumer_binding {
3199                *self
3200                    .consumer_receipt
3201                    .lock()
3202                    .unwrap_or_else(|error| error.into_inner()) =
3203                    Some(consumer::CheckpointReceipt {
3204                        binding: binding.clone(),
3205                        source_epoch: self.source_graph_commit_epoch.ok_or_else(|| {
3206                            HawDBError::Storage("registered checkpoint missing source epoch".into())
3207                        })?,
3208                        encoded_len: snapshot.encoded_len,
3209                        sha256: snapshot.encoded_sha256.to_string(),
3210                    });
3211            }
3212            Ok(snapshot.finish(
3213                publication.generation,
3214                projection_bytes_written,
3215                Some(SearchProjectionCleanupOutcome::from(&cleanup)),
3216            ))
3217        })();
3218        if let Some(telemetry) = &self.telemetry {
3219            let (byte_count, generation) = result
3220                .as_ref()
3221                .map(|report| {
3222                    (
3223                        report
3224                            .snapshot_compressed_bytes
3225                            .saturating_add(report.projection_bytes_written),
3226                        Some(report.projection_generation),
3227                    )
3228                })
3229                .unwrap_or((0, None));
3230            telemetry.record_kernel(KernelTelemetry {
3231                operation: KernelTelemetryOperation::SearchCheckpoint,
3232                success: result.is_ok(),
3233                elapsed_micros: elapsed_micros(started),
3234                item_count: self.documents.len(),
3235                byte_count,
3236                fsync_micros: 0,
3237                generation,
3238            });
3239        }
3240        result
3241    }
3242
3243    #[cfg(feature = "vector-search")]
3244    fn write_rabitq_projection(
3245        &self,
3246        path: &Path,
3247        minimum_generation: u64,
3248        task: &RuntimeTaskContext,
3249        publication: &out_of_core::SearchProjectionPublishLease,
3250    ) -> Result<(u64, u64, Option<out_of_core::ResidentRaBitQArtifact>)> {
3251        if self
3252            .documents
3253            .values()
3254            .all(|document| document.embedding.is_none())
3255        {
3256            self.invalidate_rabitq_projection();
3257            return Ok((minimum_generation, 0, None));
3258        }
3259        let loaded_generation = self
3260            .rabitq_projection()
3261            .map(|projection| projection.manifest().identity.generation)
3262            .unwrap_or(0);
3263        let artifact_generation = latest_rabitq_artifact(path)?
3264            .map(|(generation, _)| generation)
3265            .unwrap_or(0);
3266        let generation = minimum_generation
3267            .max(loaded_generation.saturating_add(1))
3268            .max(artifact_generation.saturating_add(1));
3269        let artifact_path = path.join(rabitq_artifact_file(generation));
3270        if let Some(artifact) =
3271            resident_diskann::artifact::write(self, &artifact_path, generation, task, publication)?
3272        {
3273            self.invalidate_rabitq_projection();
3274            return Ok((generation, artifact.reference.byte_length, Some(artifact)));
3275        }
3276        self.vector_scoring
3277            .validate(self.vector_index_descriptor.is_some())?;
3278        let projection = RaBitQCandidateProjection::write_from_view(
3279            &artifact_path,
3280            &self.documents,
3281            self.rabitq_projection_identity(generation),
3282            self.rabitq_build_options,
3283            self.vector_metric(),
3284        )?
3285        .ok_or_else(|| {
3286            HawDBError::Storage(
3287                "HawDB RaBitQ projection build produced no artifact for vector documents"
3288                    .to_string(),
3289            )
3290        })?;
3291        let bytes_written = fs::metadata(&artifact_path)?.len();
3292        let (reference, checksum) = projection.file_artifact_reference().ok_or_else(|| {
3293            HawDBError::StorageIntegrity(
3294                "resident RaBitQ producer did not return an artifact reference".into(),
3295            )
3296        })?;
3297        let artifact = out_of_core::ResidentRaBitQArtifact {
3298            reference,
3299            checksum,
3300            source_digest: projection.manifest().source_digest,
3301            vector_document_count: projection.manifest().document_count,
3302            payload_checksum: projection.manifest().payload_checksum,
3303            peak_build_working_bytes: projection.manifest().peak_build_working_bytes,
3304            diskann_source_digest: None,
3305        };
3306        *self
3307            .rabitq_projection
3308            .lock()
3309            .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(Arc::new(projection));
3310        Ok((generation, bytes_written, Some(artifact)))
3311    }
3312
3313    /// Searches resident documents, returning unavailable-capability and execution errors.
3314    /// Sources exceeding the optional graph cache use scalar search; use
3315    /// [`Self::search_with_report`] for the fallback diagnostic.
3316    /// This entrypoint preserves in-memory payload access; `try_*` methods may read persisted ranges.
3317    pub fn search(
3318        &self,
3319        query_text: &str,
3320        query_embedding: Option<&[f32]>,
3321        mode: SearchMode,
3322        limit: usize,
3323    ) -> Result<Vec<SearchHit>> {
3324        self.search_with_report(query_text, query_embedding, mode, limit)
3325            .map(|result| result.hits)
3326    }
3327
3328    /// Searches resident documents, returning unavailable-capability and execution errors.
3329    /// This entrypoint preserves in-memory payload access; `try_*` methods may read persisted ranges.
3330    pub fn search_with_report(
3331        &self,
3332        query_text: &str,
3333        query_embedding: Option<&[f32]>,
3334        mode: SearchMode,
3335        limit: usize,
3336    ) -> Result<SearchResultSet> {
3337        self.search_with_options(
3338            query_text,
3339            query_embedding,
3340            mode,
3341            SearchQueryOptions {
3342                limit,
3343                offset: 0,
3344                rank_window: None,
3345                fusion_weights: SearchFusionWeights::default(),
3346                metadata_filters: BTreeMap::new(),
3347                policy_epoch: None,
3348            },
3349        )
3350    }
3351
3352    /// Searches resident documents, returning unavailable-capability and execution errors.
3353    /// This entrypoint preserves in-memory payload access; `try_*` methods may read persisted ranges.
3354    /// Sources exceeding the optional graph cache use scalar search and report
3355    /// [`SearchFallbackReasonCode::DiskAnnCacheBudgetExceeded`].
3356    pub fn search_with_options(
3357        &self,
3358        query_text: &str,
3359        query_embedding: Option<&[f32]>,
3360        mode: SearchMode,
3361        options: SearchQueryOptions,
3362    ) -> Result<SearchResultSet> {
3363        self.try_search_with_options_using_vector_backend(
3364            query_text,
3365            query_embedding,
3366            mode,
3367            options,
3368            SearchExecutionStrategy::default_vector(false, VectorSearchExecutionOptions::default()),
3369            None,
3370        )
3371    }
3372
3373    /// Exhaustively score the complete eligible resident vector domain.
3374    pub fn search_with_options_exact(
3375        &self,
3376        query_text: &str,
3377        query_embedding: Option<&[f32]>,
3378        mode: SearchMode,
3379        options: SearchQueryOptions,
3380    ) -> Result<SearchResultSet> {
3381        self.try_search_with_options_using_vector_backend(
3382            query_text,
3383            query_embedding,
3384            mode,
3385            options,
3386            SearchExecutionStrategy::default_vector(
3387                false,
3388                VectorSearchExecutionOptions::default().with_exact_search(),
3389            ),
3390            None,
3391        )
3392    }
3393
3394    /// Default candidates under the caller's memory and cancellation limits.
3395    /// Explicit RaBitQ selection refuses build/cache or query budget failures.
3396    /// The ordinary graph may use scalar search with a reported cache fallback.
3397    pub fn try_search_with_options_context(
3398        &self,
3399        query_text: &str,
3400        query_embedding: Option<&[f32]>,
3401        mode: SearchMode,
3402        options: SearchQueryOptions,
3403        vector_options: VectorSearchExecutionOptions<'_>,
3404    ) -> Result<SearchResultSet> {
3405        self.try_search_with_options_using_vector_backend(
3406            query_text,
3407            query_embedding,
3408            mode,
3409            options,
3410            SearchExecutionStrategy::default_vector(true, vector_options),
3411            None,
3412        )
3413    }
3414
3415    pub fn try_search_with_options(
3416        &self,
3417        query_text: &str,
3418        query_embedding: Option<&[f32]>,
3419        mode: SearchMode,
3420        options: SearchQueryOptions,
3421    ) -> Result<SearchResultSet> {
3422        self.try_search_with_options_using_vector_backend(
3423            query_text,
3424            query_embedding,
3425            mode,
3426            options,
3427            SearchExecutionStrategy::default_vector(true, VectorSearchExecutionOptions::default()),
3428            None,
3429        )
3430    }
3431
3432    pub fn try_search_with_options_access_control(
3433        &self,
3434        query_text: &str,
3435        query_embedding: Option<&[f32]>,
3436        mode: SearchMode,
3437        options: SearchQueryOptions,
3438        access_control: SearchAccessControlContext,
3439    ) -> Result<SearchResultSet> {
3440        self.try_search_with_options_using_vector_backend(
3441            query_text,
3442            query_embedding,
3443            mode,
3444            options,
3445            SearchExecutionStrategy::default_vector(true, VectorSearchExecutionOptions::default()),
3446            Some(&access_control),
3447        )
3448    }
3449
3450    /// Searches resident documents, returning unavailable-capability and execution errors.
3451    /// This entrypoint preserves in-memory payload access; `try_*` methods may read persisted ranges.
3452    pub fn search_with_options_prefer_compressed_vector_projection(
3453        &self,
3454        query_text: &str,
3455        query_embedding: Option<&[f32]>,
3456        mode: SearchMode,
3457        options: SearchQueryOptions,
3458    ) -> Result<SearchResultSet> {
3459        self.search_with_options_compressed_vector_projection_mode(
3460            query_text,
3461            query_embedding,
3462            mode,
3463            options,
3464            CompressedVectorSearchMode::Preferred,
3465        )
3466    }
3467
3468    /// Searches resident documents, returning unavailable-capability and execution errors.
3469    /// This entrypoint preserves in-memory payload access; `try_*` methods may read persisted ranges.
3470    pub fn search_with_options_compressed_vector_projection_mode(
3471        &self,
3472        query_text: &str,
3473        query_embedding: Option<&[f32]>,
3474        mode: SearchMode,
3475        options: SearchQueryOptions,
3476        compressed_vector_search_mode: CompressedVectorSearchMode,
3477    ) -> Result<SearchResultSet> {
3478        self.try_search_with_options_compressed_vector_projection_mode_internal(
3479            query_text,
3480            query_embedding,
3481            mode,
3482            options,
3483            AdaptiveVectorSearchOptions::new(compressed_vector_search_mode),
3484            AdaptiveVectorExecutionControls::IN_MEMORY,
3485        )
3486    }
3487
3488    pub fn try_search_with_options_compressed_vector_projection_mode(
3489        &self,
3490        query_text: &str,
3491        query_embedding: Option<&[f32]>,
3492        mode: SearchMode,
3493        options: SearchQueryOptions,
3494        compressed_vector_search_mode: CompressedVectorSearchMode,
3495    ) -> Result<SearchResultSet> {
3496        self.try_search_with_options_compressed_vector_projection_mode_internal(
3497            query_text,
3498            query_embedding,
3499            mode,
3500            options,
3501            AdaptiveVectorSearchOptions::new(compressed_vector_search_mode),
3502            AdaptiveVectorExecutionControls::PERSISTED,
3503        )
3504    }
3505
3506    pub fn try_search_with_options_adaptive_vector_projection(
3507        &self,
3508        query_text: &str,
3509        query_embedding: Option<&[f32]>,
3510        mode: SearchMode,
3511        options: SearchQueryOptions,
3512        adaptive_options: AdaptiveVectorSearchOptions,
3513    ) -> Result<SearchResultSet> {
3514        self.try_search_with_options_compressed_vector_projection_mode_internal(
3515            query_text,
3516            query_embedding,
3517            mode,
3518            options,
3519            adaptive_options,
3520            AdaptiveVectorExecutionControls::PERSISTED,
3521        )
3522    }
3523
3524    pub fn try_search_with_options_adaptive_vector_projection_context(
3525        &self,
3526        query_text: &str,
3527        query_embedding: Option<&[f32]>,
3528        mode: SearchMode,
3529        options: SearchQueryOptions,
3530        adaptive_options: AdaptiveVectorSearchOptions,
3531        vector_execution_options: VectorSearchExecutionOptions<'_>,
3532    ) -> Result<SearchResultSet> {
3533        if let Some(task_context) = vector_execution_options.task_context {
3534            task_context
3535                .checkpoint()
3536                .map_err(HawDBError::RuntimeTaskStopped)?;
3537        }
3538        let result = self.try_search_with_options_compressed_vector_projection_mode_internal(
3539            query_text,
3540            query_embedding,
3541            mode,
3542            options,
3543            adaptive_options,
3544            AdaptiveVectorExecutionControls::persisted(vector_execution_options),
3545        )?;
3546        if let Some(task_context) = vector_execution_options.task_context {
3547            task_context
3548                .checkpoint()
3549                .map_err(HawDBError::RuntimeTaskStopped)?;
3550        }
3551        Ok(result)
3552    }
3553
3554    /// Searches resident documents, returning unavailable-capability and execution errors.
3555    /// This entrypoint preserves in-memory payload access; `try_*` methods may read persisted ranges.
3556    pub fn search_with_options_adaptive_vector_projection(
3557        &self,
3558        query_text: &str,
3559        query_embedding: Option<&[f32]>,
3560        mode: SearchMode,
3561        options: SearchQueryOptions,
3562        adaptive_options: AdaptiveVectorSearchOptions,
3563    ) -> Result<SearchResultSet> {
3564        self.try_search_with_options_compressed_vector_projection_mode_internal(
3565            query_text,
3566            query_embedding,
3567            mode,
3568            options,
3569            adaptive_options,
3570            AdaptiveVectorExecutionControls::IN_MEMORY,
3571        )
3572    }
3573
3574    pub fn validate_sampled_vector_recall(
3575        &self,
3576        options: VectorRecallValidationOptions,
3577    ) -> VectorRecallValidationReport {
3578        self.validate_sampled_vector_recall_with_controls(
3579            options,
3580            AdaptiveVectorExecutionControls::IN_MEMORY,
3581            AdaptiveVectorExecutionControls::RECALL_CANDIDATES,
3582        )
3583    }
3584
3585    /// Validate the explicit compressed candidate path rather than the default engine.
3586    pub fn validate_sampled_compressed_vector_recall(
3587        &self,
3588        options: VectorRecallValidationOptions,
3589    ) -> VectorRecallValidationReport {
3590        self.validate_sampled_vector_recall_with_backend(
3591            options,
3592            AdaptiveVectorExecutionControls::IN_MEMORY,
3593            AdaptiveVectorExecutionControls::RECALL_CANDIDATES,
3594            VectorRecallProbeBackend::Compressed,
3595        )
3596    }
3597
3598    fn validate_sampled_vector_recall_with_controls(
3599        &self,
3600        options: VectorRecallValidationOptions,
3601        exact_controls: AdaptiveVectorExecutionControls<'_>,
3602        approximate_controls: AdaptiveVectorExecutionControls<'_>,
3603    ) -> VectorRecallValidationReport {
3604        self.validate_sampled_vector_recall_with_backend(
3605            options,
3606            exact_controls,
3607            approximate_controls,
3608            VectorRecallProbeBackend::Default,
3609        )
3610    }
3611
3612    fn validate_sampled_vector_recall_with_backend(
3613        &self,
3614        options: VectorRecallValidationOptions,
3615        exact_controls: AdaptiveVectorExecutionControls<'_>,
3616        approximate_controls: AdaptiveVectorExecutionControls<'_>,
3617        backend: VectorRecallProbeBackend,
3618    ) -> VectorRecallValidationReport {
3619        let predicate_pushdown = search_metadata_predicate_pushdown(&options.metadata_filters);
3620        let eligible = || {
3621            self.documents.values().filter(|document| {
3622                document.embedding.is_some()
3623                    && search_document_matches_predicates(document, &predicate_pushdown.predicates)
3624            })
3625        };
3626        let sample_candidate_count = eligible().count();
3627        let mut accumulator =
3628            VectorRecallValidationAccumulator::new(sample_candidate_count, &options)
3629                .with_backend(backend.name());
3630        if predicate_pushdown.report.parse_error.is_some() {
3631            accumulator.mark_metadata_filter_invalid();
3632            return accumulator.finish();
3633        }
3634        if accumulator.requested_sample_count() == 0 || accumulator.top_k() == 0 {
3635            return accumulator.finish();
3636        }
3637        let sample_positions =
3638            sample_positions(sample_candidate_count, accumulator.requested_sample_count())
3639                .into_iter()
3640                .collect::<BTreeSet<_>>();
3641        let sample_documents = eligible()
3642            .enumerate()
3643            .filter(|(index, _)| sample_positions.contains(index))
3644            .map(|(_, document)| document)
3645            .collect::<Vec<_>>();
3646        let query_limit = accumulator.top_k().saturating_add(1);
3647
3648        for document in sample_documents {
3649            let embedding = document
3650                .embedding
3651                .as_deref()
3652                .expect("sampled vector document has an embedding");
3653            let exact_query_options = SearchQueryOptions {
3654                limit: query_limit,
3655                offset: 0,
3656                rank_window: None,
3657                fusion_weights: SearchFusionWeights::default(),
3658                metadata_filters: options.metadata_filters.clone(),
3659                policy_epoch: None,
3660            };
3661            let Ok(exact) = self
3662                .try_search_with_options_compressed_vector_projection_mode_internal(
3663                    "",
3664                    Some(embedding),
3665                    SearchMode::Vector,
3666                    exact_query_options.clone(),
3667                    AdaptiveVectorSearchOptions::new(CompressedVectorSearchMode::Disabled)
3668                        .as_recall_validation_probe(),
3669                    exact_controls,
3670                )
3671            else {
3672                accumulator.mark_probe_execution_failed();
3673                break;
3674            };
3675            let approximate_query_options = SearchQueryOptions {
3676                rank_window: Some(accumulator.candidate_limit().saturating_add(1)),
3677                ..exact_query_options
3678            };
3679            let approximate = match backend {
3680                VectorRecallProbeBackend::Default => self
3681                    .try_search_with_options_using_vector_backend(
3682                        "",
3683                        Some(embedding),
3684                        SearchMode::Vector,
3685                        approximate_query_options,
3686                        SearchExecutionStrategy::default_vector(
3687                            approximate_controls.use_physical_range_reads,
3688                            approximate_controls.vector_execution_options,
3689                        ),
3690                        None,
3691                    ),
3692                VectorRecallProbeBackend::Compressed => self
3693                    .try_search_with_options_compressed_vector_projection_mode_internal(
3694                        "",
3695                        Some(embedding),
3696                        SearchMode::Vector,
3697                        approximate_query_options,
3698                        AdaptiveVectorSearchOptions::new(CompressedVectorSearchMode::Required),
3699                        approximate_controls,
3700                    ),
3701            };
3702            let Ok(approximate) = approximate else {
3703                accumulator.mark_probe_execution_failed();
3704                break;
3705            };
3706            let exact_ids =
3707                recall_validation_hit_ids(&exact, document.id.as_str(), accumulator.top_k());
3708            let approximate_ids =
3709                recall_validation_hit_ids(&approximate, document.id.as_str(), accumulator.top_k());
3710            let approximate_retriever = approximate
3711                .retrievers
3712                .iter()
3713                .find(|retriever| retriever.name == "vector")
3714                .expect("vector search always reports the vector retriever");
3715            let candidate_ids = recall_validation_candidate_ids(
3716                &approximate_retriever.candidate_top_ids,
3717                document.id.as_str(),
3718                accumulator.candidate_limit(),
3719            );
3720            accumulator.record(
3721                &exact_ids,
3722                &candidate_ids,
3723                &approximate_ids,
3724                approximate_retriever,
3725            );
3726        }
3727
3728        accumulator.finish()
3729    }
3730
3731    pub fn validate_sampled_vector_recall_access_control(
3732        &self,
3733        options: VectorRecallValidationOptions,
3734        access_control: &SearchAccessControlContext,
3735    ) -> VectorRecallValidationReport {
3736        self.validate_sampled_vector_recall_access_control_backend(
3737            options,
3738            access_control,
3739            VectorRecallProbeBackend::Default,
3740        )
3741    }
3742
3743    pub fn validate_sampled_compressed_vector_recall_access_control(
3744        &self,
3745        options: VectorRecallValidationOptions,
3746        access_control: &SearchAccessControlContext,
3747    ) -> VectorRecallValidationReport {
3748        self.validate_sampled_vector_recall_access_control_backend(
3749            options,
3750            access_control,
3751            VectorRecallProbeBackend::Compressed,
3752        )
3753    }
3754
3755    fn validate_sampled_vector_recall_access_control_backend(
3756        &self,
3757        mut options: VectorRecallValidationOptions,
3758        access_control: &SearchAccessControlContext,
3759        backend: VectorRecallProbeBackend,
3760    ) -> VectorRecallValidationReport {
3761        match access_control.effective_metadata_filters(&options.metadata_filters) {
3762            Ok(filters) => options.metadata_filters = filters,
3763            Err(_) => {
3764                let mut accumulator = VectorRecallValidationAccumulator::new(0, &options)
3765                    .with_backend(backend.name());
3766                accumulator.mark_metadata_filter_invalid();
3767                return accumulator.finish();
3768            }
3769        }
3770        self.validate_sampled_vector_recall_with_backend(
3771            options,
3772            AdaptiveVectorExecutionControls::IN_MEMORY,
3773            AdaptiveVectorExecutionControls::RECALL_CANDIDATES,
3774            backend,
3775        )
3776    }
3777
3778    pub fn vector_projection_qualification_identity(
3779        &self,
3780    ) -> Option<VectorProjectionQualificationIdentity> {
3781        #[cfg(feature = "vector-search")]
3782        {
3783            if !self.rabitq_backend_selected() {
3784                return self.resident_diskann.qualification_identity(self);
3785            }
3786            let projection = self.rabitq_projection()?;
3787            let manifest = projection.manifest();
3788            Some(VectorProjectionQualificationIdentity {
3789                projection_generation: manifest.identity.generation,
3790                source_graph_commit_epoch: manifest.identity.source_epoch,
3791                document_count: manifest.document_count,
3792                source_digest: manifest.source_digest,
3793                payload_bytes: manifest.payload_bytes,
3794                payload_checksum: manifest.payload_checksum,
3795                format_version: manifest.format_version,
3796                algorithm: manifest.algorithm.clone(),
3797                bit_width: manifest.bit_width,
3798                dimension: manifest.dimension,
3799                transform_seed: manifest.transform_seed,
3800                embedding_model: manifest.identity.embedding_model.clone(),
3801                embedding_version: manifest.identity.embedding_version.clone(),
3802                file_backed: projection.is_file_backed(),
3803            })
3804        }
3805        #[cfg(not(feature = "vector-search"))]
3806        {
3807            None
3808        }
3809    }
3810
3811    pub fn vector_projection_resource_evidence(&self) -> Option<VectorProjectionResourceEvidence> {
3812        #[cfg(feature = "vector-search")]
3813        {
3814            // Resident graph snapshots do not persist construction measurements.
3815            // Never manufacture their resource evidence from an unrelated codec.
3816            if !self.rabitq_backend_selected() {
3817                return None;
3818            }
3819            let projection = self.rabitq_projection()?;
3820            let manifest = projection.manifest();
3821            let raw_vector_bytes = u64::try_from(manifest.document_count)
3822                .unwrap_or(u64::MAX)
3823                .saturating_mul(u64::try_from(manifest.dimension).unwrap_or(u64::MAX))
3824                .saturating_mul(std::mem::size_of::<f32>() as u64);
3825            let build_write_amplification_per_million = if raw_vector_bytes == 0 {
3826                0
3827            } else {
3828                manifest
3829                    .payload_bytes
3830                    .saturating_mul(1_000_000)
3831                    .checked_div(raw_vector_bytes)
3832                    .unwrap_or(u64::MAX)
3833            };
3834            Some(VectorProjectionResourceEvidence {
3835                segment_count: manifest.segments.len(),
3836                requested_segment_rows: manifest.requested_segment_rows,
3837                admitted_segment_rows: manifest.admitted_segment_rows,
3838                configured_build_working_bytes: manifest.configured_build_working_bytes,
3839                peak_build_working_bytes: manifest.peak_build_working_bytes,
3840                raw_vector_bytes,
3841                projection_payload_bytes: manifest.payload_bytes,
3842                build_write_amplification_per_million,
3843            })
3844        }
3845        #[cfg(not(feature = "vector-search"))]
3846        {
3847            None
3848        }
3849    }
3850
3851    pub fn qualify_sampled_vector_recall_for_production(
3852        &self,
3853        options: VectorRecallValidationOptions,
3854        evidence_binding: crate::ProductionEvidenceBinding,
3855        expected_identity: crate::ProductionQualificationIdentity,
3856    ) -> VectorRecallProductionQualificationReport {
3857        let recall = self.validate_sampled_vector_recall(options);
3858        VectorRecallProductionQualificationReport::evaluate(
3859            recall,
3860            self.vector_projection_qualification_identity()
3861                .unwrap_or_default(),
3862            evidence_binding,
3863            expected_identity,
3864        )
3865    }
3866
3867    pub fn qualify_sampled_compressed_vector_recall_for_production(
3868        &self,
3869        options: VectorRecallValidationOptions,
3870        evidence_binding: crate::ProductionEvidenceBinding,
3871        expected_identity: crate::ProductionQualificationIdentity,
3872    ) -> VectorRecallProductionQualificationReport {
3873        let recall = self.validate_sampled_compressed_vector_recall(options);
3874        VectorRecallProductionQualificationReport::evaluate(
3875            recall,
3876            self.vector_projection_qualification_identity()
3877                .unwrap_or_default(),
3878            evidence_binding,
3879            expected_identity,
3880        )
3881    }
3882
3883    fn try_search_with_options_compressed_vector_projection_mode_internal(
3884        &self,
3885        query_text: &str,
3886        query_embedding: Option<&[f32]>,
3887        mode: SearchMode,
3888        options: SearchQueryOptions,
3889        adaptive_options: AdaptiveVectorSearchOptions,
3890        controls: AdaptiveVectorExecutionControls,
3891    ) -> Result<SearchResultSet> {
3892        self.try_search_with_options_using_vector_backend(
3893            query_text,
3894            query_embedding,
3895            mode,
3896            options,
3897            SearchExecutionStrategy::adaptive(
3898                vector_compression_preference(adaptive_options.compression_mode),
3899                adaptive_options.backend_policy,
3900                adaptive_options.recall_validation_probe,
3901                controls,
3902            ),
3903            None,
3904        )
3905    }
3906
3907    fn prepare_adaptive_vector_backend(
3908        &self,
3909        request: AdaptiveVectorSearchRequest,
3910        filtered_documents: &[&SearchDocument],
3911        embedding_dimension: usize,
3912        execution: VectorSearchExecutionOptions<'_>,
3913    ) -> Result<PreparedAdaptiveVectorBackend> {
3914        let task = execution.task_context;
3915        task.map_or(Ok(()), crate::build_control::checkpoint)?;
3916        let document_count = self
3917            .documents
3918            .values()
3919            .filter(|document| document.embedding.is_some())
3920            .count();
3921        let filtered_document_count = filtered_documents
3922            .iter()
3923            .filter(|document| document.embedding.is_some())
3924            .count();
3925        let decision_input =
3926            |quantized_projection_available, quantized_projection_covered_document_count| {
3927                AdaptiveVectorBackendInput {
3928                    compression_preference: request.compression_preference,
3929                    document_count,
3930                    filtered_document_count,
3931                    embedding_dimension,
3932                    recall_validation_probe: request.recall_validation_probe,
3933                    quantized_projection_available,
3934                    quantized_projection_covered_document_count,
3935                }
3936            };
3937        let preliminary = select_adaptive_vector_backend(
3938            decision_input(true, filtered_document_count),
3939            request.policy,
3940        );
3941        if preliminary.backend == AdaptiveVectorBackend::ScalarFlat {
3942            return Ok(PreparedAdaptiveVectorBackend {
3943                decision: preliminary,
3944                fallback_reason: None,
3945                #[cfg(feature = "vector-search")]
3946                projection: None,
3947            });
3948        }
3949
3950        #[cfg(feature = "vector-search")]
3951        {
3952            let cached = self.lock_rabitq_projection(task)?.clone();
3953            let projection = cached.or_else(|| {
3954                self.path
3955                    .is_none()
3956                    .then(|| {
3957                        self.build_in_memory_rabitq_projection_with_context(
3958                            task,
3959                            Some(execution.max_working_bytes),
3960                        )
3961                        .ok()
3962                        .flatten()
3963                    })
3964                    .flatten()
3965            });
3966            task.map_or(Ok(()), crate::build_control::checkpoint)?;
3967            let covered_document_count = projection
3968                .as_ref()
3969                .map(|projection| {
3970                    filtered_documents
3971                        .iter()
3972                        .filter(|document| {
3973                            document.embedding.is_some()
3974                                && projection.contains_document_id(document.id.as_str())
3975                        })
3976                        .count()
3977                })
3978                .unwrap_or(0);
3979            let decision = select_adaptive_vector_backend(
3980                decision_input(projection.is_some(), covered_document_count),
3981                request.policy,
3982            );
3983            let fallback_reason = adaptive_vector_fallback_reason(decision);
3984            Ok(PreparedAdaptiveVectorBackend {
3985                projection: (decision.backend == AdaptiveVectorBackend::QuantizedProjection)
3986                    .then_some(projection)
3987                    .flatten(),
3988                decision,
3989                fallback_reason,
3990            })
3991        }
3992
3993        #[cfg(not(feature = "vector-search"))]
3994        {
3995            let decision = select_adaptive_vector_backend(decision_input(false, 0), request.policy);
3996            Ok(PreparedAdaptiveVectorBackend {
3997                decision,
3998                fallback_reason: adaptive_vector_fallback_reason(decision),
3999            })
4000        }
4001    }
4002
4003    /// Executes externally generated candidates through HawDB's normal
4004    /// metadata filtering and raw-vector rerank path. This validation surface
4005    /// is not a production vector backend contract.
4006    #[cfg(feature = "qualification")]
4007    #[doc(hidden)]
4008    pub fn search_with_external_vector_candidates_for_validation(
4009        &self,
4010        candidates: &[(String, f64)],
4011        indexed_document_ids: &BTreeSet<String>,
4012        query_text: &str,
4013        query_embedding: Option<&[f32]>,
4014        mode: SearchMode,
4015        options: SearchQueryOptions,
4016    ) -> Result<SearchResultSet> {
4017        let mut strategy = SearchExecutionStrategy::fixed(
4018            VectorSearchBackend::ExternalValidation {
4019                candidates,
4020                indexed_document_ids,
4021            },
4022            None,
4023            false,
4024        );
4025        strategy.capture_candidate_ids = true;
4026        self.try_search_with_options_using_vector_backend(
4027            query_text,
4028            query_embedding,
4029            mode,
4030            options,
4031            strategy,
4032            None,
4033        )
4034    }
4035
4036    fn try_search_with_options_using_vector_backend(
4037        &self,
4038        query_text: &str,
4039        query_embedding: Option<&[f32]>,
4040        mode: SearchMode,
4041        options: SearchQueryOptions,
4042        strategy: SearchExecutionStrategy<'_>,
4043        access_control: Option<&SearchAccessControlContext>,
4044    ) -> Result<SearchResultSet> {
4045        if access_control.is_some() {
4046            self.runtime_capabilities
4047                .require(RuntimeCapability::AccessControl)?;
4048        }
4049        self.require_search_capabilities(mode)?;
4050        let SearchExecutionStrategy {
4051            vector_backend: vector_backend_request,
4052            vector_backend_fallback_reason,
4053            payload_access,
4054            capture_candidate_ids,
4055            vector_execution_options,
4056        } = strategy;
4057        let query_can_generate_candidates = vector_execution::query_can_generate_candidates(
4058            query_embedding,
4059            self.embedding_dimension,
4060            self.vector_metric(),
4061            vector_execution_options,
4062        )?;
4063        // Text-scoring modes stop analyzing once the analyzed-term cap is passed.
4064        let mut query_terms = if mode == SearchMode::Vector {
4065            tokenize(query_text, &self.analyzer_lexicon)
4066        } else {
4067            tokenize_query_bounded(query_text, &self.analyzer_lexicon, &self.lexical_config)?
4068        };
4069        let mut vector_fallback_reason_codes = Vec::new();
4070        let mut vector_fallback_reasons = Vec::new();
4071        if let Some(reason) = vector_backend_fallback_reason {
4072            vector_fallback_reason_codes
4073                .push(SearchFallbackReasonCode::CompressedVectorProjectionUnavailable);
4074            vector_fallback_reasons.push(reason);
4075        }
4076        let limit = options.limit;
4077        let document_count = self.documents.len();
4078        let metadata_filters = match access_control {
4079            Some(access_control) => access_control.effective_query_filters(&options)?,
4080            None => options.metadata_filters.clone(),
4081        };
4082        let policy_epoch = access_control
4083            .map(|access_control| access_control.policy_epoch)
4084            .or(options.policy_epoch);
4085        let mut predicate_pushdown = search_metadata_predicate_pushdown(&metadata_filters);
4086        let range_read = if matches!(payload_access, SearchPayloadAccess::PrunedRanges) {
4087            self.read_pruned_search_segments(&predicate_pushdown.predicates)?
4088        } else {
4089            None
4090        };
4091        let filtered = match &range_read {
4092            Some(range_read) => filter_search_documents_with_persisted_segments(
4093                &range_read.documents,
4094                &predicate_pushdown.predicates,
4095                self.segment_descriptor
4096                    .as_ref()
4097                    .expect("range reads require a persisted segment descriptor"),
4098            ),
4099            None => filter_search_documents_with_segment_pruning(
4100                &self.documents,
4101                &predicate_pushdown.predicates,
4102                self.segment_descriptor.as_deref(),
4103            ),
4104        };
4105        predicate_pushdown.report.segment_count = filtered.segment_count;
4106        predicate_pushdown.report.pruned_segment_count = filtered.pruned_segment_count;
4107        predicate_pushdown.report.scanned_segment_count = filtered.scanned_segment_count;
4108        predicate_pushdown
4109            .report
4110            .segment_pruning_candidate_document_count =
4111            filtered.segment_pruning_candidate_document_count;
4112        predicate_pushdown.report.segment_pruned_document_count =
4113            filtered.segment_pruned_document_count;
4114        predicate_pushdown.report.segment_scanned_document_count =
4115            filtered.segment_scanned_document_count;
4116        predicate_pushdown.report.persisted_segment_descriptor_used =
4117            filtered.persisted_segment_descriptor_used;
4118        if let Some(range_read) = &range_read {
4119            predicate_pushdown.report.physical_range_read_count = range_read.range_count;
4120            predicate_pushdown.report.physical_bytes_read = range_read.bytes_read;
4121        }
4122        predicate_pushdown.report.field_summaries = filtered.field_summaries;
4123        let mut filtered_documents = filtered.documents;
4124        filtered_documents.sort_unstable_by(|left, right| left.id.cmp(&right.id));
4125        let filtered_document_count = filtered_documents.len();
4126        let mut prepared_adaptive_backend = None;
4127        self.vector_scoring
4128            .validate(self.vector_index_descriptor.is_some())?;
4129        #[cfg(feature = "vector-search")]
4130        let default_without_candidates = mode != SearchMode::Text
4131            && matches!(vector_backend_request, VectorSearchBackendRequest::Default)
4132            && (limit == 0
4133                || !filtered_documents
4134                    .iter()
4135                    .any(|document| document.embedding.is_some()))
4136            && if self.rabitq_backend_selected() {
4137                self.lock_rabitq_projection(vector_execution_options.task_context)?
4138                    .is_none()
4139            } else {
4140                !self
4141                    .resident_diskann
4142                    .has_cached_projection(vector_execution_options.task_context)?
4143            };
4144        #[cfg(not(feature = "vector-search"))]
4145        let default_without_candidates = false;
4146        let vector_backend_request = if vector_execution_options.exact || default_without_candidates
4147        {
4148            VectorSearchBackendRequest::Fixed(VectorSearchBackend::Scalar)
4149        } else {
4150            vector_backend_request
4151        };
4152        #[cfg(feature = "vector-search")]
4153        let default_rabitq =
4154            if matches!(vector_backend_request, VectorSearchBackendRequest::Default)
4155                && self.rabitq_backend_selected()
4156                && mode != SearchMode::Text
4157                && query_can_generate_candidates
4158            {
4159                self.build_in_memory_rabitq_projection_with_context(
4160                    vector_execution_options.task_context,
4161                    Some(vector_execution_options.max_working_bytes),
4162                )?
4163            } else {
4164                None
4165            };
4166        let vector_backend = match vector_backend_request {
4167            VectorSearchBackendRequest::Default => {
4168                #[cfg(feature = "vector-search")]
4169                {
4170                    if let Some(projection) = default_rabitq.as_deref() {
4171                        VectorSearchBackend::RaBitQ {
4172                            projection,
4173                            required: true,
4174                        }
4175                    } else {
4176                        if !vector_execution_options.exact
4177                            && mode != SearchMode::Text
4178                            && query_can_generate_candidates
4179                        {
4180                            let candidate_limit = options
4181                                .offset
4182                                .saturating_add(limit)
4183                                .max(options.rank_window.unwrap_or(0))
4184                                .max(vector_execution_options.resident_candidate_window());
4185                            if self.resident_diskann.admits_default_search(
4186                                self,
4187                                &filtered_documents,
4188                                query_embedding.expect("valid query").len(),
4189                                candidate_limit,
4190                                vector_execution_options,
4191                            )? {
4192                                VectorSearchBackend::DiskAnn { index: self }
4193                            } else {
4194                                vector_fallback_reason_codes
4195                                    .push(SearchFallbackReasonCode::DiskAnnCacheBudgetExceeded);
4196                                vector_fallback_reasons.push("resident DiskANN cache exceeds its memory envelope; using scalar vector scan".into());
4197                                VectorSearchBackend::Scalar
4198                            }
4199                        } else {
4200                            VectorSearchBackend::Scalar
4201                        }
4202                    }
4203                }
4204                #[cfg(not(feature = "vector-search"))]
4205                {
4206                    VectorSearchBackend::Scalar
4207                }
4208            }
4209            VectorSearchBackendRequest::Fixed(backend) => backend,
4210            VectorSearchBackendRequest::Adaptive(request)
4211                if mode != SearchMode::Text && query_can_generate_candidates =>
4212            {
4213                prepared_adaptive_backend = Some(
4214                    self.prepare_adaptive_vector_backend(
4215                        request,
4216                        &filtered_documents,
4217                        self.embedding_dimension
4218                            .unwrap_or_else(|| query_embedding.map_or(0, <[f32]>::len)),
4219                        vector_execution_options,
4220                    )?,
4221                );
4222                prepared_adaptive_backend
4223                    .as_ref()
4224                    .expect("adaptive backend was prepared")
4225                    .backend()
4226            }
4227            VectorSearchBackendRequest::Adaptive(_) => VectorSearchBackend::Scalar,
4228        };
4229        if let Some(reason) = prepared_adaptive_backend
4230            .as_ref()
4231            .and_then(|backend| backend.fallback_reason.as_ref())
4232        {
4233            vector_fallback_reason_codes
4234                .push(SearchFallbackReasonCode::CompressedVectorProjectionUnavailable);
4235            vector_fallback_reasons.push(reason.clone());
4236        }
4237        let vector_backend_decision = prepared_adaptive_backend
4238            .as_ref()
4239            .map(|backend| backend.decision);
4240        let vector_filter_fields = predicate_pushdown
4241            .predicates
4242            .predicates()
4243            .iter()
4244            .map(|predicate| predicate.field().name().to_string())
4245            .collect::<Vec<_>>();
4246        let candidate_set = SearchCandidateSetReport {
4247            id_space: "search_projection_document_id".to_string(),
4248            representation: "sorted_document_ids".to_string(),
4249            cardinality: filtered_document_count,
4250            exact: true,
4251            snapshot_source_graph_commit_epoch: self.source_graph_commit_epoch,
4252            policy_epoch,
4253            filtered_out_count: document_count.saturating_sub(filtered_document_count),
4254            metadata_filters: options.metadata_filters.clone(),
4255            metadata_predicate_pushdown: predicate_pushdown.report,
4256        };
4257        let vector_available = match (query_embedding, self.embedding_dimension) {
4258            (Some(vector), Some(dimension)) if vector.len() == dimension => true,
4259            (Some(vector), Some(dimension)) => {
4260                vector_fallback_reason_codes
4261                    .push(SearchFallbackReasonCode::VectorDimensionMismatch);
4262                vector_fallback_reasons.push(format!(
4263                    "query embedding dimension {} does not match index dimension {dimension}",
4264                    vector.len()
4265                ));
4266                false
4267            }
4268            (Some(_), None) => {
4269                vector_fallback_reason_codes.push(SearchFallbackReasonCode::VectorIndexEmpty);
4270                vector_fallback_reasons.push("index has no vector rows".to_string());
4271                false
4272            }
4273            (None, _) => {
4274                if mode != SearchMode::Text {
4275                    vector_fallback_reason_codes
4276                        .push(SearchFallbackReasonCode::QueryEmbeddingMissing);
4277                    vector_fallback_reasons.push("query embedding not provided".to_string());
4278                }
4279                false
4280            }
4281        };
4282        let text_available = !query_terms.is_empty();
4283        let (mut text_fallback_reason_codes, mut text_fallback_reasons) =
4284            if !text_available && mode != SearchMode::Vector {
4285                (
4286                    vec![SearchFallbackReasonCode::TextQueryEmpty],
4287                    vec!["query text produced no searchable terms".to_string()],
4288                )
4289            } else {
4290                (Vec::new(), Vec::new())
4291            };
4292        let lexical_snapshot = if text_available
4293            && mode != SearchMode::Vector
4294            && matches!(payload_access, SearchPayloadAccess::PrunedRanges)
4295        {
4296            self.lexical_snapshot()
4297        } else {
4298            None
4299        };
4300        #[cfg(all(test, feature = "full-text-search"))]
4301        if lexical_snapshot.is_some() {
4302            lexical_snapshot_test_gate::pause_after_capture();
4303        }
4304        // The segmented projection bounds scored terms; long queries keep
4305        // their most selective terms instead of failing the whole search.
4306        if let Some((projection, delta)) = &lexical_snapshot {
4307            let selection = projection.fit_query_terms(
4308                &mut query_terms,
4309                delta,
4310                self.lexical_config.max_term_bytes,
4311                self.lexical_config.query_term_policy,
4312                None,
4313            )?;
4314            if selection.reduced() {
4315                text_fallback_reason_codes.push(SearchFallbackReasonCode::TextQueryTermsReduced);
4316                text_fallback_reasons.push(selection.to_string());
4317            }
4318        }
4319        // Without a projection, resident BM25 applies the same caps and the
4320        // same selection as the resident text seed over the filtered corpus.
4321        if text_available && mode != SearchMode::Vector && lexical_snapshot.is_none() {
4322            let selection = resident_bm25::select_query_terms(
4323                &mut query_terms,
4324                filtered_documents.iter().copied(),
4325                &self.analyzer_lexicon,
4326                &self.lexical_config,
4327            )?;
4328            if selection.reduced() {
4329                text_fallback_reason_codes.push(SearchFallbackReasonCode::TextQueryTermsReduced);
4330                text_fallback_reasons.push(selection.to_string());
4331            }
4332        }
4333        let mut text_corpus =
4334            if text_available && mode != SearchMode::Vector && lexical_snapshot.is_none() {
4335                Some(resident_bm25::Scorer::from_documents(
4336                    &query_terms,
4337                    filtered_documents.iter().copied(),
4338                    &self.analyzer_lexicon,
4339                )?)
4340            } else {
4341                None
4342            };
4343        let projection_freshness = self.projection_freshness();
4344        let (vector_index_covered_document_count, vector_index_candidate_document_count) =
4345            vector_backend.index_coverage(&filtered_documents);
4346
4347        let mut vector_execution = if vector_available && mode != SearchMode::Text {
4348            Some(execute_search_vector_plan(SearchVectorExecutionRequest {
4349                query_embedding: query_embedding
4350                    .expect("vector_available requires query embedding"),
4351                metric: self.vector_metric(),
4352                scoring: self.vector_scoring,
4353                documents: &filtered_documents,
4354                backend: vector_backend,
4355                filter_fields: vector_filter_fields,
4356                limit: options.offset.saturating_add(limit),
4357                rank_window: options.rank_window,
4358                capture_candidate_ids,
4359                vector_execution_options,
4360                fallback_reason_codes: &mut vector_fallback_reason_codes,
4361                fallback_reasons: &mut vector_fallback_reasons,
4362            })?)
4363        } else {
4364            None
4365        };
4366        let vector_scores = vector_execution
4367            .as_ref()
4368            .map(|execution| execution.scores.clone())
4369            .unwrap_or_default();
4370        let retained_text_score_limit = match mode {
4371            SearchMode::Text => Some(options.offset.saturating_add(limit)),
4372            SearchMode::Hybrid => options.rank_window,
4373            SearchMode::Vector => Some(0),
4374        };
4375        let lexical_report = lexical_snapshot
4376            .as_ref()
4377            .map(|(projection, delta)| {
4378                projection.score_with_stable_filter(
4379                    &query_terms,
4380                    delta,
4381                    retained_text_score_limit,
4382                    |id| {
4383                        Ok(filtered_documents
4384                            .binary_search_by(|document| document.id.as_str().cmp(id))
4385                            .is_ok())
4386                    },
4387                )
4388            })
4389            .transpose()?;
4390        let (
4391            mut text_scores,
4392            lexical_matching_document_count,
4393            lexical_postings_visited,
4394            lexical_bytes_read,
4395            lexical_blocks_skipped,
4396        ) = if let Some(report) = lexical_report {
4397            (
4398                report.scores,
4399                report.matching_document_count,
4400                report.postings_visited,
4401                report.bytes_read,
4402                report.blocks_skipped,
4403            )
4404        } else {
4405            (BTreeMap::new(), 0, 0, 0, 0)
4406        };
4407        if let Some(corpus) = &mut text_corpus {
4408            for document in &filtered_documents {
4409                let text_score = corpus.score(document, &self.analyzer_lexicon)?;
4410                if text_score > 0.0 {
4411                    text_scores.insert(document.id.clone(), text_score);
4412                }
4413            }
4414        }
4415        let segmented_lexical_projection_used = lexical_snapshot.is_some();
4416        let text_candidate_count = if segmented_lexical_projection_used {
4417            lexical_matching_document_count
4418        } else {
4419            text_scores.len()
4420        };
4421        let mut fallback_reason_codes = vector_fallback_reason_codes.clone();
4422        fallback_reason_codes.extend(text_fallback_reason_codes.iter().copied());
4423        let mut fallback_reasons = vector_fallback_reasons.clone();
4424        fallback_reasons.extend(text_fallback_reasons.iter().cloned());
4425
4426        let vector_ranks = ranked_scores(&vector_scores);
4427        let text_ranks = ranked_scores(&text_scores);
4428        let vector_window_ranks = window_ranks(&vector_ranks, options.rank_window);
4429        let text_window_ranks = window_ranks(&text_ranks, options.rank_window);
4430        let mut retrievers = vec![
4431            SearchRetrieverReport {
4432                name: "vector".to_string(),
4433                backend: vector_backend.report_name().to_string(),
4434                backend_selection_reason: vector_backend_decision.map(|decision| decision.reason),
4435                estimated_raw_vector_bytes: vector_backend_decision
4436                    .map(|decision| decision.estimated_raw_vector_bytes),
4437                filter_selectivity_per_million: vector_backend_decision
4438                    .map(|decision| decision.filter_selectivity_per_million),
4439                available: vector_available && mode != SearchMode::Text,
4440                input_candidate_set: candidate_set.clone(),
4441                candidate_score_source: vector_execution
4442                    .as_ref()
4443                    .map(|execution| execution.report.candidate_score_source.as_str())
4444                    .unwrap_or("none")
4445                    .to_string(),
4446                final_score_source: vector_execution
4447                    .as_ref()
4448                    .map(|execution| execution.report.final_score_source.as_str())
4449                    .unwrap_or("none")
4450                    .to_string(),
4451                generated_candidate_count: vector_execution
4452                    .as_ref()
4453                    .map(|execution| execution.report.generated_candidate_count)
4454                    .unwrap_or(0),
4455                candidate_scan_rounds: vector_execution
4456                    .as_ref()
4457                    .map(|execution| execution.report.candidate_scan_rounds)
4458                    .unwrap_or(0),
4459                descriptor_pruned_count: candidate_set
4460                    .metadata_predicate_pushdown
4461                    .segment_pruned_document_count,
4462                scalar_filtered_count: candidate_set
4463                    .filtered_out_count
4464                    .saturating_sub(
4465                        candidate_set
4466                            .metadata_predicate_pushdown
4467                            .segment_pruned_document_count,
4468                    )
4469                    .saturating_add(
4470                        vector_execution
4471                            .as_ref()
4472                            .map(|execution| execution.report.residual_filtered_count)
4473                            .unwrap_or(0),
4474                    ),
4475                residual_filtered_count: vector_execution
4476                    .as_ref()
4477                    .map(|execution| execution.report.residual_filtered_count)
4478                    .unwrap_or(0),
4479                reranked_candidate_count: vector_execution
4480                    .as_ref()
4481                    .map(|execution| execution.report.reranked_candidate_count)
4482                    .unwrap_or(0),
4483                raw_vector_bytes_read: vector_execution
4484                    .as_ref()
4485                    .map(|execution| execution.report.raw_vector_bytes_read)
4486                    .unwrap_or(0),
4487                candidate_scan_kernel: vector_execution
4488                    .as_ref()
4489                    .and_then(|execution| execution.report.candidate_scan_metrics.as_ref())
4490                    .map(|metrics| metrics.kernel.clone()),
4491                candidate_scan_worker_count: vector_execution
4492                    .as_ref()
4493                    .and_then(|execution| execution.report.candidate_scan_metrics.as_ref())
4494                    .map(|metrics| metrics.worker_count)
4495                    .unwrap_or(0),
4496                candidate_scan_segment_count: vector_execution
4497                    .as_ref()
4498                    .and_then(|execution| execution.report.candidate_scan_metrics.as_ref())
4499                    .map(|metrics| metrics.segment_count)
4500                    .unwrap_or(0),
4501                candidate_scan_scanned_segment_count: vector_execution
4502                    .as_ref()
4503                    .and_then(|execution| execution.report.candidate_scan_metrics.as_ref())
4504                    .map(|metrics| metrics.scanned_segment_count)
4505                    .unwrap_or(0),
4506                candidate_scan_scored_document_count: vector_execution
4507                    .as_ref()
4508                    .and_then(|execution| execution.report.candidate_scan_metrics.as_ref())
4509                    .map(|metrics| metrics.scored_document_count)
4510                    .unwrap_or(0),
4511                candidate_scan_filtered_document_count: vector_execution
4512                    .as_ref()
4513                    .and_then(|execution| execution.report.candidate_scan_metrics.as_ref())
4514                    .map(|metrics| metrics.filtered_document_count)
4515                    .unwrap_or(0),
4516                candidate_scan_scanned_block_count: vector_execution
4517                    .as_ref()
4518                    .and_then(|execution| execution.report.candidate_scan_metrics.as_ref())
4519                    .map(|metrics| metrics.scanned_block_count)
4520                    .unwrap_or(0),
4521                candidate_scan_skipped_block_count: vector_execution
4522                    .as_ref()
4523                    .and_then(|execution| execution.report.candidate_scan_metrics.as_ref())
4524                    .map(|metrics| metrics.skipped_block_count)
4525                    .unwrap_or(0),
4526                candidate_scan_adaptive_exact_scan_count: vector_execution
4527                    .as_ref()
4528                    .and_then(|execution| execution.report.candidate_scan_metrics.as_ref())
4529                    .map(|metrics| metrics.adaptive_exact_scan_count)
4530                    .unwrap_or(0),
4531                candidate_scan_payload_bytes_read: vector_execution
4532                    .as_ref()
4533                    .and_then(|execution| execution.report.candidate_scan_metrics.as_ref())
4534                    .map(|metrics| metrics.payload_bytes_read)
4535                    .unwrap_or(0),
4536                candidate_scan_admitted_working_bytes: vector_execution
4537                    .as_ref()
4538                    .and_then(|execution| execution.report.candidate_scan_metrics.as_ref())
4539                    .map(|metrics| metrics.admitted_working_bytes)
4540                    .unwrap_or(0),
4541                posting_bytes_read: 0,
4542                candidate_postings_visited: 0,
4543                candidate_blocks_skipped: 0,
4544                segmented_lexical_projection_used: false,
4545                index_covered_document_count: vector_index_covered_document_count,
4546                index_candidate_document_count: vector_index_candidate_document_count,
4547                index_coverage_complete: vector_index_covered_document_count
4548                    == vector_index_candidate_document_count,
4549                candidate_count: vector_scores.len(),
4550                candidate_set: retriever_candidate_set_report(
4551                    vector_window_ranks.len(),
4552                    self.source_graph_commit_epoch,
4553                    options.policy_epoch,
4554                    vector_execution.as_ref().is_some_and(|execution| {
4555                        execution.report.candidate_score_source
4556                            == hawdb_executor::VectorScoreSource::RawVector
4557                    }),
4558                ),
4559                fallback_reason_codes: vector_fallback_reason_codes,
4560                fallback_reasons: vector_fallback_reasons,
4561                candidate_top_ids: vector_execution
4562                    .as_mut()
4563                    .map(|execution| std::mem::take(&mut execution.candidate_ids))
4564                    .unwrap_or_default(),
4565                top_hit_ids: top_ranked_ids(&vector_window_ranks, limit),
4566                top_candidates: top_ranked_candidates(&vector_window_ranks, &vector_scores, limit),
4567            },
4568            SearchRetrieverReport {
4569                name: "text".to_string(),
4570                backend: if segmented_lexical_projection_used {
4571                    "segmented_bm25_text"
4572                } else {
4573                    "bm25_text"
4574                }
4575                .to_string(),
4576                backend_selection_reason: None,
4577                estimated_raw_vector_bytes: None,
4578                filter_selectivity_per_million: None,
4579                available: text_available && mode != SearchMode::Vector,
4580                input_candidate_set: candidate_set.clone(),
4581                candidate_score_source: if text_available && mode != SearchMode::Vector {
4582                    if segmented_lexical_projection_used {
4583                        "segmented_bm25"
4584                    } else {
4585                        "bm25"
4586                    }
4587                } else {
4588                    "none"
4589                }
4590                .to_string(),
4591                final_score_source: if text_available && mode != SearchMode::Vector {
4592                    if segmented_lexical_projection_used {
4593                        "segmented_bm25"
4594                    } else {
4595                        "bm25"
4596                    }
4597                } else {
4598                    "none"
4599                }
4600                .to_string(),
4601                generated_candidate_count: text_candidate_count,
4602                candidate_scan_rounds: 0,
4603                descriptor_pruned_count: candidate_set
4604                    .metadata_predicate_pushdown
4605                    .segment_pruned_document_count,
4606                scalar_filtered_count: candidate_set.filtered_out_count.saturating_sub(
4607                    candidate_set
4608                        .metadata_predicate_pushdown
4609                        .segment_pruned_document_count,
4610                ),
4611                residual_filtered_count: 0,
4612                reranked_candidate_count: 0,
4613                raw_vector_bytes_read: 0,
4614                candidate_scan_kernel: None,
4615                candidate_scan_worker_count: 0,
4616                candidate_scan_segment_count: 0,
4617                candidate_scan_scanned_segment_count: 0,
4618                candidate_scan_scored_document_count: 0,
4619                candidate_scan_filtered_document_count: 0,
4620                candidate_scan_scanned_block_count: 0,
4621                candidate_scan_skipped_block_count: 0,
4622                candidate_scan_adaptive_exact_scan_count: 0,
4623                candidate_scan_payload_bytes_read: 0,
4624                candidate_scan_admitted_working_bytes: 0,
4625                posting_bytes_read: lexical_bytes_read,
4626                candidate_postings_visited: lexical_postings_visited,
4627                candidate_blocks_skipped: lexical_blocks_skipped,
4628                segmented_lexical_projection_used,
4629                index_covered_document_count: 0,
4630                index_candidate_document_count: 0,
4631                index_coverage_complete: true,
4632                candidate_count: text_candidate_count,
4633                candidate_set: retriever_candidate_set_report(
4634                    text_window_ranks.len(),
4635                    self.source_graph_commit_epoch,
4636                    options.policy_epoch,
4637                    true,
4638                ),
4639                fallback_reason_codes: text_fallback_reason_codes,
4640                fallback_reasons: text_fallback_reasons,
4641                candidate_top_ids: Vec::new(),
4642                top_hit_ids: top_ranked_ids(&text_window_ranks, limit),
4643                top_candidates: top_ranked_candidates(&text_window_ranks, &text_scores, limit),
4644            },
4645        ];
4646        for retriever in &mut retrievers {
4647            if retriever.name == "vector" {
4648                for candidate in &mut retriever.top_candidates {
4649                    candidate.score = self.vector_scoring.exposed(candidate.score);
4650                }
4651            }
4652        }
4653        let mut scored_candidates = vector_scores
4654            .keys()
4655            .chain(text_scores.keys())
4656            .cloned()
4657            .collect::<BTreeSet<_>>()
4658            .into_iter()
4659            .filter_map(|id| {
4660                let vector_score = vector_scores.get(&id).copied().unwrap_or(0.0);
4661                let text_score = text_scores.get(&id).copied().unwrap_or(0.0);
4662                let vector_rank = match mode {
4663                    SearchMode::Hybrid => vector_window_ranks.get(&id).copied(),
4664                    SearchMode::Vector | SearchMode::Text => vector_ranks.get(&id).copied(),
4665                };
4666                let text_rank = match mode {
4667                    SearchMode::Hybrid => text_window_ranks.get(&id).copied(),
4668                    SearchMode::Vector | SearchMode::Text => text_ranks.get(&id).copied(),
4669                };
4670                let vector_rrf_score = rrf_child_score(vector_rank);
4671                let text_rrf_score = rrf_child_score(text_rank);
4672                let rrf_score =
4673                    weighted_rrf_score(vector_rrf_score, text_rrf_score, options.fusion_weights);
4674                let score = match mode {
4675                    SearchMode::Hybrid => rrf_score,
4676                    SearchMode::Vector => vector_score,
4677                    SearchMode::Text => text_score,
4678                };
4679                (score > 0.0).then_some(SearchScoredCandidate {
4680                    id,
4681                    score,
4682                    vector_score,
4683                    text_score,
4684                    rrf_score,
4685                    vector_rrf_score,
4686                    text_rrf_score,
4687                    vector_rank,
4688                    text_rank,
4689                })
4690            })
4691            .collect::<Vec<_>>();
4692        scored_candidates.sort_by(|left, right| {
4693            right
4694                .score
4695                .partial_cmp(&left.score)
4696                .unwrap_or(Ordering::Equal)
4697                .then_with(|| left.id.cmp(&right.id))
4698        });
4699        let total_hits = if mode == SearchMode::Text && segmented_lexical_projection_used {
4700            lexical_matching_document_count
4701        } else {
4702            scored_candidates.len()
4703        };
4704        let page_end = options.offset.saturating_add(limit);
4705        let truncated = total_hits > page_end;
4706        let mut hits = Vec::with_capacity(limit.min(scored_candidates.len()));
4707        for candidate in scored_candidates
4708            .into_iter()
4709            .skip(options.offset)
4710            .take(limit)
4711        {
4712            let document = filtered_documents
4713                .binary_search_by(|document| document.id.cmp(&candidate.id))
4714                .ok()
4715                .and_then(|index| filtered_documents.get(index).copied())
4716                .ok_or_else(|| {
4717                    HawDBError::Storage(format!(
4718                        "search candidate {} is missing from the filtered document set",
4719                        candidate.id
4720                    ))
4721                })?;
4722            let (matched_terms, matched_spans) = query_matches_bounded(
4723                &query_terms,
4724                document,
4725                &self.analyzer_lexicon,
4726                usize::MAX,
4727                u64::MAX,
4728                0,
4729            )
4730            .expect("unbounded matched-span collection cannot exhaust its admission limit");
4731            hits.push(SearchHit {
4732                id: candidate.id,
4733                score: if mode == SearchMode::Vector {
4734                    self.vector_scoring.exposed(candidate.score)
4735                } else {
4736                    candidate.score
4737                },
4738                vector_score: self.vector_scoring.exposed(candidate.vector_score),
4739                text_score: candidate.text_score,
4740                rrf_score: candidate.rrf_score,
4741                vector_rrf_score: candidate.vector_rrf_score,
4742                text_rrf_score: candidate.text_rrf_score,
4743                vector_rank: candidate.vector_rank,
4744                text_rank: candidate.text_rank,
4745                kind: document.metadata.get("kind").cloned(),
4746                external_id: document.metadata.get("external_id").cloned(),
4747                source_id: document.metadata.get("source_id").cloned(),
4748                matched_terms,
4749                matched_spans,
4750                fallback_reason_codes: fallback_reason_codes.clone(),
4751                fallback_reasons: fallback_reasons.clone(),
4752                projection_freshness: projection_freshness.clone(),
4753            });
4754        }
4755        let truncation_reasons = if truncated && options.offset > 0 {
4756            vec![format!(
4757                "offset {} limit {limit} returned from {total_hits} matching hits",
4758                options.offset
4759            )]
4760        } else if truncated {
4761            vec![format!(
4762                "limit {limit} returned from {total_hits} matching hits"
4763            )]
4764        } else {
4765            Vec::new()
4766        };
4767        let truncation_reason_codes = if truncated {
4768            vec![SearchTruncationReasonCode::LimitExceeded]
4769        } else {
4770            Vec::new()
4771        };
4772        let empty_reasons = search_empty_reasons(
4773            hits.is_empty(),
4774            document_count,
4775            filtered_document_count,
4776            total_hits,
4777            SearchPageWindow {
4778                offset: options.offset,
4779                limit,
4780            },
4781            &truncation_reasons,
4782            &fallback_reasons,
4783        );
4784        let empty_reason_codes = search_empty_reason_codes(
4785            hits.is_empty(),
4786            document_count,
4787            filtered_document_count,
4788            total_hits,
4789        );
4790        Ok(SearchResultSet {
4791            hits,
4792            total_hits,
4793            limit,
4794            offset: options.offset,
4795            truncated,
4796            truncation_reason_codes,
4797            truncation_reasons,
4798            empty_reason_codes,
4799            empty_reasons,
4800            fallback_reason_codes,
4801            fallback_reasons,
4802            retrievers,
4803            candidate_set,
4804            rank_window: options.rank_window,
4805            fusion_weights: options.fusion_weights,
4806            document_count,
4807            filtered_document_count,
4808            projection_freshness,
4809        })
4810    }
4811
4812    fn require_search_capabilities(&self, mode: SearchMode) -> Result<()> {
4813        if matches!(mode, SearchMode::Text | SearchMode::Hybrid) {
4814            self.runtime_capabilities
4815                .require(RuntimeCapability::FullTextSearch)?;
4816        }
4817        if matches!(mode, SearchMode::Vector | SearchMode::Hybrid) {
4818            self.runtime_capabilities
4819                .require(RuntimeCapability::VectorSearch)?;
4820        }
4821        Ok(())
4822    }
4823
4824    pub fn mark_full_reindex_needed(&self, reason: &str) -> Result<()> {
4825        self.append_marker(FULL_REINDEX_MARKER, reason)
4826    }
4827
4828    pub fn full_reindex_needed(&self) -> bool {
4829        self.read_marker_lines(FULL_REINDEX_MARKER)
4830            .map(|lines| !lines.is_empty())
4831            .unwrap_or(false)
4832    }
4833
4834    pub fn mark_metadata_repair_needed(&self, reason: &str) -> Result<()> {
4835        self.write_marker(METADATA_REPAIR_MARKER, reason)
4836    }
4837
4838    pub fn metadata_repair_needed(&self) -> bool {
4839        self.read_marker_lines(METADATA_REPAIR_MARKER)
4840            .map(|lines| !lines.is_empty())
4841            .unwrap_or(false)
4842    }
4843
4844    fn validate_or_set_dimension(&mut self, dimension: usize) -> Result<()> {
4845        if let Some(manifest) = &self.embedding_manifest
4846            && manifest.dimension != dimension
4847        {
4848            return Err(HawDBError::Storage(format!(
4849                "embedding dimension mismatch: manifest expects {}, row has {dimension}",
4850                manifest.dimension
4851            )));
4852        }
4853        match self.embedding_dimension {
4854            Some(existing) if existing != dimension => Err(HawDBError::Storage(format!(
4855                "embedding dimension mismatch: index has {existing}, row has {dimension}"
4856            ))),
4857            Some(_) => Ok(()),
4858            None => {
4859                self.embedding_dimension = Some(dimension);
4860                Ok(())
4861            }
4862        }
4863    }
4864
4865    fn load_snapshot(&mut self) -> Result<()> {
4866        let Some(path) = &self.path else {
4867            return Ok(());
4868        };
4869        let snapshot_path = path.join(SEARCH_SNAPSHOT_FILE);
4870        if !fs::try_exists(&snapshot_path)? {
4871            return Ok(());
4872        }
4873        let text = read_search_snapshot_text(&snapshot_path)?;
4874        self.parse_snapshot_text(&text)
4875    }
4876
4877    /// Read the registered snapshot through the original native directory.
4878    /// A saved pathname may now designate another projection namespace.
4879    fn load_snapshot_from_publication(
4880        &mut self,
4881        publication: &out_of_core::SearchProjectionPublishLease,
4882    ) -> Result<()> {
4883        let mut file = publication.open_captured_child(SEARCH_SNAPSHOT_FILE)?;
4884        let mut bytes = Vec::new();
4885        file.read_to_end(&mut bytes)?;
4886        let text = decode_search_snapshot_envelope(&bytes)?;
4887        self.parse_snapshot_text(&text)
4888    }
4889
4890    fn parse_snapshot_text(&mut self, text: &str) -> Result<()> {
4891        let (body, checksum) = split_checksum(text)?;
4892        let actual = checksum_bytes(body.as_bytes());
4893        if checksum != actual {
4894            return Err(HawDBError::Storage(format!(
4895                "search projection checksum mismatch: expected {checksum}, got {actual}"
4896            )));
4897        }
4898        for line in body.lines() {
4899            if line == "HAWDB_SEARCH_PROJECTION_V1" {
4900                continue;
4901            }
4902            let fields = line.split('\t').collect::<Vec<_>>();
4903            match fields.as_slice() {
4904                ["canonical_vector_source_epoch", epoch] => {
4905                    if self.canonical_vector_source_epoch.is_some() {
4906                        return Err(vector_index::invalid("duplicate canonical vector source"));
4907                    }
4908                    self.canonical_vector_source_epoch =
4909                        Some(parse_u64(epoch, "canonical vector source epoch")?);
4910                }
4911                ["vector_document_summary", documents, vectors, digest] => {
4912                    if self.vector_document_summary.is_some() || !self.documents.is_empty() {
4913                        return Err(vector_index::invalid(
4914                            "duplicate or misplaced vector summary",
4915                        ));
4916                    }
4917                    let summary = vector_index::VectorDocumentSummary {
4918                        document_count: parse_usize(documents, "logical vector documents")?,
4919                        vector_document_count: parse_usize(vectors, "vector-bearing documents")?,
4920                        documents_digest: parse_u64(digest, "vector documents digest")?,
4921                    };
4922                    summary.validate()?;
4923                    self.vector_document_summary = Some(summary);
4924                }
4925                ["vector_scoring", "linear_squared_l2"] => {
4926                    if !self.vector_scoring.is_default() || !self.documents.is_empty() {
4927                        return Err(vector_index::invalid(
4928                            "duplicate or misplaced vector scoring",
4929                        ));
4930                    }
4931                    self.vector_scoring = SearchVectorScoring::LinearSquaredL2;
4932                }
4933                ["vector_index_binding", encoded] => {
4934                    if self.vector_index_descriptor.is_some() || !self.documents.is_empty() {
4935                        return Err(HawDBError::StorageIntegrity(
4936                            "duplicate or misplaced vector index binding".into(),
4937                        ));
4938                    }
4939                    self.restore_vector_index(vector_index::decode(encoded)?);
4940                }
4941                ["projection_consumer_binding", database, projection, id, registration, checkpoint] =>
4942                {
4943                    if body.lines().nth(1) != Some(line) {
4944                        return Err(HawDBError::Storage(
4945                            "projection consumer binding must follow the snapshot header".into(),
4946                        ));
4947                    }
4948                    if self.consumer_binding.is_some() {
4949                        return Err(HawDBError::Storage(
4950                            "duplicate projection consumer binding".into(),
4951                        ));
4952                    }
4953                    self.consumer_binding = Some(consumer::ConsumerBinding::parse(
4954                        database,
4955                        projection,
4956                        id,
4957                        registration,
4958                        checkpoint,
4959                    )?);
4960                }
4961                ["source_graph_commit_epoch", raw] => {
4962                    if self.source_graph_commit_epoch.is_some() {
4963                        return Err(HawDBError::Storage(
4964                            "duplicate projection source epoch".into(),
4965                        ));
4966                    }
4967                    let epoch = parse_u64(raw, "source graph commit epoch")?;
4968                    self.source_graph_commit_epoch = Some(epoch);
4969                    *self
4970                        .durable_source_graph_commit_epoch
4971                        .get_mut()
4972                        .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(epoch);
4973                }
4974                ["import_source_graph_commit_epoch", raw] => {
4975                    self.import_source_graph_commit_epoch =
4976                        Some(parse_u64(raw, "import source graph commit epoch")?);
4977                }
4978                ["embedding_manifest", raw_model, raw_version, raw_dimension] => {
4979                    let version = decode_string(raw_version)?;
4980                    let manifest = SearchEmbeddingManifest {
4981                        model: decode_string(raw_model)?,
4982                        version: if version.is_empty() {
4983                            None
4984                        } else {
4985                            Some(version)
4986                        },
4987                        dimension: parse_usize(raw_dimension, "embedding manifest dimension")?,
4988                    };
4989                    self.embedding_dimension = Some(manifest.dimension);
4990                    self.embedding_manifest = Some(manifest);
4991                    #[cfg(feature = "vector-search")]
4992                    self.resident_diskann.reset();
4993                }
4994                ["rabitq_checkpoint", bits, rows, seed] => {
4995                    let bits = parse_u64(bits, "RaBitQ bit width")?;
4996                    let rows = parse_usize(rows, "RaBitQ segment rows")?;
4997                    let seed = parse_u64(seed, "RaBitQ seed")?;
4998                    if self.rabitq_checkpoint.is_some()
4999                        || !matches!(bits, 1 | 4)
5000                        || rows == 0
5001                        || rows > u32::MAX as usize
5002                    {
5003                        return Err(HawDBError::StorageIntegrity(
5004                            "invalid explicit RaBitQ checkpoint settings".into(),
5005                        ));
5006                    }
5007                    self.rabitq_checkpoint = Some((bits as u8, rows, seed));
5008                    #[cfg(feature = "vector-search")]
5009                    {
5010                        self.rabitq_build_options.bit_width = if bits == 1 {
5011                            hawdb_vector_projection::RaBitQBitWidth::One
5012                        } else {
5013                            hawdb_vector_projection::RaBitQBitWidth::Four
5014                        };
5015                        self.rabitq_build_options.segment_rows = rows;
5016                        self.rabitq_build_options.transform_seed = seed;
5017                    }
5018                }
5019                ["embedding_dimension", raw] => {
5020                    let dimension = parse_usize(raw, "embedding dimension")?;
5021                    if let Some(manifest) = &self.embedding_manifest
5022                        && manifest.dimension != dimension
5023                    {
5024                        return Err(HawDBError::Storage(format!(
5025                                "embedding manifest dimension {} does not match snapshot dimension {dimension}",
5026                                manifest.dimension
5027                            )));
5028                    }
5029                    self.embedding_dimension = Some(dimension);
5030                }
5031                ["doc", raw_id, raw_title, raw_content, raw_embedding, raw_metadata] => {
5032                    if self.vector_document_summary.is_some() {
5033                        return Err(vector_index::invalid(
5034                            "vector summary cannot contain resident rows",
5035                        ));
5036                    }
5037                    let embedding = decode_embedding(raw_embedding)?;
5038                    if let Some(embedding) = &embedding {
5039                        vector_index::validate_embedding(
5040                            self.vector_index_descriptor.as_ref(),
5041                            embedding,
5042                            || Ok(()),
5043                        )?;
5044                        self.validate_or_set_dimension(embedding.len())?;
5045                    }
5046                    let document = SearchDocument {
5047                        id: decode_string(raw_id)?,
5048                        title: decode_string(raw_title)?,
5049                        content: decode_string(raw_content)?,
5050                        embedding,
5051                        metadata: decode_metadata(raw_metadata)?,
5052                    };
5053                    self.documents.insert(document.id.clone(), document);
5054                }
5055                [""] => {}
5056                _ => {
5057                    return Err(HawDBError::Storage(format!(
5058                        "invalid search projection line: {line}"
5059                    )));
5060                }
5061            }
5062        }
5063        if self.vector_document_summary.is_some()
5064            && (self.vector_index_descriptor.is_none() || self.consumer_binding.is_none())
5065        {
5066            return Err(vector_index::invalid(
5067                "vector summary requires a bound Consumer",
5068            ));
5069        }
5070        if self.canonical_vector_source_epoch.is_some()
5071            && (self.canonical_vector_source_epoch != self.source_graph_commit_epoch
5072                || !self
5073                    .vector_document_summary
5074                    .is_some_and(|summary| summary.document_count == summary.vector_document_count))
5075        {
5076            return Err(vector_index::invalid(
5077                "canonical vector source requires a complete vector-only summary at the same epoch",
5078            ));
5079        }
5080        if self
5081            .vector_index_descriptor
5082            .as_ref()
5083            .is_some_and(|binding| {
5084                self.embedding_dimension != Some(binding.dimension().get() as usize)
5085            })
5086        {
5087            return Err(HawDBError::StorageIntegrity(
5088                "vector index snapshot dimension mismatch".into(),
5089            ));
5090        }
5091        if self.consumer_binding.is_some()
5092            && (self.source_graph_commit_epoch.is_none()
5093                || self
5094                    .import_source_graph_commit_epoch
5095                    .zip(self.source_graph_commit_epoch)
5096                    .is_some_and(|(import, source)| import > source))
5097        {
5098            return Err(HawDBError::Storage(
5099                "invalid registered projection epochs".into(),
5100            ));
5101        }
5102        self.vector_scoring
5103            .validate(self.vector_index_descriptor.is_some())?;
5104        Ok(())
5105    }
5106
5107    fn load_or_rebuild_segment_descriptor(&mut self) -> Result<()> {
5108        let Some(path) = &self.path else {
5109            return Ok(());
5110        };
5111        self.segment_descriptor = (match read_search_segment_descriptor(path) {
5112            Ok(Some(descriptor))
5113                if descriptor.matches_documents(&self.documents)
5114                    && descriptor.payload_artifact_is_available(path)? =>
5115            {
5116                Some(descriptor)
5117            }
5118            Ok(None) => Some(SearchSegmentDescriptor::build(&self.documents)),
5119            Err(error @ HawDBError::FileDescriptors(_)) => return Err(error),
5120            Ok(Some(_)) | Err(_) => {
5121                quarantine_rebuildable_artifact(path, SEARCH_SEGMENT_DESCRIPTOR_FILE);
5122                let descriptor = SearchSegmentDescriptor::build(&self.documents);
5123                let _ = write_search_segment_descriptor(path, &descriptor);
5124                Some(descriptor)
5125            }
5126        })
5127        .map(Arc::new);
5128        Ok(())
5129    }
5130
5131    fn marker_path(&self, name: &str) -> Option<PathBuf> {
5132        self.path.as_ref().map(|path| path.join(name))
5133    }
5134
5135    fn append_marker(&self, name: &str, reason: &str) -> Result<()> {
5136        let _marker_authority = self.require_marker_mutation()?;
5137        {
5138            let mut marker_lines = self
5139                .marker_lines
5140                .lock()
5141                .unwrap_or_else(|poisoned| poisoned.into_inner());
5142            let lines = marker_lines.entry(name.to_string()).or_default();
5143            if !lines.iter().any(|line| line == reason) {
5144                lines.push(reason.to_string());
5145            }
5146        }
5147        let Some(path) = self.marker_path(name) else {
5148            return Ok(());
5149        };
5150        let existing = fs::read_to_string(&path).unwrap_or_default();
5151        if existing.lines().any(|line| line == reason) {
5152            return Ok(());
5153        }
5154        let next = if existing.trim().is_empty() {
5155            reason.to_string()
5156        } else {
5157            format!("{}\n{reason}", existing.trim())
5158        };
5159        fs::write(path, next)?;
5160        Ok(())
5161    }
5162
5163    fn write_marker(&self, name: &str, reason: &str) -> Result<()> {
5164        let _marker_authority = self.require_marker_mutation()?;
5165        self.marker_lines
5166            .lock()
5167            .unwrap_or_else(|poisoned| poisoned.into_inner())
5168            .insert(name.to_string(), vec![reason.to_string()]);
5169        let Some(path) = self.marker_path(name) else {
5170            return Ok(());
5171        };
5172        fs::write(path, reason)?;
5173        Ok(())
5174    }
5175
5176    fn clear_marker(&self, name: &str) -> Result<()> {
5177        let _marker_authority = self.require_marker_mutation()?;
5178        self.marker_lines
5179            .lock()
5180            .unwrap_or_else(|poisoned| poisoned.into_inner())
5181            .remove(name);
5182        let Some(path) = self.marker_path(name) else {
5183            return Ok(());
5184        };
5185        match fs::remove_file(path) {
5186            Ok(()) => Ok(()),
5187            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
5188            Err(error) => Err(error.into()),
5189        }
5190    }
5191
5192    fn read_marker_lines(&self, name: &str) -> Result<Vec<String>> {
5193        let Some(path) = self.marker_path(name) else {
5194            return Ok(self
5195                .marker_lines
5196                .lock()
5197                .unwrap_or_else(|poisoned| poisoned.into_inner())
5198                .get(name)
5199                .cloned()
5200                .unwrap_or_default());
5201        };
5202        let content = fs::read_to_string(path).unwrap_or_default();
5203        Ok(content
5204            .lines()
5205            .map(str::trim)
5206            .filter(|line| !line.is_empty())
5207            .map(str::to_string)
5208            .collect())
5209    }
5210}
5211
5212impl Default for SearchIndex {
5213    fn default() -> Self {
5214        Self {
5215            read_generation: Mutex::default(),
5216            read_freshness: None,
5217            documents: ResidentDocuments::default(),
5218            consumer_binding: None,
5219            consumer_binding_valid: true,
5220            consumer_owner: std::sync::Weak::new(),
5221            consumer_mutation_generation: None,
5222            consumer_receipt: Mutex::new(None),
5223            path: None,
5224            _project_files: None,
5225            embedding_dimension: None,
5226            rabitq_checkpoint: None,
5227            embedding_manifest: None,
5228            vector_index_descriptor: None,
5229            vector_scoring: SearchVectorScoring::default(),
5230            vector_document_summary: None,
5231            canonical_vector_source_epoch: None,
5232            canonical_vector_delta: None,
5233            import_source_graph_commit_epoch: None,
5234            source_graph_commit_epoch: None,
5235            durable_source_graph_commit_epoch: Mutex::new(None),
5236            artifact_source_graph_commit_epoch: Mutex::new(None),
5237            marker_lines: Mutex::new(BTreeMap::new()),
5238            analyzer_lexicon: Arc::default(),
5239            lexical_projection: Mutex::new(None),
5240            lexical_delta: Mutex::new(Arc::default()),
5241            lexical_config: LexicalProjectionConfig::default(),
5242            #[cfg(feature = "vector-search")]
5243            rabitq_projection: Mutex::new(None),
5244            #[cfg(feature = "vector-search")]
5245            resident_diskann: Default::default(),
5246            #[cfg(feature = "vector-search")]
5247            rabitq_build_options: RaBitQCandidateProjectionBuildOptions::default(),
5248            segment_descriptor: None,
5249            segment_payload_reader: None,
5250            range_read_config: SearchRangeReadConfig::default(),
5251            cleanup_state: Mutex::new(SearchProjectionCleanupState::default()),
5252            cleanup_options: SearchProjectionCleanupOptions::default(),
5253            runtime_capabilities: crate::compiled_runtime_capabilities(),
5254            telemetry: None,
5255            externally_owned_kinds: BTreeSet::new(),
5256        }
5257    }
5258}
5259
5260fn quarantine_rebuildable_artifact(parent: &Path, name: &str) {
5261    let source = parent.join(name);
5262    if !source.exists() {
5263        return;
5264    }
5265    let sequence = QUARANTINE_SEQUENCE.fetch_add(1, AtomicOrdering::Relaxed);
5266    let quarantine_name = format!("{name}.corrupt.{}.{}", std::process::id(), sequence);
5267    let _ = fs::rename(source, parent.join(quarantine_name));
5268}
5269
5270#[cfg(feature = "vector-search")]
5271fn rabitq_artifact_file(generation: u64) -> String {
5272    format!("{SEARCH_RABITQ_PROJECTION_PREFIX}{generation}{SEARCH_RABITQ_PROJECTION_SUFFIX}")
5273}
5274
5275#[cfg(feature = "vector-search")]
5276fn rabitq_artifact_generation(name: &str) -> Option<u64> {
5277    name.strip_prefix(SEARCH_RABITQ_PROJECTION_PREFIX)
5278        .and_then(|value| value.strip_suffix(SEARCH_RABITQ_PROJECTION_SUFFIX))
5279        .and_then(|value| value.parse().ok())
5280}
5281
5282#[cfg(feature = "vector-search")]
5283fn latest_rabitq_artifact(path: &Path) -> Result<Option<(u64, PathBuf)>> {
5284    Ok(rabitq_artifacts_descending(path)?.into_iter().next())
5285}
5286
5287#[cfg(feature = "vector-search")]
5288fn rabitq_artifacts_descending(path: &Path) -> Result<Vec<(u64, PathBuf)>> {
5289    let entries = match fs::read_dir(path) {
5290        Ok(entries) => entries,
5291        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
5292        Err(error) => return Err(error.into()),
5293    };
5294    let mut artifacts = Vec::new();
5295    for entry in entries {
5296        let entry = entry?;
5297        if let Some(generation) = entry
5298            .file_name()
5299            .to_str()
5300            .and_then(rabitq_artifact_generation)
5301        {
5302            artifacts.push((generation, entry.path()));
5303        }
5304    }
5305    artifacts.sort_unstable_by_key(|(generation, _)| std::cmp::Reverse(*generation));
5306    Ok(artifacts)
5307}
5308
5309#[cfg(feature = "vector-search")]
5310fn rabitq_artifacts_descending_under_publication(
5311    publication: &out_of_core::SearchProjectionPublishLease,
5312) -> Result<Vec<(u64, String)>> {
5313    const MAX_REGISTERED_ARTIFACT_NAMES: usize = 4096;
5314    let mut artifacts = Vec::new();
5315    publication.with_captured_directory(|directory| {
5316        directory.visit_children(
5317            &directory.operation_context(),
5318            MAX_REGISTERED_ARTIFACT_NAMES,
5319            |name| {
5320                if let Some(generation) = rabitq_artifact_generation(name) {
5321                    artifacts.push((generation, name.to_owned()));
5322                }
5323                Ok(())
5324            },
5325        )
5326    })?;
5327    artifacts.sort_unstable_by_key(|(generation, _)| std::cmp::Reverse(*generation));
5328    Ok(artifacts)
5329}
5330
5331const NOWLEDGE_SEARCH_PROJECTION_TABLES: &[(&str, &str, bool)] = &[
5332    ("memories_index", "memory", true),
5333    ("messages_index", "message", false),
5334    ("communities_index", "community", true),
5335    ("entities_index", "entity", true),
5336    ("sources_index", "source", true),
5337    ("source_chunks_index", "source_chunk", true),
5338];
5339
5340fn search_projection_probe_table_reports(
5341    documents: &impl DocumentView,
5342    embedding_dimension: Option<usize>,
5343) -> Vec<serde_json::Value> {
5344    NOWLEDGE_SEARCH_PROJECTION_TABLES
5345        .iter()
5346        .map(|(table_name, kind, requires_vector)| {
5347            let table_documents = documents
5348                .values()
5349                .filter(|document| {
5350                    document
5351                        .metadata
5352                        .get("kind")
5353                        .is_some_and(|value| value == kind)
5354                })
5355                .collect::<Vec<_>>();
5356            let present = !table_documents.is_empty();
5357            let has_text = table_documents
5358                .iter()
5359                .any(|document| !document.title.is_empty() || !document.content.is_empty());
5360            let vectors_match = !*requires_vector
5361                || table_documents.iter().all(|document| {
5362                    document.embedding.as_ref().is_some_and(|embedding| {
5363                        embedding_dimension.is_none_or(|dimension| embedding.len() == dimension)
5364                    })
5365                });
5366            let vector_ready = !*requires_vector || (present && vectors_match);
5367            let mut blocker_codes = Vec::new();
5368            if !present {
5369                blocker_codes.push("missing_table_rows");
5370            }
5371            if !has_text {
5372                blocker_codes.push("missing_searchable_text");
5373            }
5374            if *requires_vector && !vector_ready {
5375                blocker_codes.push("missing_or_mismatched_vectors");
5376            }
5377            serde_json::json!({
5378                "name": table_name,
5379                "kind": kind,
5380                "present": present,
5381                "fts_ready": present && has_text,
5382                "vector_ready": vector_ready,
5383                "row_count": table_documents.len(),
5384                "requires_vector": requires_vector,
5385                "blocker_codes": blocker_codes,
5386            })
5387        })
5388        .collect()
5389}
5390
5391fn search_projection_probe_document_identity_report(
5392    documents: &impl DocumentView,
5393) -> serde_json::Value {
5394    let mut body = String::new();
5395    for document_id in documents.keys() {
5396        body.push_str(document_id);
5397        body.push('\n');
5398    }
5399    serde_json::json!({
5400        "ready": true,
5401        "id_space": "search_projection_document_id",
5402        "representation": "sorted_document_ids",
5403        "document_count": documents.len(),
5404        "checksum": checksum_bytes(body.as_bytes()),
5405    })
5406}
5407
5408fn search_projection_probe_predicate_pushdown_report(index: &SearchIndex) -> serde_json::Value {
5409    let segment_descriptor_ready = index
5410        .segment_descriptor
5411        .as_deref()
5412        .is_some_and(|descriptor| descriptor.matches_documents(&index.documents));
5413    let transient_descriptor;
5414    let descriptor = match index
5415        .segment_descriptor
5416        .as_deref()
5417        .filter(|descriptor| descriptor.matches_documents(&index.documents))
5418    {
5419        Some(descriptor) => Some(descriptor),
5420        None if !index.documents.is_empty() => {
5421            transient_descriptor = SearchSegmentDescriptor::build(&index.documents);
5422            Some(&transient_descriptor)
5423        }
5424        None => None,
5425    };
5426    let segment_descriptor_field_summaries = descriptor
5427        .map(search_projection_probe_segment_descriptor_field_summaries)
5428        .unwrap_or_default();
5429    let segment_document_pruning = descriptor
5430        .map(search_projection_probe_segment_document_pruning_report)
5431        .unwrap_or_default();
5432    let physical_segment_range_count = descriptor
5433        .map(|descriptor| descriptor.physical_read_ranges().len())
5434        .unwrap_or_default();
5435    let physical_segment_ranges_ready = descriptor.is_some_and(|descriptor| {
5436        physical_segment_range_count == descriptor.segments.len()
5437            && index.path.as_ref().is_some_and(|path| {
5438                descriptor
5439                    .payload_artifact_is_available(path)
5440                    .unwrap_or(false)
5441            })
5442    });
5443    serde_json::json!({
5444        "ready": true,
5445        "equality_ready": true,
5446        "in_list_ready": true,
5447        "not_in_list_ready": true,
5448        "range_ready": true,
5449        "row_filter_ready": true,
5450        "segment_pruning_ready": true,
5451        "numeric_min_max_ready": true,
5452        "timestamp_min_max_ready": true,
5453        "persisted_segment_descriptor_ready": segment_descriptor_ready,
5454        "physical_segment_ranges_ready": physical_segment_ranges_ready,
5455        "physical_segment_range_count": physical_segment_range_count,
5456        "supported_ops": ["eq", "in", "not_in", "gt", "gte", "lt", "lte"],
5457        "scan_filter_fields": NOWLEDGE_SEARCH_PROJECTION_SCAN_FILTER_FIELDS,
5458        "segment_descriptor_field_count": segment_descriptor_field_summaries.len(),
5459        "segment_descriptor_field_summaries": segment_descriptor_field_summaries,
5460        "segment_document_pruning_ready": segment_document_pruning.ready,
5461        "segment_pruning_candidate_document_count": segment_document_pruning.candidate_document_count,
5462        "segment_pruned_document_count": segment_document_pruning.pruned_document_count,
5463        "segment_scanned_document_count": segment_document_pruning.scanned_document_count,
5464    })
5465}
5466
5467#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
5468struct SearchProjectionProbeSegmentDocumentPruningReport {
5469    ready: bool,
5470    candidate_document_count: usize,
5471    pruned_document_count: usize,
5472    scanned_document_count: usize,
5473}
5474
5475fn search_projection_probe_segment_document_pruning_report(
5476    descriptor: &SearchSegmentDescriptor,
5477) -> SearchProjectionProbeSegmentDocumentPruningReport {
5478    let Some(first_segment) = descriptor.segments.first() else {
5479        return SearchProjectionProbeSegmentDocumentPruningReport::default();
5480    };
5481    if first_segment.first_document_id.is_empty() {
5482        return SearchProjectionProbeSegmentDocumentPruningReport::default();
5483    }
5484    let predicates = SearchPredicateSet::new(vec![SearchPredicate::eq(
5485        SEARCH_DOCUMENT_ID_FIELD,
5486        first_segment.first_document_id.clone(),
5487    )]);
5488    let mut pruned_document_count = 0;
5489    let mut scanned_document_count = 0;
5490    for segment in &descriptor.segments {
5491        if segment.may_match_predicates(&predicates) {
5492            scanned_document_count += segment.document_count;
5493        } else {
5494            pruned_document_count += segment.document_count;
5495        }
5496    }
5497    let ready = descriptor.document_count > 0
5498        && pruned_document_count > 0
5499        && scanned_document_count > 0
5500        && pruned_document_count + scanned_document_count == descriptor.document_count;
5501    SearchProjectionProbeSegmentDocumentPruningReport {
5502        ready,
5503        candidate_document_count: descriptor.document_count,
5504        pruned_document_count,
5505        scanned_document_count,
5506    }
5507}
5508
5509fn search_projection_probe_production_filter_pruning_report(
5510    index: &SearchIndex,
5511) -> serde_json::Value {
5512    let Some(descriptor) = index
5513        .segment_descriptor
5514        .as_deref()
5515        .filter(|descriptor| descriptor.matches_documents(&index.documents))
5516    else {
5517        return serde_json::json!({
5518            "ready": false,
5519            "persisted_segment_descriptor_used": false,
5520            "payload_read_avoidance_ready": false,
5521            "sample_count": 0,
5522            "ready_field_count": 0,
5523            "required_field_count": NOWLEDGE_SEARCH_PROJECTION_SCAN_FILTER_FIELDS.len(),
5524            "missing_fields": NOWLEDGE_SEARCH_PROJECTION_SCAN_FILTER_FIELDS,
5525            "samples": [],
5526        });
5527    };
5528
5529    let mut samples = NOWLEDGE_SEARCH_PROJECTION_SCAN_FILTER_FIELDS
5530        .iter()
5531        .map(|field| search_projection_probe_production_filter_sample(descriptor, field))
5532        .collect::<Vec<_>>();
5533    let missing_fields = samples
5534        .iter()
5535        .filter(|sample| !sample.ready)
5536        .map(|sample| sample.field)
5537        .collect::<Vec<_>>();
5538    let ready_field_count = NOWLEDGE_SEARCH_PROJECTION_SCAN_FILTER_FIELDS
5539        .len()
5540        .saturating_sub(missing_fields.len());
5541    samples.push(search_projection_probe_production_filter_sample(
5542        descriptor,
5543        SEARCH_DOCUMENT_ID_FIELD,
5544    ));
5545    let payload_read_avoidance_ready = samples
5546        .iter()
5547        .any(|sample| sample.segment_pruned_document_count > 0);
5548    let explain_analyze_ready = samples.iter().all(|sample| sample.explain_analyze_ready);
5549    let ready = missing_fields.is_empty() && payload_read_avoidance_ready && explain_analyze_ready;
5550    serde_json::json!({
5551        "ready": ready,
5552        "persisted_segment_descriptor_used": true,
5553        "payload_read_avoidance_ready": payload_read_avoidance_ready,
5554        "explain_analyze_ready": explain_analyze_ready,
5555        "sample_count": samples.len(),
5556        "ready_field_count": ready_field_count,
5557        "required_field_count": NOWLEDGE_SEARCH_PROJECTION_SCAN_FILTER_FIELDS.len(),
5558        "missing_fields": missing_fields,
5559        "samples": samples
5560            .into_iter()
5561            .map(SearchProjectionProbeProductionFilterSample::json)
5562            .collect::<Vec<_>>(),
5563    })
5564}
5565
5566#[derive(Debug, Clone, PartialEq, Eq)]
5567struct SearchProjectionProbeProductionFilterSample<'a> {
5568    field: &'a str,
5569    operation: &'static str,
5570    operation_family: &'static str,
5571    value_kind: &'static str,
5572    ready: bool,
5573    capability_ready: bool,
5574    persisted_segment_descriptor_used: bool,
5575    segment_count: usize,
5576    scanned_segment_count: usize,
5577    pruned_segment_count: usize,
5578    segment_pruning_candidate_document_count: usize,
5579    segment_scanned_document_count: usize,
5580    segment_pruned_document_count: usize,
5581    field_report_count: usize,
5582    value_summary_used: bool,
5583    numeric_range_summary_used: bool,
5584    timestamp_range_summary_used: bool,
5585    normalized_default_equality: bool,
5586    unique_key_lookup: bool,
5587    explain_analyze_ready: bool,
5588}
5589
5590impl SearchProjectionProbeProductionFilterSample<'_> {
5591    fn json(self) -> serde_json::Value {
5592        serde_json::json!({
5593            "field": self.field,
5594            "operation": self.operation,
5595            "operation_family": self.operation_family,
5596            "value_kind": self.value_kind,
5597            "ready": self.ready,
5598            "capability_ready": self.capability_ready,
5599            "persisted_segment_descriptor_used": self.persisted_segment_descriptor_used,
5600            "segment_count": self.segment_count,
5601            "scanned_segment_count": self.scanned_segment_count,
5602            "pruned_segment_count": self.pruned_segment_count,
5603            "segment_pruning_candidate_document_count": self.segment_pruning_candidate_document_count,
5604            "segment_scanned_document_count": self.segment_scanned_document_count,
5605            "segment_pruned_document_count": self.segment_pruned_document_count,
5606            "field_report_count": self.field_report_count,
5607            "value_summary_used": self.value_summary_used,
5608            "numeric_range_summary_used": self.numeric_range_summary_used,
5609            "timestamp_range_summary_used": self.timestamp_range_summary_used,
5610            "normalized_default_equality": self.normalized_default_equality,
5611            "unique_key_lookup": self.unique_key_lookup,
5612            "explain_analyze": {
5613                "ready": self.explain_analyze_ready,
5614                "operator": "search_projection_segment_scan",
5615                "segment_count": self.segment_count,
5616                "scanned_segment_count": self.scanned_segment_count,
5617                "pruned_segment_count": self.pruned_segment_count,
5618                "candidate_document_count": self.segment_pruning_candidate_document_count,
5619                "scanned_document_count": self.segment_scanned_document_count,
5620                "pruned_document_count": self.segment_pruned_document_count,
5621                "payload_read_avoidance": self.segment_pruned_document_count > 0,
5622            },
5623        })
5624    }
5625}
5626
5627fn search_projection_probe_production_filter_sample<'a>(
5628    descriptor: &SearchSegmentDescriptor,
5629    field: &'a str,
5630) -> SearchProjectionProbeProductionFilterSample<'a> {
5631    let value_kind = search_projection_probe_production_filter_value_kind(field);
5632    let operation_family = search_projection_probe_production_filter_operation_family(field);
5633    let (operation, predicate) =
5634        search_projection_probe_production_filter_predicate(descriptor, field);
5635    let predicates = SearchPredicateSet::new(vec![predicate]);
5636    let pruning = explain_search_segments_with_persisted_descriptor(&predicates, descriptor);
5637    let field_reports = pruning
5638        .field_summaries
5639        .iter()
5640        .filter(|summary| summary.field == field)
5641        .collect::<Vec<_>>();
5642    let value_summary_used = field_reports
5643        .iter()
5644        .any(|summary| summary.value_summary_used);
5645    let numeric_range_summary_used = field_reports
5646        .iter()
5647        .any(|summary| summary.numeric_range_summary_used);
5648    let timestamp_range_summary_used = field_reports
5649        .iter()
5650        .any(|summary| summary.timestamp_range_summary_used);
5651    let unique_key_lookup = field == SEARCH_DOCUMENT_ID_FIELD
5652        && descriptor.segments.iter().all(|segment| {
5653            segment.metadata.get(field).is_some_and(|summary| {
5654                summary.present_count == segment.document_count
5655                    && summary.values.len() == segment.document_count
5656            })
5657        });
5658    let capability_ready = match operation_family {
5659        "numeric_range" => numeric_range_summary_used,
5660        "timestamp_range" => timestamp_range_summary_used || numeric_range_summary_used,
5661        "unique_key" => unique_key_lookup,
5662        _ => value_summary_used,
5663    };
5664    let ready = pruning.persisted_segment_descriptor_used
5665        && pruning.segment_count > 0
5666        && pruning.segment_pruning_candidate_document_count == descriptor.document_count
5667        && field_reports.len() == 1
5668        && capability_ready;
5669    let explain_analyze_ready = pruning.persisted_segment_descriptor_used
5670        && pruning.segment_count > 0
5671        && pruning.segment_pruning_candidate_document_count == descriptor.document_count
5672        && pruning.segment_pruned_document_count + pruning.segment_scanned_document_count
5673            == descriptor.document_count;
5674    SearchProjectionProbeProductionFilterSample {
5675        field,
5676        operation,
5677        operation_family,
5678        value_kind,
5679        ready,
5680        capability_ready,
5681        persisted_segment_descriptor_used: pruning.persisted_segment_descriptor_used,
5682        segment_count: pruning.segment_count,
5683        scanned_segment_count: pruning.scanned_segment_count,
5684        pruned_segment_count: pruning.pruned_segment_count,
5685        segment_pruning_candidate_document_count: pruning.segment_pruning_candidate_document_count,
5686        segment_scanned_document_count: pruning.segment_scanned_document_count,
5687        segment_pruned_document_count: pruning.segment_pruned_document_count,
5688        field_report_count: field_reports.len(),
5689        value_summary_used,
5690        numeric_range_summary_used,
5691        timestamp_range_summary_used,
5692        normalized_default_equality: operation_family == "normalized_default_equality",
5693        unique_key_lookup,
5694        explain_analyze_ready,
5695    }
5696}
5697
5698fn explain_search_segments_with_persisted_descriptor(
5699    predicates: &SearchPredicateSet,
5700    descriptor: &SearchSegmentDescriptor,
5701) -> FilteredSearchDocuments<'static> {
5702    let mut pruned_segment_count = 0;
5703    let mut scanned_segment_count = 0;
5704    let mut pruned_document_count = 0;
5705    let mut scanned_document_count = 0;
5706    let mut field_pruning = SearchFieldPruningAccumulator::new(predicates);
5707
5708    for segment in &descriptor.segments {
5709        field_pruning.observe_persisted_segment(segment, predicates);
5710        if !segment.may_match_predicates(predicates) {
5711            pruned_segment_count += 1;
5712            pruned_document_count += segment.document_count;
5713            continue;
5714        }
5715        scanned_segment_count += 1;
5716        scanned_document_count += segment.document_count;
5717    }
5718
5719    FilteredSearchDocuments {
5720        documents: Vec::new(),
5721        segment_count: descriptor.segments.len(),
5722        pruned_segment_count,
5723        scanned_segment_count,
5724        segment_pruning_candidate_document_count: descriptor.document_count,
5725        segment_pruned_document_count: pruned_document_count,
5726        segment_scanned_document_count: scanned_document_count,
5727        persisted_segment_descriptor_used: true,
5728        field_summaries: field_pruning.into_reports(),
5729    }
5730}
5731
5732fn search_projection_probe_production_filter_predicate(
5733    descriptor: &SearchSegmentDescriptor,
5734    field: &str,
5735) -> (&'static str, SearchPredicate) {
5736    let value = descriptor
5737        .segments
5738        .iter()
5739        .filter_map(|segment| segment.metadata.get(field))
5740        .find_map(|summary| {
5741            summary
5742                .values
5743                .iter()
5744                .next()
5745                .cloned()
5746                .or_else(|| summary.numeric_range.map(|range| range.min.to_string()))
5747                .or_else(|| {
5748                    summary
5749                        .timestamp_range
5750                        .map(|range| range.min_epoch_millis.to_string())
5751                })
5752        })
5753        .unwrap_or_default();
5754    match search_projection_probe_production_filter_operation_family(field) {
5755        "numeric_range" | "timestamp_range" => ("gte", SearchPredicate::gte(field, value)),
5756        "enum_in_list" => (
5757            "in",
5758            SearchPredicate::in_list(field, std::iter::once(value)),
5759        ),
5760        _ => ("eq", SearchPredicate::eq(field, value)),
5761    }
5762}
5763
5764fn search_projection_probe_production_filter_operation_family(field: &str) -> &'static str {
5765    match field {
5766        SEARCH_DOCUMENT_ID_FIELD => "unique_key",
5767        "unit_type" | "lifecycle_state" | "temporal_context" => "enum_in_list",
5768        "importance" | "confidence" => "numeric_range",
5769        "created_at" | "updated_at" | "event_start" | "event_end" => "timestamp_range",
5770        "is_latest" => "normalized_default_equality",
5771        _ => "equality",
5772    }
5773}
5774
5775fn search_projection_probe_production_filter_value_kind(field: &str) -> &'static str {
5776    match field {
5777        "importance" | "confidence" => "numeric_range",
5778        "created_at" | "updated_at" | "event_start" | "event_end" => "timestamp_range",
5779        _ => "value",
5780    }
5781}
5782
5783fn search_projection_probe_segment_descriptor_field_summaries(
5784    descriptor: &SearchSegmentDescriptor,
5785) -> Vec<serde_json::Value> {
5786    let mut fields = BTreeMap::<String, SearchProjectionProbeFieldSummary>::new();
5787    for segment in &descriptor.segments {
5788        for (field, summary) in &segment.metadata {
5789            let entry = fields.entry(field.clone()).or_default();
5790            entry.segment_count += 1;
5791            entry.present_document_count += summary.present_count;
5792            if !summary.values.is_empty() {
5793                entry.value_summary_segment_count += 1;
5794            }
5795            if summary.numeric_range.is_some() {
5796                entry.numeric_range_segment_count += 1;
5797            }
5798            if summary.timestamp_range.is_some() {
5799                entry.timestamp_range_segment_count += 1;
5800            }
5801            if field == SEARCH_DOCUMENT_ID_FIELD
5802                && summary.present_count == segment.document_count
5803                && summary.values.len() == segment.document_count
5804            {
5805                entry.unique_key_summary_segment_count += 1;
5806            }
5807        }
5808    }
5809    fields
5810        .into_iter()
5811        .map(|(field, summary)| {
5812            serde_json::json!({
5813                "field": field,
5814                "segment_count": summary.segment_count,
5815                "present_document_count": summary.present_document_count,
5816                "value_summary_used": summary.value_summary_segment_count > 0,
5817                "value_summary_segment_count": summary.value_summary_segment_count,
5818                "numeric_range_summary_used": summary.numeric_range_segment_count > 0,
5819                "numeric_range_segment_count": summary.numeric_range_segment_count,
5820                "timestamp_range_summary_used": summary.timestamp_range_segment_count > 0,
5821                "timestamp_range_segment_count": summary.timestamp_range_segment_count,
5822                "unique_key_summary_used": summary.unique_key_summary_segment_count > 0,
5823                "unique_key_summary_segment_count": summary.unique_key_summary_segment_count,
5824            })
5825        })
5826        .collect()
5827}
5828
5829#[derive(Debug, Clone, Default, PartialEq, Eq)]
5830struct SearchProjectionProbeFieldSummary {
5831    segment_count: usize,
5832    present_document_count: usize,
5833    value_summary_segment_count: usize,
5834    numeric_range_segment_count: usize,
5835    timestamp_range_segment_count: usize,
5836    unique_key_summary_segment_count: usize,
5837}
5838
5839#[cfg(feature = "vector-search")]
5840fn search_projection_probe_compressed_vector_projection_report(
5841    index: &SearchIndex,
5842) -> serde_json::Value {
5843    // This capability describes compiled dispatch support; per-query candidate
5844    // metrics report the actual selected kernel, including scalar fallback.
5845    let supports_runtime_simd_dispatch = cfg!(any(
5846        target_arch = "x86",
5847        target_arch = "x86_64",
5848        target_arch = "aarch64"
5849    ));
5850    let projection = index.rabitq_projection().or_else(|| {
5851        index
5852            .path
5853            .is_none()
5854            .then(|| index.build_in_memory_rabitq_projection().ok().flatten())
5855            .flatten()
5856    });
5857    match projection {
5858        Some(projection) => serde_json::json!({
5859            "engine": "hawdb_rabitq_scan",
5860            "compiled": true,
5861            "ready": true,
5862            "format_version": projection.manifest().format_version,
5863            "algorithm": projection.manifest().algorithm,
5864            "bit_width": projection.manifest().bit_width,
5865            "dimension": projection.manifest().dimension,
5866            "document_count": projection.manifest().document_count,
5867            "generation": projection.manifest().identity.generation,
5868            "source_epoch": projection.manifest().identity.source_epoch,
5869            "embedding_model": projection.manifest().identity.embedding_model,
5870            "embedding_version": projection.manifest().identity.embedding_version,
5871            "transform": projection.manifest().transform,
5872            "quantizer": projection.manifest().quantizer,
5873            "calibration": projection.manifest().calibration,
5874            "segment_count": projection.manifest().segments.len(),
5875            "payload_bytes": projection.manifest().payload_bytes,
5876            "peak_build_working_bytes": projection.build_report().peak_working_bytes,
5877            "supports_allowlist": true,
5878            "supports_filter_bitmap": true,
5879            "supports_scalar_reference": true,
5880            "supports_runtime_simd_dispatch": supports_runtime_simd_dispatch,
5881            "supports_governed_parallelism": true,
5882            "raw_rerank_required": true,
5883            "persisted_artifact_used": projection.is_file_backed(),
5884            "artifact_rebuilt_from_snapshot": !projection.is_file_backed(),
5885            "blocker_codes": [],
5886        }),
5887        None => serde_json::json!({
5888            "engine": "hawdb_rabitq_scan",
5889            "compiled": true,
5890            "ready": false,
5891            "algorithm": hawdb_vector_projection::PROJECTION_ALGORITHM,
5892            "bit_width": hawdb_vector_projection::PROJECTION_BIT_WIDTH,
5893            "dimension": serde_json::Value::Null,
5894            "document_count": 0,
5895            "quantizer": hawdb_vector_projection::PROJECTION_QUANTIZER,
5896            "calibration": hawdb_vector_projection::PROJECTION_CALIBRATION,
5897            "supports_allowlist": true,
5898            "supports_filter_bitmap": true,
5899            "supports_scalar_reference": true,
5900            "supports_runtime_simd_dispatch": supports_runtime_simd_dispatch,
5901            "supports_governed_parallelism": true,
5902            "raw_rerank_required": true,
5903            "persisted_artifact_used": false,
5904            "artifact_rebuilt_from_snapshot": false,
5905            "blocker_codes": ["rabitq_projection_unavailable"],
5906        }),
5907    }
5908}
5909
5910#[cfg(not(feature = "vector-search"))]
5911fn search_projection_probe_compressed_vector_projection_report(
5912    _index: &SearchIndex,
5913) -> serde_json::Value {
5914    serde_json::json!({
5915        "engine": "hawdb_rabitq_scan",
5916        "compiled": false,
5917        "ready": false,
5918        "algorithm": "rabitq",
5919        "bit_width": serde_json::Value::Null,
5920        "dimension": serde_json::Value::Null,
5921        "document_count": 0,
5922        "supports_allowlist": false,
5923        "supports_filter_bitmap": false,
5924        "supports_scalar_reference": false,
5925        "supports_runtime_simd_dispatch": false,
5926        "supports_governed_parallelism": false,
5927        "raw_rerank_required": true,
5928        "persisted_artifact_used": false,
5929        "artifact_rebuilt_from_snapshot": false,
5930        "blocker_codes": ["vector_search_feature_disabled"],
5931    })
5932}
5933
5934fn search_projection_probe_blocker_codes(
5935    has_documents: bool,
5936    has_text: bool,
5937    has_vector: bool,
5938    has_manifest: bool,
5939    model_matches: bool,
5940    dimension_matches: bool,
5941    freshness: &SearchProjectionFreshness,
5942) -> Vec<String> {
5943    let mut blockers = BTreeSet::new();
5944    if !has_documents {
5945        blockers.insert("empty_search_projection".to_string());
5946    }
5947    if !has_text {
5948        blockers.insert("missing_text_leg".to_string());
5949    }
5950    if !has_vector {
5951        blockers.insert("missing_vector_leg".to_string());
5952    }
5953    if !has_manifest {
5954        blockers.insert("missing_embedding_manifest".to_string());
5955    }
5956    if !model_matches {
5957        blockers.insert("embedding_model_mismatch".to_string());
5958    }
5959    if !dimension_matches {
5960        blockers.insert("embedding_dimension_mismatch".to_string());
5961    }
5962    if freshness.full_reindex_needed {
5963        blockers.insert("full_reindex_needed".to_string());
5964    }
5965    if freshness.metadata_repair_needed {
5966        blockers.insert("metadata_repair_needed".to_string());
5967    }
5968    blockers.into_iter().collect()
5969}
5970
5971pub(crate) fn projection_row_from_node(
5972    catalog: &Catalog,
5973    node: &NodeRecord,
5974) -> Option<SearchProjectionRow> {
5975    let kind = node.labels.iter().find_map(|label_id| {
5976        catalog
5977            .label_name(*label_id)
5978            .and_then(search_projection_kind_from_label)
5979    })?;
5980    let external_id = string_property(node, "id")
5981        .filter(|id| !id.is_empty())
5982        .unwrap_or_else(|| node.id.0.to_string());
5983    let title = first_string_property(node, &["title", "name", "summary", "id"])
5984        .unwrap_or_else(|| external_id.clone());
5985    let body = first_string_property(
5986        node,
5987        &["content", "body", "text", "summary", "title", "name"],
5988    )
5989    .unwrap_or_else(|| title.clone());
5990    let source_id = first_non_empty_string_property(node, &["source_id", "thread_id", "source"]);
5991    let mut metadata = BTreeMap::new();
5992    for (key, value) in &node.properties {
5993        if matches!(key.as_str(), "kind" | "external_id" | "source_id") {
5994            continue;
5995        }
5996        metadata.insert(key.clone(), projection_metadata_value(key, value));
5997    }
5998    metadata
5999        .entry("space_id".to_string())
6000        .or_insert_with(|| DEFAULT_SPACE_ID.to_string());
6001    if metadata
6002        .get("space_id")
6003        .is_some_and(|space_id| space_id.is_empty())
6004    {
6005        metadata.insert("space_id".to_string(), DEFAULT_SPACE_ID.to_string());
6006    }
6007    if kind == SearchProjectionKind::Memory {
6008        materialize_memory_metadata_paths(node, &mut metadata);
6009    }
6010    Some(SearchProjectionRow {
6011        kind,
6012        external_id,
6013        title,
6014        body,
6015        embedding: None,
6016        source_id,
6017        metadata,
6018    })
6019}
6020
6021pub fn projection_row_from_node_with_graph_metadata<S: SearchProjectionSource + ?Sized>(
6022    catalog: &Catalog,
6023    store: &S,
6024    node: &NodeRecord,
6025) -> Result<Option<SearchProjectionRow>> {
6026    let Some(mut row) = projection_row_from_node(catalog, node) else {
6027        return Ok(None);
6028    };
6029    let labels = projection_business_labels_for_node(catalog, store, node)?;
6030    apply_projection_business_labels(&mut row, &labels);
6031    Ok(Some(row))
6032}
6033
6034/// Shapes one canonical node with already collected business-label values.
6035/// The caller must establish label completeness and source validity separately.
6036#[doc(hidden)]
6037pub fn projection_row_from_node_with_business_labels(
6038    catalog: &Catalog,
6039    node: &NodeRecord,
6040    labels: &[String],
6041) -> Option<SearchProjectionRow> {
6042    let mut row = projection_row_from_node(catalog, node)?;
6043    apply_projection_business_labels(&mut row, labels);
6044    Some(row)
6045}
6046
6047fn apply_projection_business_labels(row: &mut SearchProjectionRow, labels: &[String]) {
6048    if !labels.is_empty() {
6049        row.metadata.insert(
6050            "labels".to_string(),
6051            serde_json::to_string(labels).expect("label metadata serializes as a string array"),
6052        );
6053    }
6054}
6055
6056fn projection_business_labels_for_node<S: SearchProjectionSource + ?Sized>(
6057    catalog: &Catalog,
6058    store: &S,
6059    node: &NodeRecord,
6060) -> Result<Vec<String>> {
6061    store.projection_business_labels(catalog, node)
6062}
6063
6064#[doc(hidden)]
6065pub fn projection_business_label_value(label: &NodeRecord) -> Option<String> {
6066    projection_business_label_value_from_properties(&label.properties)
6067}
6068
6069/// Applies the canonical business-label precedence to a decoded query node.
6070#[doc(hidden)]
6071pub fn projection_business_label_value_from_properties(
6072    properties: &BTreeMap<String, Value>,
6073) -> Option<String> {
6074    ["canonical_name", "name", "id"]
6075        .into_iter()
6076        .filter_map(|key| properties.get(key).map(value_to_projection_string))
6077        .find(|value| !value.is_empty())
6078}
6079
6080fn search_projection_kind_from_label(label: &str) -> Option<SearchProjectionKind> {
6081    match label {
6082        "Memory" | "memory" => Some(SearchProjectionKind::Memory),
6083        "Message" | "message" => Some(SearchProjectionKind::Message),
6084        "Entity" | "entity" => Some(SearchProjectionKind::Entity),
6085        "Source" | "source" => Some(SearchProjectionKind::Source),
6086        "SourceChunk" | "source_chunk" | "chunk" => Some(SearchProjectionKind::SourceChunk),
6087        "Community" | "community" => Some(SearchProjectionKind::Community),
6088        _ => None,
6089    }
6090}
6091
6092fn first_string_property(node: &NodeRecord, keys: &[&str]) -> Option<String> {
6093    keys.iter().find_map(|key| string_property(node, key))
6094}
6095
6096fn first_non_empty_string_property(node: &NodeRecord, keys: &[&str]) -> Option<String> {
6097    keys.iter()
6098        .filter_map(|key| string_property(node, key))
6099        .find(|value| !value.is_empty())
6100}
6101
6102fn string_property(node: &NodeRecord, key: &str) -> Option<String> {
6103    node.properties.get(key).map(value_to_projection_string)
6104}
6105
6106const DEFAULT_SPACE_ID: &str = "default";
6107
6108fn projection_metadata_value(key: &str, value: &Value) -> String {
6109    let text = value_to_projection_string(value);
6110    if key == "space_id" && text.is_empty() {
6111        DEFAULT_SPACE_ID.to_string()
6112    } else {
6113        text
6114    }
6115}
6116
6117fn materialize_memory_metadata_paths(node: &NodeRecord, metadata: &mut BTreeMap<String, String>) {
6118    let Some(raw) = node
6119        .properties
6120        .get("metadata")
6121        .and_then(|value| match value {
6122            Value::String(raw) => Some(raw),
6123            _ => None,
6124        })
6125    else {
6126        return;
6127    };
6128    let Ok(value) = serde_json::from_str::<serde_json::Value>(raw) else {
6129        return;
6130    };
6131    for path in NOWLEDGE_MEMORY_MATERIALIZED_METADATA_PATHS {
6132        let values = metadata_json_values_at_path(&value, path);
6133        if values.is_empty() {
6134            continue;
6135        }
6136        let key = format!("metadata.{path}");
6137        let value = if values.len() == 1 {
6138            values.into_iter().next().unwrap_or_default()
6139        } else {
6140            serde_json::to_string(&values).unwrap_or_default()
6141        };
6142        metadata.insert(key, value);
6143    }
6144}
6145
6146fn metadata_json_values_at_path(value: &serde_json::Value, path: &str) -> Vec<String> {
6147    let mut values = vec![value];
6148    for segment in path.split('.') {
6149        values = values
6150            .into_iter()
6151            .filter_map(|value| value.as_object()?.get(segment))
6152            .collect();
6153        if values.is_empty() {
6154            return Vec::new();
6155        }
6156    }
6157    values
6158        .into_iter()
6159        .flat_map(|value| match value {
6160            serde_json::Value::Array(values) => values.iter().collect::<Vec<_>>(),
6161            value => vec![value],
6162        })
6163        .filter_map(metadata_json_scalar)
6164        .collect()
6165}
6166
6167fn metadata_json_scalar(value: &serde_json::Value) -> Option<String> {
6168    match value {
6169        serde_json::Value::Null => Some("null".to_string()),
6170        serde_json::Value::Bool(value) => Some(value.to_string()),
6171        serde_json::Value::Number(value) => Some(value.to_string()),
6172        serde_json::Value::String(value) => Some(value.clone()),
6173        serde_json::Value::Array(_) | serde_json::Value::Object(_) => None,
6174    }
6175}
6176
6177fn value_to_projection_string(value: &Value) -> String {
6178    match value {
6179        Value::Null => String::new(),
6180        Value::Bool(value) => value.to_string(),
6181        Value::Int(value) => value.to_string(),
6182        Value::Float(value) => value.to_string(),
6183        Value::Decimal(value) => value.to_string(),
6184        Value::String(value) => value.clone(),
6185        Value::Binary(value) => format!(
6186            "\\x{}",
6187            value
6188                .iter()
6189                .map(|byte| format!("{byte:02x}"))
6190                .collect::<String>()
6191        ),
6192        Value::Uuid(value) => value.to_string(),
6193        Value::Vector(_)
6194        | Value::Date(_)
6195        | Value::LocalTime(_)
6196        | Value::LocalDateTime(_)
6197        | Value::DateTime(_)
6198        | Value::Duration(_) => value.to_string(),
6199        Value::List(values) => values
6200            .iter()
6201            .map(value_to_projection_string)
6202            .collect::<Vec<_>>()
6203            .join(","),
6204        Value::Map(values) => values
6205            .iter()
6206            .map(|(key, value)| format!("{key}:{}", value_to_projection_string(value)))
6207            .collect::<Vec<_>>()
6208            .join(","),
6209    }
6210}
6211
6212fn ranked_scores(scores: &BTreeMap<String, f64>) -> BTreeMap<String, usize> {
6213    let mut ranked = scores
6214        .iter()
6215        .map(|(id, score)| (id.clone(), *score))
6216        .collect::<Vec<_>>();
6217    ranked.sort_by(|(left_id, left_score), (right_id, right_score)| {
6218        right_score
6219            .partial_cmp(left_score)
6220            .unwrap_or(Ordering::Equal)
6221            .then_with(|| left_id.cmp(right_id))
6222    });
6223    ranked
6224        .into_iter()
6225        .enumerate()
6226        .map(|(index, (id, _score))| (id, index + 1))
6227        .collect()
6228}
6229
6230fn search_empty_reason_codes(
6231    returned_empty: bool,
6232    document_count: usize,
6233    filtered_document_count: usize,
6234    total_hits: usize,
6235) -> Vec<SearchEmptyReasonCode> {
6236    if !returned_empty {
6237        return Vec::new();
6238    }
6239    if document_count == 0 {
6240        return vec![SearchEmptyReasonCode::ProjectionEmpty];
6241    }
6242    if filtered_document_count == 0 {
6243        return vec![SearchEmptyReasonCode::MetadataFilterEmpty];
6244    }
6245    if total_hits == 0 {
6246        return vec![SearchEmptyReasonCode::RetrieverNoHits];
6247    }
6248    vec![SearchEmptyReasonCode::LimitExcludedAllHits]
6249}
6250
6251#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6252struct SearchPageWindow {
6253    offset: usize,
6254    limit: usize,
6255}
6256
6257fn search_empty_reasons(
6258    returned_empty: bool,
6259    document_count: usize,
6260    filtered_document_count: usize,
6261    total_hits: usize,
6262    page_window: SearchPageWindow,
6263    truncation_reasons: &[String],
6264    fallback_reasons: &[String],
6265) -> Vec<String> {
6266    if !returned_empty {
6267        return Vec::new();
6268    }
6269    if document_count == 0 {
6270        return vec!["search projection has no documents".to_string()];
6271    }
6272    if filtered_document_count == 0 {
6273        return vec!["metadata filters matched no search documents".to_string()];
6274    }
6275    if total_hits == 0 {
6276        let mut reasons =
6277            vec!["search retrievers returned no hits inside filtered scope".to_string()];
6278        reasons.extend(fallback_reasons.iter().cloned());
6279        return reasons;
6280    }
6281    if page_window.offset > 0 {
6282        return vec![format!(
6283            "offset {} limit {} returned no hits from {total_hits} matching hits",
6284            page_window.offset, page_window.limit
6285        )];
6286    }
6287    truncation_reasons.to_vec()
6288}
6289
6290fn window_ranks(
6291    ranks: &BTreeMap<String, usize>,
6292    rank_window: Option<usize>,
6293) -> BTreeMap<String, usize> {
6294    let Some(rank_window) = rank_window else {
6295        return ranks.clone();
6296    };
6297    ranks
6298        .iter()
6299        .filter_map(|(id, rank)| (*rank <= rank_window).then_some((id.clone(), *rank)))
6300        .collect()
6301}
6302
6303fn top_ranked_ids<K: AsRef<str> + Ord>(ranks: &BTreeMap<K, usize>, limit: usize) -> Vec<String> {
6304    let mut ranked = ranks
6305        .iter()
6306        .map(|(id, rank)| (id.as_ref().to_owned(), *rank))
6307        .collect::<Vec<_>>();
6308    ranked.sort_by(|(left_id, left_rank), (right_id, right_rank)| {
6309        left_rank
6310            .cmp(right_rank)
6311            .then_with(|| left_id.cmp(right_id))
6312    });
6313    ranked
6314        .into_iter()
6315        .take(limit)
6316        .map(|(id, _rank)| id)
6317        .collect()
6318}
6319
6320fn top_ranked_candidates<K: AsRef<str> + Ord>(
6321    ranks: &BTreeMap<K, usize>,
6322    scores: &BTreeMap<String, f64>,
6323    limit: usize,
6324) -> Vec<SearchRetrieverCandidate> {
6325    let mut ranked = ranks
6326        .iter()
6327        .filter_map(|(id, rank)| {
6328            scores
6329                .get(id.as_ref())
6330                .map(|score| SearchRetrieverCandidate {
6331                    id: id.as_ref().to_owned(),
6332                    rank: *rank,
6333                    score: *score,
6334                })
6335        })
6336        .collect::<Vec<_>>();
6337    ranked.sort_by(|left, right| {
6338        left.rank
6339            .cmp(&right.rank)
6340            .then_with(|| left.id.cmp(&right.id))
6341    });
6342    ranked.truncate(limit);
6343    ranked
6344}
6345
6346fn retriever_candidate_set_report(
6347    cardinality: usize,
6348    snapshot_source_graph_commit_epoch: Option<u64>,
6349    policy_epoch: Option<u64>,
6350    exact: bool,
6351) -> SearchRetrieverCandidateSetReport {
6352    SearchRetrieverCandidateSetReport {
6353        id_space: "search_projection_document_id".to_string(),
6354        representation: "ranked_document_ids".to_string(),
6355        cardinality,
6356        exact,
6357        snapshot_source_graph_commit_epoch,
6358        policy_epoch,
6359    }
6360}
6361
6362fn rrf_child_score(rank: Option<usize>) -> f64 {
6363    rank.map(|rank| 1.0 / (RRF_K + rank as f64)).unwrap_or(0.0)
6364}
6365
6366fn weighted_rrf_score(
6367    vector_rrf_score: f64,
6368    text_rrf_score: f64,
6369    weights: SearchFusionWeights,
6370) -> f64 {
6371    vector_rrf_score * weights.vector_weight + text_rrf_score * weights.text_weight
6372}
6373
6374fn format_embedding_manifest(manifest: &SearchEmbeddingManifest) -> String {
6375    match &manifest.version {
6376        Some(version) => format!("{}@{}:{}", manifest.model, version, manifest.dimension),
6377        None => format!("{}:{}", manifest.model, manifest.dimension),
6378    }
6379}
6380
6381#[doc(hidden)]
6382pub struct SearchMetadataPredicatePushdown {
6383    pub predicates: SearchPredicateSet,
6384    pub report: SearchPredicatePushdownReport,
6385}
6386
6387#[doc(hidden)]
6388pub fn search_metadata_predicate_pushdown(
6389    filters: &BTreeMap<String, String>,
6390) -> SearchMetadataPredicatePushdown {
6391    let (predicates, parse_error) = match SearchPredicateSet::from_metadata_filters(filters) {
6392        Ok(predicates) => (predicates, None),
6393        Err(error) => (SearchPredicateSet::unsatisfiable(), Some(error.to_string())),
6394    };
6395    metadata_predicate_pushdown(filters.len(), predicates, parse_error)
6396}
6397
6398fn metadata_predicate_pushdown(
6399    input_predicate_count: usize,
6400    predicates: SearchPredicateSet,
6401    parse_error: Option<String>,
6402) -> SearchMetadataPredicatePushdown {
6403    // The metadata scan implements every SearchPredicateOp. Move its complete
6404    // set rather than cloning it twice through an all-supported optimizer
6405    // partition whose RuleEvents are immediately discarded.
6406    let report = SearchPredicatePushdownReport {
6407        input_predicate_count,
6408        pushed_predicate_count: predicates.predicates().len(),
6409        residual_predicate_count: 0,
6410        unsatisfiable: predicates.is_unsatisfiable(),
6411        parse_error,
6412        segment_count: 0,
6413        pruned_segment_count: 0,
6414        scanned_segment_count: 0,
6415        segment_pruning_candidate_document_count: 0,
6416        segment_pruned_document_count: 0,
6417        segment_scanned_document_count: 0,
6418        persisted_segment_descriptor_used: false,
6419        physical_range_read_count: 0,
6420        physical_bytes_read: 0,
6421        postings_segment_count: 0,
6422        postings_predicate_count: 0,
6423        postings_residual_predicate_count: 0,
6424        postings_prefiltered_segment_count: 0,
6425        field_summaries: Vec::new(),
6426    };
6427    SearchMetadataPredicatePushdown { predicates, report }
6428}
6429
6430fn search_document_matches_predicates(
6431    document: &SearchDocument,
6432    predicates: &SearchPredicateSet,
6433) -> bool {
6434    search_metadata_matches_predicates(&document.id, &document.metadata, predicates)
6435}
6436
6437fn search_metadata_matches_predicate(
6438    id: &str,
6439    metadata: &BTreeMap<String, String>,
6440    predicate: &SearchPredicate,
6441) -> bool {
6442    let header = crate::document_encoding::Header {
6443        id,
6444        title: "",
6445        embedding: None,
6446        metadata,
6447    };
6448    search_header_matches_predicate(header, predicate)
6449}
6450
6451fn search_metadata_matches_predicates(
6452    id: &str,
6453    metadata: &BTreeMap<String, String>,
6454    predicates: &SearchPredicateSet,
6455) -> bool {
6456    if predicates.is_unsatisfiable() {
6457        return false;
6458    }
6459    predicates
6460        .predicates()
6461        .iter()
6462        .all(|predicate| search_metadata_matches_predicate(id, metadata, predicate))
6463}
6464
6465struct FilteredSearchDocuments<'a> {
6466    documents: Vec<&'a SearchDocument>,
6467    segment_count: usize,
6468    pruned_segment_count: usize,
6469    scanned_segment_count: usize,
6470    segment_pruning_candidate_document_count: usize,
6471    segment_pruned_document_count: usize,
6472    segment_scanned_document_count: usize,
6473    persisted_segment_descriptor_used: bool,
6474    field_summaries: Vec<SearchPredicateFieldPruningReport>,
6475}
6476
6477#[derive(Debug, Clone, Copy, PartialEq)]
6478struct SearchNumericRange {
6479    min: f64,
6480    max: f64,
6481}
6482
6483#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6484struct SearchTimestampRange {
6485    min_epoch_millis: i64,
6486    max_epoch_millis: i64,
6487}
6488
6489#[derive(Debug, Clone, PartialEq)]
6490struct SearchFilterSegmentSummary {
6491    document_count: usize,
6492    present_counts: BTreeMap<String, usize>,
6493    values: BTreeMap<String, BTreeSet<String>>,
6494    numeric_ranges: BTreeMap<String, SearchNumericRange>,
6495    timestamp_ranges: BTreeMap<String, SearchTimestampRange>,
6496}
6497
6498#[derive(Debug, Clone, PartialEq)]
6499struct SearchSegmentDescriptor {
6500    target_documents: usize,
6501    document_count: usize,
6502    segments: Vec<SearchSegmentDescriptorEntry>,
6503}
6504
6505#[derive(Debug, Clone, PartialEq)]
6506struct SearchSegmentDescriptorEntry {
6507    segment_id: u64,
6508    first_document_id: String,
6509    last_document_id: String,
6510    document_count: usize,
6511    payload_range: Option<SearchSegmentPayloadRange>,
6512    metadata: BTreeMap<String, SearchSegmentFieldSummary>,
6513}
6514
6515#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6516struct SearchSegmentPayloadRange {
6517    artifact_id: u64,
6518    offset: u64,
6519    length: u64,
6520    checksum: u64,
6521}
6522
6523#[derive(Debug, Default)]
6524struct SearchPhysicalRangeRead {
6525    documents: BTreeMap<String, SearchDocument>,
6526    range_count: usize,
6527    bytes_read: u64,
6528}
6529
6530#[derive(Debug, Clone, Default, PartialEq)]
6531struct SearchSegmentFieldSummary {
6532    present_count: usize,
6533    /// The complete set of distinct normalized values, used to skip a segment
6534    /// for `Eq`, `In` and `NotIn`. Empty when `values_omitted` is set.
6535    values: BTreeSet<String>,
6536    /// The value set exceeded the segment value-summary bounds, so it is not
6537    /// kept and value predicates on this field cannot skip the segment (#1746).
6538    values_omitted: bool,
6539    numeric_range: Option<SearchNumericRange>,
6540    timestamp_range: Option<SearchTimestampRange>,
6541}
6542
6543/// Largest normalized value an out-of-core segment value summary keeps (#1746).
6544/// Longer values, such as document bodies copied into metadata, omit the
6545/// field's value summary for the segment.
6546const SEARCH_SEGMENT_VALUE_SUMMARY_MAX_VALUE_BYTES: usize = 256;
6547
6548/// Largest sum of distinct normalized value bytes one out-of-core segment
6549/// keeps per field (#1746). With 128-document segments this is at most 64
6550/// bytes per document per field, independent of document size.
6551const SEARCH_SEGMENT_VALUE_SUMMARY_MAX_FIELD_BYTES: usize = 8 * 1024;
6552
6553fn filter_search_documents_with_segment_pruning<'a>(
6554    documents: &'a impl DocumentView,
6555    predicates: &SearchPredicateSet,
6556    descriptor: Option<&'a SearchSegmentDescriptor>,
6557) -> FilteredSearchDocuments<'a> {
6558    if predicates.is_empty() {
6559        return FilteredSearchDocuments {
6560            documents: documents.values().collect(),
6561            segment_count: 0,
6562            pruned_segment_count: 0,
6563            scanned_segment_count: 0,
6564            segment_pruning_candidate_document_count: 0,
6565            segment_pruned_document_count: 0,
6566            segment_scanned_document_count: 0,
6567            persisted_segment_descriptor_used: false,
6568            field_summaries: Vec::new(),
6569        };
6570    }
6571
6572    if let Some(descriptor) =
6573        descriptor.filter(|descriptor| descriptor.matches_documents(documents))
6574    {
6575        return filter_search_documents_with_persisted_segments(documents, predicates, descriptor);
6576    }
6577
6578    let predicate_fields = search_predicate_fields(predicates);
6579    let mut filtered_documents = Vec::new();
6580    let mut segment_documents = Vec::with_capacity(SEARCH_FILTER_SEGMENT_TARGET_DOCUMENTS);
6581    let mut pruning = SearchSegmentPruningState::new(predicates);
6582
6583    for document in documents.values() {
6584        segment_documents.push(document);
6585        if segment_documents.len() == SEARCH_FILTER_SEGMENT_TARGET_DOCUMENTS {
6586            filter_search_document_segment(
6587                &mut filtered_documents,
6588                &mut pruning,
6589                &segment_documents,
6590                &predicate_fields,
6591                predicates,
6592            );
6593            segment_documents.clear();
6594        }
6595    }
6596
6597    if !segment_documents.is_empty() {
6598        filter_search_document_segment(
6599            &mut filtered_documents,
6600            &mut pruning,
6601            &segment_documents,
6602            &predicate_fields,
6603            predicates,
6604        );
6605    }
6606
6607    FilteredSearchDocuments {
6608        documents: filtered_documents,
6609        segment_count: pruning.segment_count,
6610        pruned_segment_count: pruning.pruned_segment_count,
6611        scanned_segment_count: pruning.scanned_segment_count,
6612        segment_pruning_candidate_document_count: pruning.segment_pruning_candidate_document_count,
6613        segment_pruned_document_count: pruning.segment_pruned_document_count,
6614        segment_scanned_document_count: pruning.segment_scanned_document_count,
6615        persisted_segment_descriptor_used: false,
6616        field_summaries: pruning.field_pruning.into_reports(),
6617    }
6618}
6619
6620fn filter_search_documents_with_persisted_segments<'a>(
6621    documents: &'a impl DocumentView,
6622    predicates: &SearchPredicateSet,
6623    descriptor: &'a SearchSegmentDescriptor,
6624) -> FilteredSearchDocuments<'a> {
6625    let mut filtered_documents = Vec::new();
6626    let mut pruned_segment_count = 0;
6627    let mut scanned_segment_count = 0;
6628    let mut pruned_document_count = 0;
6629    let mut scanned_document_count = 0;
6630    let mut field_pruning = SearchFieldPruningAccumulator::new(predicates);
6631
6632    for segment in &descriptor.segments {
6633        field_pruning.observe_persisted_segment(segment, predicates);
6634        if !segment.may_match_predicates(predicates) {
6635            pruned_segment_count += 1;
6636            pruned_document_count += segment.document_count;
6637            continue;
6638        }
6639        scanned_segment_count += 1;
6640        scanned_document_count += segment.document_count;
6641        filtered_documents.extend(
6642            documents
6643                .range_documents(&segment.first_document_id, &segment.last_document_id)
6644                .map(|(_, document)| document)
6645                .filter(|document| search_document_matches_predicates(document, predicates)),
6646        );
6647    }
6648
6649    FilteredSearchDocuments {
6650        documents: filtered_documents,
6651        segment_count: descriptor.segments.len(),
6652        pruned_segment_count,
6653        scanned_segment_count,
6654        segment_pruning_candidate_document_count: descriptor.document_count,
6655        segment_pruned_document_count: pruned_document_count,
6656        segment_scanned_document_count: scanned_document_count,
6657        persisted_segment_descriptor_used: true,
6658        field_summaries: field_pruning.into_reports(),
6659    }
6660}
6661
6662fn filter_search_document_segment<'a>(
6663    output: &mut Vec<&'a SearchDocument>,
6664    pruning: &mut SearchSegmentPruningState,
6665    segment_documents: &[&'a SearchDocument],
6666    predicate_fields: &BTreeSet<String>,
6667    predicates: &SearchPredicateSet,
6668) {
6669    pruning.segment_count += 1;
6670    let summary = SearchFilterSegmentSummary::from_documents(segment_documents, predicate_fields);
6671    pruning.segment_pruning_candidate_document_count += summary.document_count;
6672    pruning
6673        .field_pruning
6674        .observe_in_memory_segment(&summary, predicates);
6675    if !summary.may_match_predicates(predicates) {
6676        pruning.pruned_segment_count += 1;
6677        pruning.segment_pruned_document_count += summary.document_count;
6678        return;
6679    }
6680    pruning.scanned_segment_count += 1;
6681    pruning.segment_scanned_document_count += summary.document_count;
6682    output.extend(
6683        segment_documents
6684            .iter()
6685            .copied()
6686            .filter(|document| search_document_matches_predicates(document, predicates)),
6687    );
6688}
6689
6690fn search_predicate_fields(predicates: &SearchPredicateSet) -> BTreeSet<String> {
6691    predicates
6692        .predicates()
6693        .iter()
6694        .map(|predicate| predicate.field().name().to_string())
6695        .collect()
6696}
6697
6698#[derive(Debug, Clone)]
6699struct SearchSegmentPruningState {
6700    segment_count: usize,
6701    pruned_segment_count: usize,
6702    scanned_segment_count: usize,
6703    segment_pruning_candidate_document_count: usize,
6704    segment_pruned_document_count: usize,
6705    segment_scanned_document_count: usize,
6706    field_pruning: SearchFieldPruningAccumulator,
6707}
6708
6709impl SearchSegmentPruningState {
6710    fn new(predicates: &SearchPredicateSet) -> Self {
6711        Self {
6712            segment_count: 0,
6713            pruned_segment_count: 0,
6714            scanned_segment_count: 0,
6715            segment_pruning_candidate_document_count: 0,
6716            segment_pruned_document_count: 0,
6717            segment_scanned_document_count: 0,
6718            field_pruning: SearchFieldPruningAccumulator::new(predicates),
6719        }
6720    }
6721}
6722
6723#[derive(Debug, Clone, Default)]
6724struct SearchFieldPruningAccumulator {
6725    fields: BTreeMap<String, SearchFieldPruningStats>,
6726}
6727
6728#[derive(Debug, Clone, Default)]
6729struct SearchFieldPruningStats {
6730    value_kinds: BTreeSet<String>,
6731    operation_kinds: BTreeSet<String>,
6732    segment_count: usize,
6733    pruned_segment_count: usize,
6734    scanned_segment_count: usize,
6735    numeric_range_summary_used: bool,
6736    timestamp_range_summary_used: bool,
6737    value_summary_used: bool,
6738}
6739
6740impl SearchFieldPruningAccumulator {
6741    fn new(predicates: &SearchPredicateSet) -> Self {
6742        let mut fields = BTreeMap::<String, SearchFieldPruningStats>::new();
6743        for predicate in predicates.predicates() {
6744            let stats = fields
6745                .entry(predicate.field().name().to_string())
6746                .or_default();
6747            stats
6748                .operation_kinds
6749                .insert(search_predicate_op_kind(predicate.op()).to_string());
6750            stats
6751                .value_kinds
6752                .insert(search_predicate_value_kind(predicate).to_string());
6753            match predicate.op() {
6754                SearchPredicateOp::Eq(_)
6755                | SearchPredicateOp::In(_)
6756                | SearchPredicateOp::NotIn(_) => stats.value_summary_used = true,
6757                SearchPredicateOp::Gt(_)
6758                | SearchPredicateOp::Gte(_)
6759                | SearchPredicateOp::Lt(_)
6760                | SearchPredicateOp::Lte(_) => {
6761                    stats.numeric_range_summary_used = true;
6762                    if range_predicate_expects_timestamp(predicate) {
6763                        stats.timestamp_range_summary_used = true;
6764                    }
6765                }
6766                SearchPredicateOp::Exists | SearchPredicateOp::IsMissing => {
6767                    stats.value_summary_used = true;
6768                }
6769            }
6770        }
6771        Self { fields }
6772    }
6773
6774    fn observe_in_memory_segment(
6775        &mut self,
6776        summary: &SearchFilterSegmentSummary,
6777        predicates: &SearchPredicateSet,
6778    ) {
6779        self.observe_segment(predicates, |field_predicates| {
6780            field_predicates
6781                .iter()
6782                .all(|predicate| summary.may_match_predicate(predicate))
6783        });
6784    }
6785
6786    fn observe_persisted_segment(
6787        &mut self,
6788        segment: &SearchSegmentDescriptorEntry,
6789        predicates: &SearchPredicateSet,
6790    ) {
6791        self.observe_segment(predicates, |field_predicates| {
6792            field_predicates
6793                .iter()
6794                .all(|predicate| segment.may_match_predicate(predicate))
6795        });
6796    }
6797
6798    fn observe_segment(
6799        &mut self,
6800        predicates: &SearchPredicateSet,
6801        mut may_match: impl FnMut(&[&SearchPredicate]) -> bool,
6802    ) {
6803        let mut predicates_by_field = BTreeMap::<String, Vec<&SearchPredicate>>::new();
6804        for predicate in predicates.predicates() {
6805            predicates_by_field
6806                .entry(predicate.field().name().to_string())
6807                .or_default()
6808                .push(predicate);
6809        }
6810        for (field, field_predicates) in predicates_by_field {
6811            let stats = self.fields.entry(field).or_default();
6812            stats.segment_count += 1;
6813            if may_match(&field_predicates) {
6814                stats.scanned_segment_count += 1;
6815            } else {
6816                stats.pruned_segment_count += 1;
6817            }
6818        }
6819    }
6820
6821    fn into_reports(self) -> Vec<SearchPredicateFieldPruningReport> {
6822        self.fields
6823            .into_iter()
6824            .map(|(field, stats)| SearchPredicateFieldPruningReport {
6825                field,
6826                value_kind: search_pruning_value_kind(&stats.value_kinds),
6827                operation_kinds: stats.operation_kinds.into_iter().collect(),
6828                segment_count: stats.segment_count,
6829                pruned_segment_count: stats.pruned_segment_count,
6830                scanned_segment_count: stats.scanned_segment_count,
6831                numeric_range_summary_used: stats.numeric_range_summary_used,
6832                timestamp_range_summary_used: stats.timestamp_range_summary_used,
6833                value_summary_used: stats.value_summary_used,
6834            })
6835            .collect()
6836    }
6837}
6838
6839fn search_pruning_value_kind(value_kinds: &BTreeSet<String>) -> String {
6840    match value_kinds.len() {
6841        0 => "unknown".to_string(),
6842        1 => value_kinds
6843            .first()
6844            .cloned()
6845            .unwrap_or_else(|| "unknown".to_string()),
6846        _ => "mixed".to_string(),
6847    }
6848}
6849
6850fn search_predicate_value_kind(predicate: &SearchPredicate) -> &'static str {
6851    match predicate.op() {
6852        SearchPredicateOp::Eq(value)
6853        | SearchPredicateOp::Gt(value)
6854        | SearchPredicateOp::Gte(value)
6855        | SearchPredicateOp::Lt(value)
6856        | SearchPredicateOp::Lte(value) => search_scalar_report_kind(value),
6857        SearchPredicateOp::In(values) | SearchPredicateOp::NotIn(values) => values
6858            .iter()
6859            .next()
6860            .map(search_scalar_report_kind)
6861            .unwrap_or("unknown"),
6862        SearchPredicateOp::Exists | SearchPredicateOp::IsMissing => "presence",
6863    }
6864}
6865
6866fn search_scalar_report_kind(value: &SearchScalarValue) -> &'static str {
6867    match value {
6868        SearchScalarValue::Enum(_) => "enum",
6869        SearchScalarValue::String(_) => "numeric_or_string",
6870    }
6871}
6872
6873fn search_predicate_op_kind(op: &SearchPredicateOp) -> &'static str {
6874    match op {
6875        SearchPredicateOp::Eq(_) => "eq",
6876        SearchPredicateOp::In(_) => "in",
6877        SearchPredicateOp::NotIn(_) => "not_in",
6878        SearchPredicateOp::Gt(_) => "gt",
6879        SearchPredicateOp::Gte(_) => "gte",
6880        SearchPredicateOp::Lt(_) => "lt",
6881        SearchPredicateOp::Lte(_) => "lte",
6882        SearchPredicateOp::Exists => "exists",
6883        SearchPredicateOp::IsMissing => "missing",
6884    }
6885}
6886
6887fn range_predicate_expects_timestamp(predicate: &SearchPredicate) -> bool {
6888    match predicate.op() {
6889        SearchPredicateOp::Gt(value)
6890        | SearchPredicateOp::Gte(value)
6891        | SearchPredicateOp::Lt(value)
6892        | SearchPredicateOp::Lte(value) => metadata_timestamp_value(value.as_str()).is_some(),
6893        _ => false,
6894    }
6895}
6896
6897impl SearchFilterSegmentSummary {
6898    fn from_documents(documents: &[&SearchDocument], fields: &BTreeSet<String>) -> Self {
6899        let mut present_counts = BTreeMap::new();
6900        let mut values = BTreeMap::<String, BTreeSet<String>>::new();
6901        let mut numeric_ranges = BTreeMap::<String, SearchNumericRange>::new();
6902        let mut timestamp_ranges = BTreeMap::<String, SearchTimestampRange>::new();
6903        for document in documents {
6904            for field in fields {
6905                let actual_values = search_document_field_values(document, field);
6906                if actual_values.is_empty() {
6907                    continue;
6908                }
6909                *present_counts.entry(field.clone()).or_insert(0) += 1;
6910                for value in actual_values {
6911                    values
6912                        .entry(field.clone())
6913                        .or_default()
6914                        .insert(search_segment_summary_value(field, value.as_ref()));
6915                    if let Some(number) = metadata_numeric_value(value.as_ref()) {
6916                        numeric_ranges
6917                            .entry(field.clone())
6918                            .and_modify(|range| *range = range.with_value(number))
6919                            .or_insert_with(|| SearchNumericRange::point(number));
6920                    }
6921                    if let Some(timestamp) = metadata_timestamp_value(value.as_ref()) {
6922                        timestamp_ranges
6923                            .entry(field.clone())
6924                            .and_modify(|range| *range = range.with_value(timestamp))
6925                            .or_insert_with(|| SearchTimestampRange::point(timestamp));
6926                    }
6927                }
6928            }
6929        }
6930        Self {
6931            document_count: documents.len(),
6932            present_counts,
6933            values,
6934            numeric_ranges,
6935            timestamp_ranges,
6936        }
6937    }
6938
6939    fn may_match_predicates(&self, predicates: &SearchPredicateSet) -> bool {
6940        if predicates.is_unsatisfiable() {
6941            return false;
6942        }
6943        // Each predicate is pruned on its own field, so only those fields
6944        // are summarized (#1613).
6945        let summary = self.storage_summary_for(predicates);
6946        predicates.predicates().iter().all(|predicate| {
6947            if !self.may_match_predicate(predicate) {
6948                return false;
6949            }
6950            search_storage_scan_predicate(predicate).map_or_else(
6951                || true,
6952                |predicate| {
6953                    SegmentPruner::new(&summary)
6954                        .evaluate(&predicate)
6955                        .should_open_payload()
6956                },
6957            )
6958        })
6959    }
6960
6961    fn storage_summary_for(&self, predicates: &SearchPredicateSet) -> SegmentSummary {
6962        let fields = predicates
6963            .predicates()
6964            .iter()
6965            .map(|predicate| predicate.field().name())
6966            .collect::<BTreeSet<_>>();
6967        self.storage_summary_fields(|field| fields.contains(field))
6968    }
6969
6970    fn storage_summary_fields(&self, include: impl Fn(&str) -> bool) -> SegmentSummary {
6971        let mut segment = SegmentSummary::new(0, self.document_count as u64);
6972        for field in self
6973            .present_counts
6974            .keys()
6975            .chain(self.values.keys())
6976            .chain(self.numeric_ranges.keys())
6977            .chain(self.timestamp_ranges.keys())
6978            .filter(|field| include(field))
6979        {
6980            if segment.field(field).is_some() {
6981                continue;
6982            }
6983            let present_count = self.present_counts.get(field).copied().unwrap_or_default() as u64;
6984            let mut summary = FieldSummary::new(self.document_count as u64)
6985                .with_presence_counts(present_count, 0, self.document_count as u64 - present_count)
6986                .expect("search summary counts must match segment rows");
6987            if let Some(range) = self.numeric_ranges.get(field) {
6988                summary = summary
6989                    .with_numeric_min_max(range.min, range.max)
6990                    .expect("search numeric summary must be finite and ordered");
6991            }
6992            if let Some(range) = self.timestamp_ranges.get(field) {
6993                summary = summary
6994                    .with_datetime_min_max(range.min_epoch_millis, range.max_epoch_millis)
6995                    .expect("search timestamp summary must be ordered");
6996            }
6997            if let Some(values) = self.values.get(field) {
6998                summary = summary.with_enum_dictionary(EnumDictionaryStats::complete(
6999                    values
7000                        .iter()
7001                        .map(|value| search_segment_summary_value(field, value))
7002                        .map(Value::String),
7003                ));
7004            }
7005            segment.insert_field(field.clone(), summary);
7006        }
7007        segment
7008    }
7009
7010    fn may_match_predicate(&self, predicate: &SearchPredicate) -> bool {
7011        match predicate.op() {
7012            SearchPredicateOp::Eq(expected) => self
7013                .values_may_match_any(predicate.field().name(), std::iter::once(expected.as_str())),
7014            SearchPredicateOp::In(expected_values) => self.values_may_match_any(
7015                predicate.field().name(),
7016                expected_values.iter().map(|value| value.as_str()),
7017            ),
7018            SearchPredicateOp::NotIn(excluded_values) => {
7019                self.values_may_match_not_in(predicate.field().name(), excluded_values)
7020            }
7021            SearchPredicateOp::Gt(expected)
7022            | SearchPredicateOp::Gte(expected)
7023            | SearchPredicateOp::Lt(expected)
7024            | SearchPredicateOp::Lte(expected) => self.numeric_range_may_match(
7025                predicate.field().name(),
7026                predicate.op(),
7027                expected.as_str(),
7028            ),
7029            SearchPredicateOp::Exists => self.field_may_exist(predicate.field().name()),
7030            SearchPredicateOp::IsMissing => self.field_may_be_missing(predicate.field().name()),
7031        }
7032    }
7033
7034    fn field_may_exist(&self, field: &str) -> bool {
7035        self.present_counts.get(field).copied().unwrap_or_default() > 0
7036    }
7037
7038    fn field_may_be_missing(&self, field: &str) -> bool {
7039        self.present_counts.get(field).copied().unwrap_or_default() < self.document_count
7040    }
7041
7042    fn values_may_match_any<'a>(
7043        &self,
7044        field: &str,
7045        expected_values: impl Iterator<Item = &'a str>,
7046    ) -> bool {
7047        let Some(actual_values) = self.values.get(field) else {
7048            return false;
7049        };
7050        expected_values.into_iter().any(|expected| {
7051            actual_values
7052                .iter()
7053                .any(|actual| metadata_value_matches(field, actual, expected))
7054        })
7055    }
7056
7057    fn values_may_match_not_in(
7058        &self,
7059        field: &str,
7060        excluded_values: &BTreeSet<hawdb_optimizer_predicate::SearchScalarValue>,
7061    ) -> bool {
7062        let present_count = self.present_counts.get(field).copied().unwrap_or_default();
7063        if present_count < self.document_count {
7064            return true;
7065        }
7066        let Some(actual_values) = self.values.get(field) else {
7067            return true;
7068        };
7069        actual_values.iter().any(|actual| {
7070            excluded_values
7071                .iter()
7072                .all(|excluded| !metadata_value_matches(field, actual, excluded.as_str()))
7073        })
7074    }
7075
7076    fn numeric_range_may_match(&self, field: &str, op: &SearchPredicateOp, expected: &str) -> bool {
7077        metadata_range_may_match(
7078            self.numeric_ranges.get(field).copied(),
7079            self.timestamp_ranges.get(field).copied(),
7080            op,
7081            expected,
7082        )
7083    }
7084}
7085
7086impl SearchNumericRange {
7087    fn point(value: f64) -> Self {
7088        Self {
7089            min: value,
7090            max: value,
7091        }
7092    }
7093
7094    fn with_value(self, value: f64) -> Self {
7095        Self {
7096            min: self.min.min(value),
7097            max: self.max.max(value),
7098        }
7099    }
7100}
7101
7102impl SearchTimestampRange {
7103    fn point(value: i64) -> Self {
7104        Self {
7105            min_epoch_millis: value,
7106            max_epoch_millis: value,
7107        }
7108    }
7109
7110    fn with_value(self, value: i64) -> Self {
7111        Self {
7112            min_epoch_millis: self.min_epoch_millis.min(value),
7113            max_epoch_millis: self.max_epoch_millis.max(value),
7114        }
7115    }
7116}
7117
7118impl SearchSegmentDescriptor {
7119    /// Whether any segment omits a value set, which requires the V4 grammar.
7120    fn omits_value_summaries(&self) -> bool {
7121        self.segments
7122            .iter()
7123            .any(SearchSegmentDescriptorEntry::omits_value_summaries)
7124    }
7125
7126    fn build(documents: &impl DocumentView) -> Self {
7127        let fields = search_segment_descriptor_fields(documents);
7128        let mut segments = Vec::new();
7129        let mut segment_documents = Vec::with_capacity(SEARCH_FILTER_SEGMENT_TARGET_DOCUMENTS);
7130        for document in documents.values() {
7131            segment_documents.push(document);
7132            if segment_documents.len() == SEARCH_FILTER_SEGMENT_TARGET_DOCUMENTS {
7133                segments.push(SearchSegmentDescriptorEntry::from_documents(
7134                    segments.len() as u64,
7135                    &segment_documents,
7136                    &fields,
7137                ));
7138                segment_documents.clear();
7139            }
7140        }
7141        if !segment_documents.is_empty() {
7142            segments.push(SearchSegmentDescriptorEntry::from_documents(
7143                segments.len() as u64,
7144                &segment_documents,
7145                &fields,
7146            ));
7147        }
7148        Self {
7149            target_documents: SEARCH_FILTER_SEGMENT_TARGET_DOCUMENTS,
7150            document_count: documents.len(),
7151            segments,
7152        }
7153    }
7154
7155    fn matches_documents(&self, documents: &impl DocumentView) -> bool {
7156        self.target_documents == SEARCH_FILTER_SEGMENT_TARGET_DOCUMENTS
7157            && self.document_count == documents.len()
7158            && self
7159                .segments
7160                .first()
7161                .map(|segment| segment.first_document_id.as_str())
7162                == documents.keys().next().map(String::as_str)
7163            && self
7164                .segments
7165                .last()
7166                .map(|segment| segment.last_document_id.as_str())
7167                == documents.keys().next_back().map(String::as_str)
7168    }
7169
7170    fn payload_artifact_is_available(&self, path: &Path) -> Result<bool> {
7171        let Some(last_range) = self
7172            .segments
7173            .iter()
7174            .filter_map(|segment| segment.payload_range)
7175            .next_back()
7176        else {
7177            return Ok(true);
7178        };
7179        match fs::metadata(path.join(SEARCH_SEGMENT_PAYLOAD_FILE)) {
7180            Ok(metadata) => {
7181                Ok(metadata.len() >= last_range.offset.saturating_add(last_range.length))
7182            }
7183            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
7184            Err(error) => Err(error.into()),
7185        }
7186    }
7187
7188    fn payload_artifact_is_available_under_publication(
7189        &self,
7190        publication: &out_of_core::SearchProjectionPublishLease,
7191    ) -> Result<bool> {
7192        let Some(last_range) = self
7193            .segments
7194            .iter()
7195            .filter_map(|segment| segment.payload_range)
7196            .next_back()
7197        else {
7198            return Ok(true);
7199        };
7200        match publication.open_captured_child(SEARCH_SEGMENT_PAYLOAD_FILE) {
7201            Ok(file) => {
7202                Ok(file.metadata()?.len() >= last_range.offset.saturating_add(last_range.length))
7203            }
7204            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
7205            Err(error) => Err(error.into()),
7206        }
7207    }
7208
7209    fn physical_read_ranges(&self) -> Vec<SegmentReadRange> {
7210        self.segments
7211            .iter()
7212            .filter_map(|segment| {
7213                let range = segment.payload_range?;
7214                Some(SegmentReadRange::new(
7215                    range.artifact_id,
7216                    segment.segment_id,
7217                    range.offset,
7218                    std::num::NonZeroU64::new(range.length)?,
7219                ))
7220            })
7221            .collect()
7222    }
7223}
7224
7225impl SearchSegmentDescriptorEntry {
7226    /// Whether any field omits its value set, which requires the V4 grammar.
7227    fn omits_value_summaries(&self) -> bool {
7228        self.metadata.values().any(|summary| summary.values_omitted)
7229    }
7230
7231    fn from_documents(
7232        segment_id: u64,
7233        documents: &[&SearchDocument],
7234        fields: &BTreeSet<String>,
7235    ) -> Self {
7236        let first_document_id = documents
7237            .first()
7238            .map(|document| document.id.clone())
7239            .unwrap_or_default();
7240        let last_document_id = documents
7241            .last()
7242            .map(|document| document.id.clone())
7243            .unwrap_or_default();
7244        let mut metadata = fields
7245            .iter()
7246            .map(|field| (field.clone(), SearchSegmentFieldSummary::default()))
7247            .collect::<BTreeMap<_, _>>();
7248        for document in documents {
7249            for field in fields {
7250                let values = search_document_field_values(document, field);
7251                if values.is_empty() {
7252                    continue;
7253                }
7254                let summary = metadata.entry(field.clone()).or_default();
7255                summary.present_count += 1;
7256                for value in values {
7257                    summary
7258                        .values
7259                        .insert(search_segment_summary_value(field, value.as_ref()));
7260                    summary.update_range_summaries(value.as_ref());
7261                }
7262            }
7263        }
7264        Self {
7265            segment_id,
7266            first_document_id,
7267            last_document_id,
7268            document_count: documents.len(),
7269            payload_range: None,
7270            metadata,
7271        }
7272    }
7273
7274    fn may_match_predicates(&self, predicates: &SearchPredicateSet) -> bool {
7275        if predicates.is_unsatisfiable() {
7276            return false;
7277        }
7278        // Each predicate is pruned on its own field, so only those fields
7279        // are summarized (#1613).
7280        let summary = self.storage_summary_for(predicates);
7281        predicates.predicates().iter().all(|predicate| {
7282            if !self.may_match_predicate(predicate) {
7283                return false;
7284            }
7285            search_storage_scan_predicate(predicate).map_or_else(
7286                || true,
7287                |predicate| {
7288                    SegmentPruner::new(&summary)
7289                        .evaluate(&predicate)
7290                        .should_open_payload()
7291                },
7292            )
7293        })
7294    }
7295
7296    fn storage_summary_for(&self, predicates: &SearchPredicateSet) -> SegmentSummary {
7297        let fields = predicates
7298            .predicates()
7299            .iter()
7300            .map(|predicate| predicate.field().name())
7301            .collect::<BTreeSet<_>>();
7302        let mut segment = SegmentSummary::new(0, self.document_count as u64);
7303        for (field, persisted) in self
7304            .metadata
7305            .iter()
7306            .filter(|(field, _)| fields.contains(field.as_str()))
7307        {
7308            let mut summary = FieldSummary::new(self.document_count as u64)
7309                .with_presence_counts(
7310                    persisted.present_count as u64,
7311                    0,
7312                    self.document_count as u64 - persisted.present_count as u64,
7313                )
7314                .expect("persisted search summary counts must match segment rows");
7315            if let Some(range) = persisted.numeric_range {
7316                summary = summary
7317                    .with_numeric_min_max(range.min, range.max)
7318                    .expect("persisted numeric summary must be finite and ordered");
7319            }
7320            if let Some(range) = persisted.timestamp_range {
7321                summary = summary
7322                    .with_datetime_min_max(range.min_epoch_millis, range.max_epoch_millis)
7323                    .expect("persisted timestamp summary must be ordered");
7324            }
7325            // An omitted value set proves nothing, so it adds no dictionary.
7326            if !persisted.values_omitted {
7327                summary = summary.with_enum_dictionary(EnumDictionaryStats::complete(
7328                    persisted
7329                        .values
7330                        .iter()
7331                        .map(|value| search_segment_summary_value(field, value))
7332                        .map(Value::String),
7333                ));
7334            }
7335            segment.insert_field(field.clone(), summary);
7336        }
7337        segment
7338    }
7339
7340    fn may_match_predicate(&self, predicate: &SearchPredicate) -> bool {
7341        match predicate.op() {
7342            SearchPredicateOp::Eq(expected) => self
7343                .values_may_match_any(predicate.field().name(), std::iter::once(expected.as_str())),
7344            SearchPredicateOp::In(expected_values) => self.values_may_match_any(
7345                predicate.field().name(),
7346                expected_values.iter().map(|value| value.as_str()),
7347            ),
7348            SearchPredicateOp::NotIn(excluded_values) => {
7349                self.values_may_match_not_in(predicate.field().name(), excluded_values)
7350            }
7351            SearchPredicateOp::Gt(expected)
7352            | SearchPredicateOp::Gte(expected)
7353            | SearchPredicateOp::Lt(expected)
7354            | SearchPredicateOp::Lte(expected) => self.numeric_range_may_match(
7355                predicate.field().name(),
7356                predicate.op(),
7357                expected.as_str(),
7358            ),
7359            SearchPredicateOp::Exists => self.field_may_exist(predicate.field().name()),
7360            SearchPredicateOp::IsMissing => self.field_may_be_missing(predicate.field().name()),
7361        }
7362    }
7363
7364    fn field_may_exist(&self, field: &str) -> bool {
7365        self.metadata
7366            .get(field)
7367            .is_some_and(|summary| summary.present_count > 0)
7368    }
7369
7370    fn field_may_be_missing(&self, field: &str) -> bool {
7371        self.metadata
7372            .get(field)
7373            .is_none_or(|summary| summary.present_count < self.document_count)
7374    }
7375
7376    fn values_may_match_any<'a>(
7377        &self,
7378        field: &str,
7379        expected_values: impl Iterator<Item = &'a str>,
7380    ) -> bool {
7381        let Some(summary) = self.metadata.get(field) else {
7382            return false;
7383        };
7384        if summary.values_omitted {
7385            return summary.present_count > 0;
7386        }
7387        expected_values.into_iter().any(|expected| {
7388            summary
7389                .values
7390                .iter()
7391                .any(|actual| metadata_value_matches(field, actual, expected))
7392        })
7393    }
7394
7395    fn values_may_match_not_in(
7396        &self,
7397        field: &str,
7398        excluded_values: &BTreeSet<hawdb_optimizer_predicate::SearchScalarValue>,
7399    ) -> bool {
7400        let Some(summary) = self.metadata.get(field) else {
7401            return true;
7402        };
7403        if summary.present_count < self.document_count || summary.values_omitted {
7404            return true;
7405        }
7406        summary.values.iter().any(|actual| {
7407            excluded_values
7408                .iter()
7409                .all(|excluded| !metadata_value_matches(field, actual, excluded.as_str()))
7410        })
7411    }
7412
7413    fn numeric_range_may_match(&self, field: &str, op: &SearchPredicateOp, expected: &str) -> bool {
7414        metadata_range_may_match(
7415            self.metadata
7416                .get(field)
7417                .and_then(|summary| summary.numeric_range),
7418            self.metadata
7419                .get(field)
7420                .and_then(|summary| summary.timestamp_range),
7421            op,
7422            expected,
7423        )
7424    }
7425}
7426
7427fn search_storage_scan_predicate(predicate: &SearchPredicate) -> Option<ScanPredicate> {
7428    let property = predicate.field().name().to_string();
7429    let summary_value = |value: &SearchScalarValue| {
7430        Value::String(search_segment_summary_value(
7431            predicate.field().name(),
7432            value.as_str(),
7433        ))
7434    };
7435    match predicate.op() {
7436        SearchPredicateOp::Eq(value) => Some(ScanPredicate::Eq {
7437            property,
7438            value: summary_value(value),
7439        }),
7440        SearchPredicateOp::In(values) => Some(ScanPredicate::In {
7441            property,
7442            values: values.iter().map(summary_value).collect(),
7443        }),
7444        SearchPredicateOp::NotIn(_) => None,
7445        SearchPredicateOp::Gt(value) => Some(ScanPredicate::Range {
7446            property,
7447            lower: Some(RangeBound::exclusive(search_range_summary_value(value))),
7448            upper: None,
7449        }),
7450        SearchPredicateOp::Gte(value) => Some(ScanPredicate::Range {
7451            property,
7452            lower: Some(RangeBound::inclusive(search_range_summary_value(value))),
7453            upper: None,
7454        }),
7455        SearchPredicateOp::Lt(value) => Some(ScanPredicate::Range {
7456            property,
7457            lower: None,
7458            upper: Some(RangeBound::exclusive(search_range_summary_value(value))),
7459        }),
7460        SearchPredicateOp::Lte(value) => Some(ScanPredicate::Range {
7461            property,
7462            lower: None,
7463            upper: Some(RangeBound::inclusive(search_range_summary_value(value))),
7464        }),
7465        SearchPredicateOp::Exists => Some(ScanPredicate::Exists { property }),
7466        SearchPredicateOp::IsMissing => Some(ScanPredicate::IsMissing { property }),
7467    }
7468}
7469
7470fn search_range_summary_value(value: &SearchScalarValue) -> Value {
7471    metadata_numeric_value(value.as_str())
7472        .map(Value::Float)
7473        .unwrap_or_else(|| Value::String(value.as_str().to_string()))
7474}
7475
7476impl SearchSegmentFieldSummary {
7477    /// Drop the value set; value predicates can no longer skip the segment.
7478    fn omit_values(&mut self) {
7479        self.values = BTreeSet::new();
7480        self.values_omitted = true;
7481    }
7482
7483    fn update_range_summaries(&mut self, value: &str) {
7484        if let Some(number) = metadata_numeric_value(value) {
7485            self.numeric_range = Some(match self.numeric_range {
7486                Some(range) => range.with_value(number),
7487                None => SearchNumericRange::point(number),
7488            });
7489        }
7490        if let Some(timestamp) = metadata_timestamp_value(value) {
7491            self.timestamp_range = Some(match self.timestamp_range {
7492                Some(range) => range.with_value(timestamp),
7493                None => SearchTimestampRange::point(timestamp),
7494            });
7495        }
7496    }
7497}
7498
7499fn search_segment_descriptor_fields(documents: &impl DocumentView) -> BTreeSet<String> {
7500    let mut fields = documents
7501        .values()
7502        .flat_map(|document| document.metadata.keys().cloned())
7503        .collect::<BTreeSet<_>>();
7504    fields.insert(SEARCH_DOCUMENT_ID_FIELD.to_string());
7505    fields.extend(
7506        NOWLEDGE_SEARCH_PROJECTION_SCAN_FILTER_FIELDS
7507            .iter()
7508            .map(|field| field.to_string()),
7509    );
7510    fields
7511}
7512
7513fn search_header_matches_predicate(
7514    header: crate::document_encoding::Header<'_>,
7515    predicate: &SearchPredicate,
7516) -> bool {
7517    let actual_values = search_header_field_values(header, predicate.field().name());
7518    match predicate.op() {
7519        SearchPredicateOp::Eq(expected) => actual_values.iter().any(|actual| {
7520            metadata_value_matches(predicate.field().name(), actual.as_ref(), expected.as_str())
7521        }),
7522        SearchPredicateOp::In(expected_values) => actual_values.iter().any(|actual| {
7523            expected_values.iter().any(|expected| {
7524                metadata_value_matches(predicate.field().name(), actual.as_ref(), expected.as_str())
7525            })
7526        }),
7527        SearchPredicateOp::NotIn(excluded_values) => actual_values.iter().all(|actual| {
7528            excluded_values.iter().all(|excluded| {
7529                !metadata_value_matches(
7530                    predicate.field().name(),
7531                    actual.as_ref(),
7532                    excluded.as_str(),
7533                )
7534            })
7535        }),
7536        SearchPredicateOp::Gt(expected) => actual_values
7537            .iter()
7538            .any(|actual| metadata_range_gt(actual.as_ref(), expected.as_str())),
7539        SearchPredicateOp::Gte(expected) => actual_values
7540            .iter()
7541            .any(|actual| metadata_range_gte(actual.as_ref(), expected.as_str())),
7542        SearchPredicateOp::Lt(expected) => actual_values
7543            .iter()
7544            .any(|actual| metadata_range_lt(actual.as_ref(), expected.as_str())),
7545        SearchPredicateOp::Lte(expected) => actual_values
7546            .iter()
7547            .any(|actual| metadata_range_lte(actual.as_ref(), expected.as_str())),
7548        SearchPredicateOp::Exists => !actual_values.is_empty(),
7549        SearchPredicateOp::IsMissing => actual_values.is_empty(),
7550    }
7551}
7552
7553fn search_document_field_values<'a>(document: &'a SearchDocument, key: &str) -> Vec<Cow<'a, str>> {
7554    use crate::document_encoding::HeaderSource;
7555    search_header_field_values(document.header(), key)
7556}
7557
7558fn search_header_field_values<'a>(
7559    header: crate::document_encoding::Header<'a>,
7560    key: &str,
7561) -> Vec<Cow<'a, str>> {
7562    if key == "labels" || key.starts_with("metadata.") {
7563        return header
7564            .metadata
7565            .get(key)
7566            .map(|value| parse_label_metadata_values(value))
7567            .unwrap_or_default();
7568    }
7569    header.field(key).map(Cow::Borrowed).into_iter().collect()
7570}
7571
7572fn parse_label_metadata_values(value: &str) -> Vec<Cow<'_, str>> {
7573    if let Ok(values) = serde_json::from_str::<Vec<String>>(value) {
7574        return values
7575            .into_iter()
7576            .map(|value| Cow::<str>::Owned(value.trim().to_string()))
7577            .filter(|value| !value.is_empty())
7578            .collect();
7579    }
7580    value
7581        .split(',')
7582        .map(str::trim)
7583        .filter(|value| !value.is_empty())
7584        .map(Cow::Borrowed)
7585        .collect()
7586}
7587
7588fn metadata_value_matches(key: &str, actual: &str, expected: &str) -> bool {
7589    normalize_metadata_posting_value(key, actual) == normalize_metadata_posting_value(key, expected)
7590}
7591
7592/// Canonical value shared by metadata matching and persistent postings.
7593fn normalize_metadata_posting_value(key: &str, value: &str) -> String {
7594    match key {
7595        "kind" => normalized_projection_kind(value)
7596            .map(str::to_string)
7597            .unwrap_or_else(|| value.to_string()),
7598        _ => normalize_metadata_filter_value(value),
7599    }
7600}
7601
7602fn search_segment_summary_value(key: &str, value: &str) -> String {
7603    match key {
7604        "kind" => normalized_projection_kind(value)
7605            .map(str::to_string)
7606            .unwrap_or_else(|| normalize_search_enum_value(value)),
7607        key if search_field_is_enum_like(key) => normalize_search_enum_value(value),
7608        _ => normalize_metadata_filter_value(value),
7609    }
7610}
7611
7612fn normalize_metadata_filter_value(value: &str) -> String {
7613    value.trim().to_lowercase()
7614}
7615
7616fn metadata_numeric_value(value: &str) -> Option<f64> {
7617    let number = value.trim().parse::<f64>().ok()?;
7618    number.is_finite().then_some(number)
7619}
7620
7621fn metadata_timestamp_value(value: &str) -> Option<i64> {
7622    hawdb_core::temporal::parse_metadata_millis(value)
7623}
7624
7625fn metadata_range_gt(actual: &str, expected: &str) -> bool {
7626    metadata_numeric_pair(actual, expected).is_some_and(|(actual, expected)| actual > expected)
7627        || metadata_timestamp_pair(actual, expected)
7628            .is_some_and(|(actual, expected)| actual > expected)
7629}
7630
7631fn metadata_range_gte(actual: &str, expected: &str) -> bool {
7632    metadata_numeric_pair(actual, expected).is_some_and(|(actual, expected)| actual >= expected)
7633        || metadata_timestamp_pair(actual, expected)
7634            .is_some_and(|(actual, expected)| actual >= expected)
7635}
7636
7637fn metadata_range_lt(actual: &str, expected: &str) -> bool {
7638    metadata_numeric_pair(actual, expected).is_some_and(|(actual, expected)| actual < expected)
7639        || metadata_timestamp_pair(actual, expected)
7640            .is_some_and(|(actual, expected)| actual < expected)
7641}
7642
7643fn metadata_range_lte(actual: &str, expected: &str) -> bool {
7644    metadata_numeric_pair(actual, expected).is_some_and(|(actual, expected)| actual <= expected)
7645        || metadata_timestamp_pair(actual, expected)
7646            .is_some_and(|(actual, expected)| actual <= expected)
7647}
7648
7649fn metadata_numeric_pair(actual: &str, expected: &str) -> Option<(f64, f64)> {
7650    Some((
7651        metadata_numeric_value(actual)?,
7652        metadata_numeric_value(expected)?,
7653    ))
7654}
7655
7656fn metadata_timestamp_pair(actual: &str, expected: &str) -> Option<(i64, i64)> {
7657    Some((
7658        metadata_timestamp_value(actual)?,
7659        metadata_timestamp_value(expected)?,
7660    ))
7661}
7662
7663fn metadata_range_may_match(
7664    numeric_range: Option<SearchNumericRange>,
7665    timestamp_range: Option<SearchTimestampRange>,
7666    op: &SearchPredicateOp,
7667    expected: &str,
7668) -> bool {
7669    if let Some(expected) = metadata_numeric_value(expected) {
7670        return numeric_range
7671            .map(|range| metadata_numeric_range_may_match(range, op, expected))
7672            .unwrap_or(false);
7673    }
7674    if let Some(expected) = metadata_timestamp_value(expected) {
7675        return timestamp_range
7676            .map(|range| metadata_timestamp_range_may_match(range, op, expected))
7677            .unwrap_or(false);
7678    }
7679    false
7680}
7681
7682fn metadata_numeric_range_may_match(
7683    range: SearchNumericRange,
7684    op: &SearchPredicateOp,
7685    expected: f64,
7686) -> bool {
7687    match op {
7688        SearchPredicateOp::Gt(_) => range.max > expected,
7689        SearchPredicateOp::Gte(_) => range.max >= expected,
7690        SearchPredicateOp::Lt(_) => range.min < expected,
7691        SearchPredicateOp::Lte(_) => range.min <= expected,
7692        SearchPredicateOp::Eq(_)
7693        | SearchPredicateOp::In(_)
7694        | SearchPredicateOp::NotIn(_)
7695        | SearchPredicateOp::Exists
7696        | SearchPredicateOp::IsMissing => true,
7697    }
7698}
7699
7700fn metadata_timestamp_range_may_match(
7701    range: SearchTimestampRange,
7702    op: &SearchPredicateOp,
7703    expected: i64,
7704) -> bool {
7705    match op {
7706        SearchPredicateOp::Gt(_) => range.max_epoch_millis > expected,
7707        SearchPredicateOp::Gte(_) => range.max_epoch_millis >= expected,
7708        SearchPredicateOp::Lt(_) => range.min_epoch_millis < expected,
7709        SearchPredicateOp::Lte(_) => range.min_epoch_millis <= expected,
7710        SearchPredicateOp::Eq(_)
7711        | SearchPredicateOp::In(_)
7712        | SearchPredicateOp::NotIn(_)
7713        | SearchPredicateOp::Exists
7714        | SearchPredicateOp::IsMissing => true,
7715    }
7716}
7717
7718fn normalized_projection_kind(value: &str) -> Option<&'static str> {
7719    match value {
7720        "Memory" | "memory" => Some("memory"),
7721        "Message" | "message" => Some("message"),
7722        "Entity" | "entity" => Some("entity"),
7723        "Source" | "source" => Some("source"),
7724        "SourceChunk" | "source_chunk" | "sourcechunk" | "chunk" => Some("source_chunk"),
7725        "Community" | "community" => Some("community"),
7726        _ => None,
7727    }
7728}
7729
7730#[cfg(test)]
7731#[derive(Debug, Clone, PartialEq)]
7732struct TextCorpusStats {
7733    document_count: usize,
7734    average_document_len: f64,
7735    document_frequency: BTreeMap<String, usize>,
7736}
7737
7738#[cfg(test)]
7739impl TextCorpusStats {
7740    fn from_documents<'a>(
7741        documents: impl Iterator<Item = &'a SearchDocument>,
7742        analyzer_lexicon: &SearchAnalyzerLexicon,
7743    ) -> Self {
7744        let mut document_count = 0;
7745        let mut total_len = 0;
7746        let mut document_frequency = BTreeMap::new();
7747        for document in documents {
7748            document_count += 1;
7749            let tokens = document_tokens(document, analyzer_lexicon);
7750            total_len += tokens.len();
7751            for term in tokens.into_iter().collect::<BTreeSet<_>>() {
7752                *document_frequency.entry(term).or_insert(0) += 1;
7753            }
7754        }
7755        Self {
7756            document_count,
7757            average_document_len: if document_count == 0 {
7758                0.0
7759            } else {
7760                total_len as f64 / document_count as f64
7761            },
7762            document_frequency,
7763        }
7764    }
7765}
7766
7767#[cfg(test)]
7768fn bm25_score(
7769    query_terms: &BTreeSet<String>,
7770    document: &SearchDocument,
7771    corpus: &TextCorpusStats,
7772    analyzer_lexicon: &SearchAnalyzerLexicon,
7773) -> f64 {
7774    if query_terms.is_empty() || corpus.document_count == 0 {
7775        return 0.0;
7776    }
7777    let tokens = document_tokens(document, analyzer_lexicon);
7778    if tokens.is_empty() {
7779        return 0.0;
7780    }
7781    let term_frequency = token_frequencies(tokens.iter().cloned());
7782    let document_len = tokens.len() as f64;
7783    let average_document_len = corpus.average_document_len.max(1.0);
7784    let mut score = 0.0;
7785    for term in query_terms {
7786        let Some(frequency) = term_frequency.get(term).copied() else {
7787            continue;
7788        };
7789        let document_frequency = corpus
7790            .document_frequency
7791            .get(term)
7792            .copied()
7793            .unwrap_or_default();
7794        if document_frequency == 0 {
7795            continue;
7796        }
7797        let idf = (1.0
7798            + (corpus.document_count as f64 - document_frequency as f64 + 0.5)
7799                / (document_frequency as f64 + 0.5))
7800            .ln();
7801        let frequency = frequency as f64;
7802        let denominator =
7803            frequency + BM25_K1 * (1.0 - BM25_B + BM25_B * document_len / average_document_len);
7804        score += idf * (frequency * (BM25_K1 + 1.0)) / denominator;
7805    }
7806    score
7807}
7808
7809/// Reference: query terms among the whole document's tokens.
7810#[cfg(test)]
7811fn matched_query_terms(
7812    query_terms: &BTreeSet<String>,
7813    document: &SearchDocument,
7814    analyzer_lexicon: &SearchAnalyzerLexicon,
7815) -> Vec<String> {
7816    if query_terms.is_empty() {
7817        return Vec::new();
7818    }
7819    let document_terms = document_tokens(document, analyzer_lexicon)
7820        .into_iter()
7821        .collect::<BTreeSet<_>>();
7822    query_terms
7823        .iter()
7824        .filter(|term| document_terms.contains(*term))
7825        .cloned()
7826        .collect()
7827}
7828
7829#[cfg(test)]
7830fn matched_query_spans(
7831    query_terms: &BTreeSet<String>,
7832    document: &SearchDocument,
7833    analyzer_lexicon: &SearchAnalyzerLexicon,
7834) -> Vec<SearchMatchedSpan> {
7835    matched_query_spans_bounded(
7836        query_terms,
7837        document,
7838        analyzer_lexicon,
7839        usize::MAX,
7840        u64::MAX,
7841        0,
7842    )
7843    .expect("unbounded matched-span collection cannot exhaust its admission limit")
7844}
7845
7846/// Matched terms and spans of one hit without query memory accounting. The
7847/// span count and byte limits behave like the reference collector's.
7848fn query_matches_bounded(
7849    query_terms: &BTreeSet<String>,
7850    document: &SearchDocument,
7851    analyzer_lexicon: &SearchAnalyzerLexicon,
7852    max_spans: usize,
7853    max_bytes: u64,
7854    used_bytes: u64,
7855) -> Result<(Vec<String>, Vec<SearchMatchedSpan>)> {
7856    let mut terms = BTreeSet::new();
7857    let mut spans = Vec::new();
7858    let mut span_bytes = 0u64;
7859    query_matches::visit(
7860        query_terms,
7861        document,
7862        analyzer_lexicon,
7863        analyzer_stream::Control::default(),
7864        |term| {
7865            terms.insert(term);
7866            Ok(())
7867        },
7868        || Ok(()),
7869        |span| {
7870            if spans.len() >= max_spans {
7871                return Err(HawDBError::Storage(format!(
7872                    "search matched-span hydration exceeded {max_spans} spans"
7873                )));
7874            }
7875            let required = (span.field.len() as u64)
7876                .saturating_add(span.text.len() as u64)
7877                .saturating_add(span.term.len() as u64)
7878                .saturating_add(std::mem::size_of::<SearchMatchedSpan>() as u64);
7879            let previous_bytes = span_bytes;
7880            span_bytes = span_bytes.saturating_add(required);
7881            let remaining_bytes = max_bytes.saturating_sub(used_bytes);
7882            if span_bytes > remaining_bytes {
7883                return Err(ResourceBudgetError {
7884                    resource: ResourceBudgetKind::MemoryBytes,
7885                    scope: ResourceBudgetScope::Operator,
7886                    owner: "search matched-span hydration".to_string(),
7887                    memory_class: None,
7888                    requested: required,
7889                    used: used_bytes.saturating_add(previous_bytes),
7890                    budget: max_bytes,
7891                    budget_option: "SearchOutOfCoreConfig.max_matched_span_bytes",
7892                    message: format!(
7893                        "search matched-span hydration requires {span_bytes} bytes, exceeding {remaining_bytes}"
7894                    ),
7895                }
7896                .into());
7897            }
7898            spans.push(SearchMatchedSpan {
7899                field: span.field.to_string(),
7900                start_byte: span.start,
7901                end_byte: span.end,
7902                text: span.text.to_string(),
7903                term: span.term.to_string(),
7904            });
7905            Ok(())
7906        },
7907    )?;
7908    Ok((terms.into_iter().map(str::to_string).collect(), spans))
7909}
7910
7911/// Reference: every word of title and content analyzed on its own.
7912#[cfg(test)]
7913fn matched_query_spans_bounded(
7914    query_terms: &BTreeSet<String>,
7915    document: &SearchDocument,
7916    analyzer_lexicon: &SearchAnalyzerLexicon,
7917    max_spans: usize,
7918    max_bytes: u64,
7919    used_bytes: u64,
7920) -> Result<Vec<SearchMatchedSpan>> {
7921    if query_terms.is_empty() {
7922        return Ok(Vec::new());
7923    }
7924    let mut collector = MatchedSpanCollector {
7925        query_terms,
7926        analyzer_lexicon,
7927        spans: Vec::new(),
7928        span_bytes: 0,
7929        max_spans,
7930        max_bytes,
7931        used_bytes,
7932    };
7933    collector.collect("title", &document.title)?;
7934    collector.collect("content", &document.content)?;
7935    Ok(collector.spans)
7936}
7937
7938#[cfg(test)]
7939struct MatchedSpanCollector<'a> {
7940    query_terms: &'a BTreeSet<String>,
7941    analyzer_lexicon: &'a SearchAnalyzerLexicon,
7942    spans: Vec<SearchMatchedSpan>,
7943    span_bytes: u64,
7944    max_spans: usize,
7945    max_bytes: u64,
7946    used_bytes: u64,
7947}
7948
7949#[cfg(test)]
7950impl MatchedSpanCollector<'_> {
7951    fn collect(&mut self, field: &str, text: &str) -> Result<()> {
7952        let mut run_start = None::<usize>;
7953        for (index, ch) in text.char_indices() {
7954            if ch.is_alphanumeric() || ch == '_' {
7955                run_start.get_or_insert(index);
7956            } else if let Some(start) = run_start.take() {
7957                self.push(field, text, start, index)?;
7958            }
7959        }
7960        if let Some(start) = run_start {
7961            self.push(field, text, start, text.len())?;
7962        }
7963        Ok(())
7964    }
7965
7966    fn push(&mut self, field: &str, text: &str, start_byte: usize, end_byte: usize) -> Result<()> {
7967        let raw = &text[start_byte..end_byte];
7968        let matching_terms = identifier_tokens(raw, self.analyzer_lexicon)
7969            .into_iter()
7970            .filter(|term| self.query_terms.contains(term))
7971            .collect::<BTreeSet<_>>();
7972        for term in matching_terms {
7973            if self.spans.len() >= self.max_spans {
7974                return Err(HawDBError::Storage(format!(
7975                    "search matched-span hydration exceeded {} spans",
7976                    self.max_spans
7977                )));
7978            }
7979            let required = (field.len() as u64)
7980                .saturating_add(raw.len() as u64)
7981                .saturating_add(term.len() as u64)
7982                .saturating_add(std::mem::size_of::<SearchMatchedSpan>() as u64);
7983            let previous_bytes = self.span_bytes;
7984            self.span_bytes = self.span_bytes.saturating_add(required);
7985            let remaining_bytes = self.max_bytes.saturating_sub(self.used_bytes);
7986            if self.span_bytes > remaining_bytes {
7987                return Err(ResourceBudgetError {
7988                    resource: ResourceBudgetKind::MemoryBytes,
7989                    scope: ResourceBudgetScope::Operator,
7990                    owner: "search matched-span hydration".to_string(),
7991                    memory_class: None,
7992                    requested: required,
7993                    used: self.used_bytes.saturating_add(previous_bytes),
7994                    budget: self.max_bytes,
7995                    budget_option: "SearchOutOfCoreConfig.max_matched_span_bytes",
7996                    message: format!(
7997                        "search matched-span hydration requires {} bytes, exceeding {remaining_bytes}",
7998                        self.span_bytes
7999                    ),
8000                }
8001                .into());
8002            }
8003            self.spans.push(SearchMatchedSpan {
8004                field: field.to_string(),
8005                start_byte,
8006                end_byte,
8007                text: raw.to_string(),
8008                term,
8009            });
8010        }
8011        Ok(())
8012    }
8013}
8014
8015#[cfg(test)]
8016fn document_tokens(
8017    document: &SearchDocument,
8018    analyzer_lexicon: &SearchAnalyzerLexicon,
8019) -> Vec<String> {
8020    let mut tokens = Vec::new();
8021    for (text, weight) in document_token_fields(document) {
8022        let field_tokens = tokenize_list(text, analyzer_lexicon);
8023        for _ in 1..weight {
8024            tokens.extend(field_tokens.iter().cloned());
8025        }
8026        tokens.extend(field_tokens);
8027    }
8028    tokens
8029}
8030
8031#[cfg(test)]
8032fn token_frequencies(tokens: impl Iterator<Item = String>) -> BTreeMap<String, usize> {
8033    let mut frequencies = BTreeMap::new();
8034    for token in tokens {
8035        *frequencies.entry(token).or_insert(0) += 1;
8036    }
8037    frequencies
8038}
8039
8040fn tokenize(text: &str, analyzer_lexicon: &SearchAnalyzerLexicon) -> BTreeSet<String> {
8041    tokenize_list(text, analyzer_lexicon).into_iter().collect()
8042}
8043
8044/// Distinct query terms, refusing as soon as they would exceed the analyzed
8045/// cap. Like the out-of-core normalizer, refusal costs O(cap) analysis rather
8046/// than tokenizing the remainder of an oversized query.
8047fn tokenize_query_bounded(
8048    text: &str,
8049    analyzer_lexicon: &SearchAnalyzerLexicon,
8050    config: &LexicalProjectionConfig,
8051) -> Result<BTreeSet<String>> {
8052    let limit = config.analyzed_query_term_limit();
8053    let mut terms = BTreeSet::new();
8054    analyzer_stream::visit_token_list(text, analyzer_lexicon, |term, _| {
8055        if !terms.contains(&term) {
8056            if terms.len() >= limit {
8057                return Err(config.analyzed_query_term_error());
8058            }
8059            terms.insert(term);
8060        }
8061        Ok(())
8062    })?;
8063    Ok(terms)
8064}
8065
8066fn tokenize_list(text: &str, analyzer_lexicon: &SearchAnalyzerLexicon) -> Vec<String> {
8067    analyzer_stream::collect_token_list(text, analyzer_lexicon)
8068}
8069
8070fn normalized_alias_rule_terms(text: &str) -> Vec<String> {
8071    tokenize_list(text, &SearchAnalyzerLexicon::empty())
8072}
8073
8074fn normalized_stopword_terms(text: &str) -> Vec<String> {
8075    tokenize_list(text, &SearchAnalyzerLexicon::empty())
8076}
8077
8078#[cfg(test)]
8079fn identifier_tokens(raw: &str, analyzer_lexicon: &SearchAnalyzerLexicon) -> Vec<String> {
8080    analyzer_stream::identifier_tokens(raw, analyzer_lexicon)
8081}
8082
8083// Keep the eager expansion helpers as an independent test reference.
8084#[cfg(test)]
8085fn push_cjk_ngram_tokens(
8086    tokens: &mut TokenSequence,
8087    raw: &str,
8088    analyzer_lexicon: &SearchAnalyzerLexicon,
8089) {
8090    let mut run = Vec::new();
8091    for ch in raw.chars() {
8092        if is_cjk_search_char(ch) {
8093            run.push(ch);
8094        } else {
8095            push_cjk_ngram_run_tokens(tokens, &run, analyzer_lexicon);
8096            run.clear();
8097        }
8098    }
8099    push_cjk_ngram_run_tokens(tokens, &run, analyzer_lexicon);
8100}
8101
8102#[cfg(test)]
8103fn push_cjk_ngram_run_tokens(
8104    tokens: &mut TokenSequence,
8105    run: &[char],
8106    analyzer_lexicon: &SearchAnalyzerLexicon,
8107) {
8108    for width in [2_usize, 3] {
8109        if run.len() < width {
8110            continue;
8111        }
8112        for window in run.windows(width) {
8113            push_unique_token(tokens, window.iter().collect(), analyzer_lexicon);
8114        }
8115    }
8116}
8117
8118#[cfg(test)]
8119fn push_unique_token(
8120    tokens: &mut TokenSequence,
8121    token: String,
8122    analyzer_lexicon: &SearchAnalyzerLexicon,
8123) {
8124    if !token.is_empty() && !analyzer_lexicon.is_stopword(&token) {
8125        tokens.push_unique(token);
8126    }
8127}
8128
8129#[cfg(test)]
8130fn push_analyzed_token(
8131    tokens: &mut TokenSequence,
8132    token: String,
8133    analyzer_lexicon: &SearchAnalyzerLexicon,
8134) {
8135    push_unique_token(tokens, token.clone(), analyzer_lexicon);
8136    for normalized in normalize_english_suffixes(&token) {
8137        push_unique_token(tokens, normalized, analyzer_lexicon);
8138    }
8139    for alias in analyzer_lexicon.semantic_aliases(&token) {
8140        push_unique_token(tokens, alias, analyzer_lexicon);
8141    }
8142}
8143
8144#[derive(Debug, Default)]
8145struct TokenSequence {
8146    token_ids: HashMap<String, usize>,
8147    order: Vec<usize>,
8148}
8149
8150impl TokenSequence {
8151    #[cfg(test)]
8152    fn push_unique(&mut self, token: String) {
8153        let next_id = self.token_ids.len();
8154        if let std::collections::hash_map::Entry::Vacant(entry) = self.token_ids.entry(token) {
8155            entry.insert(next_id);
8156            self.order.push(next_id);
8157        }
8158    }
8159
8160    #[cfg(test)]
8161    fn push(&mut self, token: String) {
8162        let next_id = self.token_ids.len();
8163        let token_id = *self.token_ids.entry(token).or_insert(next_id);
8164        self.order.push(token_id);
8165    }
8166
8167    #[cfg(test)]
8168    fn extend(&mut self, tokens: impl IntoIterator<Item = String>) {
8169        for token in tokens {
8170            self.push(token);
8171        }
8172    }
8173
8174    fn into_vec(self) -> Vec<String> {
8175        let mut tokens_by_id = (0..self.token_ids.len())
8176            .map(|_| None)
8177            .collect::<Vec<Option<String>>>();
8178        for (token, token_id) in self.token_ids {
8179            tokens_by_id[token_id] = Some(token);
8180        }
8181
8182        let mut remaining = vec![0_usize; tokens_by_id.len()];
8183        for token_id in &self.order {
8184            remaining[*token_id] += 1;
8185        }
8186
8187        self.order
8188            .into_iter()
8189            .map(|token_id| {
8190                remaining[token_id] -= 1;
8191                if remaining[token_id] == 0 {
8192                    tokens_by_id[token_id]
8193                        .take()
8194                        .expect("token sequence IDs must resolve")
8195                } else {
8196                    tokens_by_id[token_id]
8197                        .as_ref()
8198                        .expect("token sequence IDs must resolve")
8199                        .clone()
8200                }
8201            })
8202            .collect()
8203    }
8204}
8205
8206#[cfg(test)]
8207fn normalize_english_suffixes(token: &str) -> Vec<String> {
8208    if token.len() <= 4 || token.contains('_') || token.chars().any(|ch| ch.is_ascii_digit()) {
8209        return Vec::new();
8210    }
8211    if let Some(stem) = token.strip_suffix("ies")
8212        && stem.len() >= 2
8213    {
8214        return vec![format!("{stem}y")];
8215    }
8216    if let Some(stem) = token.strip_suffix("ing")
8217        && stem.len() >= 3
8218    {
8219        return suffix_stem_variants(trim_doubled_suffix_consonant(stem));
8220    }
8221    if let Some(stem) = token.strip_suffix("ed")
8222        && stem.len() >= 3
8223    {
8224        return suffix_stem_variants(trim_doubled_suffix_consonant(stem));
8225    }
8226    if let Some(stem) = token.strip_suffix('s')
8227        && stem.len() >= 3
8228        && !stem.ends_with('s')
8229    {
8230        return vec![stem.to_string()];
8231    }
8232    Vec::new()
8233}
8234
8235#[cfg(test)]
8236fn suffix_stem_variants(stem: &str) -> Vec<String> {
8237    let mut variants = vec![stem.to_string()];
8238    if matches!(stem.chars().last(), Some('c' | 'v' | 'z')) {
8239        variants.push(format!("{stem}e"));
8240    }
8241    variants
8242}
8243
8244fn english_suffix_parts(token: &str) -> [Option<(&str, &str)>; 2] {
8245    if token.len() <= 4 || token.contains('_') || token.chars().any(|ch| ch.is_ascii_digit()) {
8246        return [None, None];
8247    }
8248    if let Some(stem) = token.strip_suffix("ies")
8249        && stem.len() >= 2
8250    {
8251        return [Some((stem, "y")), None];
8252    }
8253    let stem = token
8254        .strip_suffix("ing")
8255        .or_else(|| token.strip_suffix("ed"));
8256    if let Some(stem) = stem.filter(|stem| stem.len() >= 3) {
8257        let stem = trim_doubled_suffix_consonant(stem);
8258        let tail = matches!(stem.chars().last(), Some('c' | 'v' | 'z')).then_some((stem, "e"));
8259        return [Some((stem, "")), tail];
8260    }
8261    if let Some(stem) = token.strip_suffix('s')
8262        && stem.len() >= 3
8263        && !stem.ends_with('s')
8264    {
8265        return [Some((stem, "")), None];
8266    }
8267    [None, None]
8268}
8269
8270fn is_core_search_stopword(token: &str) -> bool {
8271    matches!(
8272        token,
8273        "a" | "an"
8274            | "and"
8275            | "are"
8276            | "as"
8277            | "at"
8278            | "be"
8279            | "by"
8280            | "for"
8281            | "from"
8282            | "how"
8283            | "in"
8284            | "is"
8285            | "it"
8286            | "of"
8287            | "on"
8288            | "or"
8289            | "that"
8290            | "the"
8291            | "this"
8292            | "to"
8293            | "was"
8294            | "with"
8295    )
8296}
8297
8298fn trim_doubled_suffix_consonant(stem: &str) -> &str {
8299    let mut chars = stem.char_indices().rev();
8300    let Some((last_index, last)) = chars.next() else {
8301        return stem;
8302    };
8303    let Some((_, previous)) = chars.next() else {
8304        return stem;
8305    };
8306    if last == previous && is_ascii_consonant(last) {
8307        &stem[..last_index]
8308    } else {
8309        stem
8310    }
8311}
8312
8313fn is_ascii_consonant(ch: char) -> bool {
8314    ch.is_ascii_alphabetic() && !matches!(ch, 'a' | 'e' | 'i' | 'o' | 'u')
8315}
8316
8317#[cfg(test)]
8318mod raw_vector_math_tests;
8319
8320#[cfg(all(test, feature = "vector-search"))]
8321mod vector_metric_tests;
8322
8323// Final facade vector relevance is positive-only in [0, 1], higher is better,
8324// and is always computed with the projection's own distance metric:
8325// - cosine: positive cosine similarity. Nonpositive exact similarities cannot
8326//   contribute a vector hit (text may still match);
8327// - Euclidean: `1 / (1 + l2_distance)`. It is positive for every finite pair
8328//   and strictly decreasing in distance, so descending relevance is ascending
8329//   L2 distance and no candidate is dropped for its direction.
8330// Signed RaBitQ estimates and graph distances are candidate-ranking hints, not
8331// final scores. Schema-bound vector index queries expose raw distances instead.
8332/// One prepared query shared by a scoring phase. Keep legacy nonfinite behavior
8333/// at this private boundary; public projection distances validate finite inputs.
8334#[derive(Clone, Copy)]
8335struct VectorRelevanceQuery<'a> {
8336    query: &'a [f32],
8337    metric: hawdb_core::VectorDistance,
8338    scoring: SearchVectorScoring,
8339    prepared: Option<hawdb_core::vector::PreparedVectorQuery<'a>>,
8340}
8341
8342impl<'a> VectorRelevanceQuery<'a> {
8343    #[cfg(test)]
8344    fn new(query: &'a [f32], metric: hawdb_core::VectorDistance) -> Self {
8345        Self {
8346            query,
8347            metric,
8348            scoring: SearchVectorScoring::default(),
8349            prepared: (query.len() >= 16)
8350                .then(|| hawdb_core::vector::PreparedVectorQuery::new(query).ok())
8351                .flatten(),
8352        }
8353    }
8354
8355    fn with_work(
8356        query: &'a [f32],
8357        metric: hawdb_core::VectorDistance,
8358        mut checkpoint: impl FnMut() -> Result<()>,
8359    ) -> Result<Self> {
8360        if query.len() < 16 {
8361            return Ok(Self {
8362                query,
8363                metric,
8364                scoring: SearchVectorScoring::default(),
8365                prepared: None,
8366            });
8367        }
8368        let mut failure = None;
8369        let prepared = hawdb_core::vector::PreparedVectorQuery::with_work(query, || {
8370            checkpoint().map_err(|error| {
8371                failure = Some(error);
8372                hawdb_core::HawDBError::ProjectionBusy
8373            })
8374        });
8375        if let Some(error) = failure {
8376            return Err(error);
8377        }
8378        Ok(Self {
8379            query,
8380            metric,
8381            scoring: SearchVectorScoring::default(),
8382            prepared: prepared.ok(),
8383        })
8384    }
8385
8386    /// A query whose scoring phase has no candidates needs no prepared norm.
8387    #[cfg(feature = "vector-search")]
8388    fn unprepared(query: &'a [f32], metric: hawdb_core::VectorDistance) -> Self {
8389        Self {
8390            query,
8391            metric,
8392            scoring: SearchVectorScoring::default(),
8393            prepared: None,
8394        }
8395    }
8396
8397    fn with_scoring(mut self, scoring: SearchVectorScoring) -> Self {
8398        self.scoring = scoring;
8399        self
8400    }
8401
8402    /// Exact mathematical distance under this query's metric.
8403    #[cfg(feature = "vector-search")]
8404    fn distance_with_work(
8405        &self,
8406        embedding: &[f32],
8407        checkpoint: impl FnMut() -> Result<()>,
8408    ) -> Result<f64> {
8409        match &self.prepared {
8410            Some(prepared) => {
8411                prepared.distance_slices_with_work(self.metric, embedding, checkpoint)
8412            }
8413            None => self
8414                .metric
8415                .distance_slices_with_work(self.query, embedding, checkpoint),
8416        }
8417    }
8418
8419    /// Facade relevance in [0, 1]; `None` when the pair has no defined score.
8420    fn score(&self, embedding: &[f32]) -> Option<f64> {
8421        if self.scoring == SearchVectorScoring::LinearSquaredL2 {
8422            return self.scoring.ranking_score(self.query, embedding);
8423        }
8424        match self.metric {
8425            hawdb_core::VectorDistance::Cosine => {
8426                if let Some(prepared) = &self.prepared
8427                    && let Ok(score) = prepared.positive_cosine_similarity(embedding)
8428                {
8429                    return score;
8430                }
8431                scalar_cosine_similarity(self.query, embedding)
8432            }
8433            hawdb_core::VectorDistance::Euclidean => {
8434                if self.query.len() != embedding.len() || embedding.is_empty() {
8435                    return None;
8436                }
8437                let distance = match &self.prepared {
8438                    Some(prepared) => prepared.distance_slices_with_work(
8439                        hawdb_core::VectorDistance::Euclidean,
8440                        embedding,
8441                        || Ok(()),
8442                    ),
8443                    None => hawdb_core::VectorDistance::Euclidean.distance_slices_with_work(
8444                        self.query,
8445                        embedding,
8446                        || Ok(()),
8447                    ),
8448                }
8449                .ok()?;
8450                euclidean_relevance(distance)
8451            }
8452        }
8453    }
8454}
8455
8456/// Maps a finite L2 distance onto the facade's higher-is-better (0, 1] scale.
8457fn euclidean_relevance(distance: f64) -> Option<f64> {
8458    (distance.is_finite() && distance >= 0.0).then(|| 1.0 / (1.0 + distance))
8459}
8460
8461#[cfg(test)]
8462fn cosine_similarity(left: &[f32], right: &[f32]) -> Option<f64> {
8463    VectorRelevanceQuery::new(left, hawdb_core::VectorDistance::Cosine).score(right)
8464}
8465
8466fn scalar_cosine_similarity(left: &[f32], right: &[f32]) -> Option<f64> {
8467    if left.len() != right.len() || left.is_empty() {
8468        return None;
8469    }
8470    let dot = dot_product(left, right)?;
8471    let left_norm_squared = dot_product(left, left)?;
8472    let right_norm_squared = dot_product(right, right)?;
8473    if left_norm_squared == 0.0 || right_norm_squared == 0.0 {
8474        return None;
8475    }
8476    Some((dot / (left_norm_squared.sqrt() * right_norm_squared.sqrt())).clamp(0.0, 1.0))
8477}
8478
8479fn dot_product(left: &[f32], right: &[f32]) -> Option<f64> {
8480    if left.len() != right.len() || left.is_empty() {
8481        return None;
8482    }
8483
8484    // HawDB owns this exact raw-vector score. It is independent from RaBitQ's
8485    // candidate index, persistence, and branch state. Keep a single scalar
8486    // implementation here so a future platform-SIMD kernel can be added without
8487    // changing the `Option<f64>` search contract.
8488    Some(left.iter().zip(right).fold(0.0, |sum, (left, right)| {
8489        sum + f64::from(*left) * f64::from(*right)
8490    }))
8491}
8492
8493fn decode_embedding(input: &str) -> Result<Option<Vec<f32>>> {
8494    if input.is_empty() {
8495        return Ok(None);
8496    }
8497    input
8498        .split(',')
8499        .map(|raw| {
8500            raw.parse::<f32>()
8501                .map_err(|_| HawDBError::Storage(format!("invalid embedding value: {raw}")))
8502        })
8503        .collect::<Result<Vec<_>>>()
8504        .map(Some)
8505}
8506
8507fn encode_metadata(metadata: &BTreeMap<String, String>) -> String {
8508    metadata
8509        .iter()
8510        .map(|(key, value)| format!("{}={}", encode_string(key), encode_string(value)))
8511        .collect::<Vec<_>>()
8512        .join(";")
8513}
8514
8515/// The metadata keys a candidate filter reads, hex-encoded as stored, so a
8516/// record's other pairs are skipped without being decoded (#1613).
8517#[derive(Debug, Clone, Default)]
8518pub(crate) struct MetadataKeys(BTreeSet<String>);
8519
8520impl MetadataKeys {
8521    pub(crate) fn contains(&self, encoded_key: &str) -> bool {
8522        self.0.contains(encoded_key)
8523    }
8524
8525    /// Every key `predicates` read: a predicate reads the metadata entry of
8526    /// its field's name (see [`search_header_field_values`]).
8527    pub(crate) fn for_predicates(predicates: &SearchPredicateSet) -> Self {
8528        Self::for_predicate_iter(predicates.predicates())
8529    }
8530
8531    pub(crate) fn for_predicate_iter<'a>(
8532        predicates: impl IntoIterator<Item = &'a SearchPredicate>,
8533    ) -> Self {
8534        Self(
8535            predicates
8536                .into_iter()
8537                .map(|predicate| encode_string(predicate.field().name()))
8538                .collect(),
8539        )
8540    }
8541}
8542
8543/// [`decode_metadata`] restricted to `keys`. Every pair must still be a
8544/// `key=value` pair; pairs with other keys are not hex-decoded.
8545pub(crate) fn decode_metadata_keys(
8546    input: &str,
8547    keys: Option<&MetadataKeys>,
8548) -> Result<BTreeMap<String, String>> {
8549    let Some(keys) = keys else {
8550        return decode_metadata(input);
8551    };
8552    let mut metadata = BTreeMap::new();
8553    if input.is_empty() {
8554        return Ok(metadata);
8555    }
8556    for pair in input.split(';') {
8557        let Some((key, value)) = pair.split_once('=') else {
8558            return Err(HawDBError::Storage(format!(
8559                "invalid metadata pair: {pair}"
8560            )));
8561        };
8562        if keys.0.contains(key) {
8563            metadata.insert(decode_string(key)?, decode_string(value)?);
8564        }
8565    }
8566    Ok(metadata)
8567}
8568
8569fn decode_metadata(input: &str) -> Result<BTreeMap<String, String>> {
8570    let mut metadata = BTreeMap::new();
8571    if input.is_empty() {
8572        return Ok(metadata);
8573    }
8574    for pair in input.split(';') {
8575        let Some((key, value)) = pair.split_once('=') else {
8576            return Err(HawDBError::Storage(format!(
8577                "invalid metadata pair: {pair}"
8578            )));
8579        };
8580        metadata.insert(decode_string(key)?, decode_string(value)?);
8581    }
8582    Ok(metadata)
8583}
8584
8585fn decode_search_document_line(line: &str) -> Result<SearchDocument> {
8586    decode_search_document_line_with(line, true)
8587}
8588
8589/// Decodes one document line; without `embeddings` its decimal-text vector
8590/// is left unparsed and the document carries none (#1917 text-only hits).
8591fn decode_search_document_line_with(line: &str, embeddings: bool) -> Result<SearchDocument> {
8592    let line = line.strip_suffix('\n').unwrap_or(line);
8593    let fields = line.split('\t').collect::<Vec<_>>();
8594    match fields.as_slice() {
8595        ["doc", raw_id, raw_title, raw_content, raw_embedding, raw_metadata] => {
8596            Ok(SearchDocument {
8597                id: decode_string(raw_id)?,
8598                title: decode_string(raw_title)?,
8599                content: decode_string(raw_content)?,
8600                embedding: if embeddings {
8601                    decode_embedding(raw_embedding)?
8602                } else {
8603                    None
8604                },
8605                metadata: decode_metadata(raw_metadata)?,
8606            })
8607        }
8608        _ => Err(HawDBError::Storage(format!(
8609            "invalid search document line: {line}"
8610        ))),
8611    }
8612}
8613
8614fn write_search_segment_payloads<T>(
8615    path: &Path,
8616    file_name: &str,
8617    documents: &impl DocumentView,
8618    descriptor: &mut SearchSegmentDescriptor,
8619    finish: impl FnOnce(&mut File) -> Result<T>,
8620) -> Result<T> {
8621    let artifact_path = path.join(file_name);
8622    let tmp_path = artifact_path.with_extension("hawdb.tmp");
8623    let mut offset = 0u64;
8624    let reference;
8625    {
8626        let mut file = fs::OpenOptions::new()
8627            .read(true)
8628            .write(true)
8629            .create(true)
8630            .truncate(true)
8631            .open(&tmp_path)?;
8632        for segment in &mut descriptor.segments {
8633            let mut body = String::from("HAWDB_SEARCH_SEGMENT_V1\n");
8634            for document in documents
8635                .range_documents(&segment.first_document_id, &segment.last_document_id)
8636                .map(|(_, document)| document)
8637            {
8638                body.push_str(&encode_search_document_line(document));
8639            }
8640            let payload = encode_search_snapshot_text(&body)?;
8641            let length = u64::try_from(payload.len()).map_err(|_| {
8642                HawDBError::Storage(format!(
8643                    "search segment {} payload exceeds the supported range length",
8644                    segment.segment_id
8645                ))
8646            })?;
8647            segment.payload_range = Some(SearchSegmentPayloadRange {
8648                artifact_id: SEARCH_SEGMENT_PAYLOAD_ARTIFACT_ID,
8649                offset,
8650                length,
8651                checksum: checksum_bytes(&payload),
8652            });
8653            file.write_all(&payload)?;
8654            offset = offset.checked_add(length).ok_or_else(|| {
8655                HawDBError::Storage("search segment payload artifact length overflow".to_string())
8656            })?;
8657        }
8658        file.sync_all()?;
8659        reference = finish(&mut file)?;
8660    }
8661    durable_replace_file(&tmp_path, &artifact_path)?;
8662    Ok(reference)
8663}
8664
8665fn write_search_segment_descriptor(
8666    path: &Path,
8667    descriptor: &SearchSegmentDescriptor,
8668) -> Result<()> {
8669    write_search_segment_descriptor_bounded(path, descriptor, u64::MAX).map(|_| ())
8670}
8671
8672fn write_search_segment_descriptor_bounded(
8673    path: &Path,
8674    descriptor: &SearchSegmentDescriptor,
8675    max_bytes: u64,
8676) -> Result<u64> {
8677    write_search_segment_descriptor_output(
8678        path,
8679        SEARCH_SEGMENT_DESCRIPTOR_FILE,
8680        descriptor,
8681        max_bytes,
8682        |_| Ok(()),
8683    )
8684    .map(|(length, ())| length)
8685}
8686
8687fn write_search_segment_descriptor_output<T>(
8688    path: &Path,
8689    file_name: &str,
8690    descriptor: &SearchSegmentDescriptor,
8691    max_bytes: u64,
8692    finish: impl FnOnce(&mut File) -> Result<T>,
8693) -> Result<(u64, T)> {
8694    let encoding = document_encoding::DescriptorEncoding::new(descriptor, max_bytes)?;
8695    let descriptor_path = path.join(file_name);
8696    let tmp_path = descriptor_path.with_extension("hawdb.tmp");
8697    let reference;
8698    {
8699        let mut file = std::io::BufWriter::new(
8700            fs::OpenOptions::new()
8701                .read(true)
8702                .write(true)
8703                .create(true)
8704                .truncate(true)
8705                .open(&tmp_path)?,
8706        );
8707        encoding.write_to(&mut file)?;
8708        file.flush()?;
8709        file.get_ref().sync_all()?;
8710        reference = finish(file.get_mut())?;
8711    }
8712    durable_replace_file(&tmp_path, &descriptor_path)?;
8713    Ok((encoding.len() as u64, reference))
8714}
8715
8716fn read_search_segment_descriptor(path: &Path) -> Result<Option<SearchSegmentDescriptor>> {
8717    let descriptor_path = path.join(SEARCH_SEGMENT_DESCRIPTOR_FILE);
8718    if !fs::try_exists(&descriptor_path)? {
8719        return Ok(None);
8720    }
8721    let text = fs::read_to_string(&descriptor_path)?;
8722    decode_search_segment_descriptor_text(&text).map(Some)
8723}
8724
8725fn read_captured_search_segment_descriptor(
8726    publication: &out_of_core::SearchProjectionPublishLease,
8727) -> Result<Option<SearchSegmentDescriptor>> {
8728    let mut file = match publication.open_captured_child(SEARCH_SEGMENT_DESCRIPTOR_FILE) {
8729        Ok(file) => file,
8730        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
8731        Err(error) => return Err(error.into()),
8732    };
8733    let mut text = String::new();
8734    file.read_to_string(&mut text)?;
8735    decode_search_segment_descriptor_text(&text).map(Some)
8736}
8737
8738#[cfg(test)]
8739fn encode_search_segment_descriptor_body(descriptor: &SearchSegmentDescriptor) -> String {
8740    let mut body = String::new();
8741    body.push_str(if descriptor.omits_value_summaries() {
8742        "HAWDB_SEARCH_SEGMENTS_V4\n"
8743    } else {
8744        "HAWDB_SEARCH_SEGMENTS_V3\n"
8745    });
8746    body.push_str(&format!(
8747        "target_documents\t{}\n",
8748        descriptor.target_documents
8749    ));
8750    body.push_str(&format!("document_count\t{}\n", descriptor.document_count));
8751    for segment in &descriptor.segments {
8752        let payload_range = segment.payload_range.unwrap_or(SearchSegmentPayloadRange {
8753            artifact_id: 0,
8754            offset: 0,
8755            length: 0,
8756            checksum: 0,
8757        });
8758        body.push_str(&format!(
8759            "segment\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n",
8760            segment.segment_id,
8761            encode_string(&segment.first_document_id),
8762            encode_string(&segment.last_document_id),
8763            segment.document_count,
8764            payload_range.artifact_id,
8765            payload_range.offset,
8766            payload_range.length,
8767            payload_range.checksum,
8768        ));
8769        for (field, summary) in &segment.metadata {
8770            let (numeric_min, numeric_max) = encode_search_numeric_range(summary.numeric_range);
8771            let (timestamp_min, timestamp_max) =
8772                encode_search_timestamp_range(summary.timestamp_range);
8773            body.push_str(&format!(
8774                "field\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n",
8775                encode_string(field),
8776                summary.present_count,
8777                if summary.values_omitted {
8778                    SEARCH_SEGMENT_OMITTED_VALUES.to_string()
8779                } else {
8780                    encode_segment_values(&summary.values)
8781                },
8782                numeric_min,
8783                numeric_max,
8784                timestamp_min,
8785                timestamp_max
8786            ));
8787        }
8788    }
8789    body
8790}
8791
8792fn decode_search_segment_descriptor_text(text: &str) -> Result<SearchSegmentDescriptor> {
8793    decode_search_segment_descriptor_with_context(text, None, false)
8794}
8795
8796/// Decode a segment descriptor. With `bound_value_summaries`, a value set
8797/// above the segment value-summary bounds is omitted while it is decoded, so
8798/// a descriptor written before #1746 does not keep document bodies resident.
8799fn decode_search_segment_descriptor_with_context(
8800    text: &str,
8801    task: Option<&hawdb_core::RuntimeTaskContext>,
8802    bound_value_summaries: bool,
8803) -> Result<SearchSegmentDescriptor> {
8804    let (body, checksum) = split_checksum(text)?;
8805    let mut hasher = hawdb_integrity::Crc32cHasher::new();
8806    for chunk in body.as_bytes().chunks(8192) {
8807        task.map_or(Ok(()), build_control::checkpoint)?;
8808        hasher.update(chunk);
8809    }
8810    let actual = hasher.finish();
8811    if checksum != actual {
8812        return Err(HawDBError::Storage(format!(
8813            "search segment descriptor checksum mismatch: expected {checksum}, got {actual}"
8814        )));
8815    }
8816
8817    let mut target_documents = None;
8818    let mut document_count = None;
8819    let mut segments = Vec::new();
8820    let mut current_segment = None::<SearchSegmentDescriptorEntry>;
8821    // Only a V4 descriptor may mark a value set as omitted.
8822    let mut omitted_values_allowed = false;
8823
8824    for line in body.lines() {
8825        task.map_or(Ok(()), build_control::checkpoint)?;
8826        if line == "HAWDB_SEARCH_SEGMENTS_V1"
8827            || line == "HAWDB_SEARCH_SEGMENTS_V2"
8828            || line == "HAWDB_SEARCH_SEGMENTS_V3"
8829        {
8830            continue;
8831        }
8832        if line == SEARCH_SEGMENT_DESCRIPTOR_V4_HEADER {
8833            omitted_values_allowed = true;
8834            continue;
8835        }
8836        // The longest descriptor production has nine fields. Keep the field
8837        // table on the stack: rejected input may contain a tab per byte, and
8838        // collecting those borrowed slices would amplify it into a large Vec.
8839        let mut fields = [""; 9];
8840        let mut count = 0;
8841        for field in line.split('\t') {
8842            let Some(slot) = fields.get_mut(count) else {
8843                return Err(HawDBError::Storage(format!(
8844                    "invalid search segment descriptor line: {line}"
8845                )));
8846            };
8847            *slot = field;
8848            count += 1;
8849        }
8850        match &fields[..count] {
8851            ["target_documents", raw] => {
8852                target_documents = Some(parse_usize(raw, "search segment target documents")?);
8853            }
8854            ["document_count", raw] => {
8855                document_count = Some(parse_usize(raw, "search segment document count")?);
8856            }
8857            ["segment", raw_first, raw_last, raw_count] => {
8858                if let Some(segment) = current_segment.take() {
8859                    segments.push(segment);
8860                }
8861                current_segment = Some(SearchSegmentDescriptorEntry {
8862                    segment_id: segments.len() as u64,
8863                    first_document_id: decode_string(raw_first)?,
8864                    last_document_id: decode_string(raw_last)?,
8865                    document_count: parse_usize(raw_count, "search segment document count")?,
8866                    payload_range: None,
8867                    metadata: BTreeMap::new(),
8868                });
8869            }
8870            ["segment", raw_segment_id, raw_first, raw_last, raw_count, raw_artifact_id, raw_offset, raw_length, raw_checksum] =>
8871            {
8872                if let Some(segment) = current_segment.take() {
8873                    segments.push(segment);
8874                }
8875                let length = parse_u64(raw_length, "search segment payload length")?;
8876                current_segment = Some(SearchSegmentDescriptorEntry {
8877                    segment_id: parse_u64(raw_segment_id, "search segment id")?,
8878                    first_document_id: decode_string(raw_first)?,
8879                    last_document_id: decode_string(raw_last)?,
8880                    document_count: parse_usize(raw_count, "search segment document count")?,
8881                    payload_range: (length > 0).then_some(SearchSegmentPayloadRange {
8882                        artifact_id: parse_u64(
8883                            raw_artifact_id,
8884                            "search segment payload artifact id",
8885                        )?,
8886                        offset: parse_u64(raw_offset, "search segment payload offset")?,
8887                        length,
8888                        checksum: parse_u64(raw_checksum, "search segment payload checksum")?,
8889                    }),
8890                    metadata: BTreeMap::new(),
8891                });
8892            }
8893            ["field", raw_field, raw_present_count, raw_values, ranges @ ..]
8894                if matches!(ranges.len(), 0 | 2 | 4) =>
8895            {
8896                let Some(segment) = current_segment.as_mut() else {
8897                    return Err(HawDBError::Storage(
8898                        "search segment descriptor field appeared before segment".to_string(),
8899                    ));
8900                };
8901                let (values, values_omitted) = decode_segment_value_summary(
8902                    raw_values,
8903                    omitted_values_allowed,
8904                    bound_value_summaries,
8905                )?;
8906                segment.metadata.insert(
8907                    decode_string(raw_field)?,
8908                    SearchSegmentFieldSummary {
8909                        present_count: parse_usize(
8910                            raw_present_count,
8911                            "search segment field present count",
8912                        )?,
8913                        values,
8914                        values_omitted,
8915                        numeric_range: match ranges {
8916                            [raw_numeric_min, raw_numeric_max, ..] => {
8917                                decode_search_numeric_range(raw_numeric_min, raw_numeric_max)?
8918                            }
8919                            _ => None,
8920                        },
8921                        timestamp_range: match ranges {
8922                            [_, _, raw_timestamp_min, raw_timestamp_max] => {
8923                                decode_search_timestamp_range(raw_timestamp_min, raw_timestamp_max)?
8924                            }
8925                            _ => None,
8926                        },
8927                    },
8928                );
8929            }
8930            [""] => {}
8931            _ => {
8932                return Err(HawDBError::Storage(format!(
8933                    "invalid search segment descriptor line: {line}"
8934                )));
8935            }
8936        }
8937    }
8938    if let Some(segment) = current_segment.take() {
8939        segments.push(segment);
8940    }
8941    validate_search_segment_payload_ranges(&segments)?;
8942
8943    Ok(SearchSegmentDescriptor {
8944        target_documents: target_documents.ok_or_else(|| {
8945            HawDBError::Storage("search segment descriptor missing target_documents".to_string())
8946        })?,
8947        document_count: document_count.ok_or_else(|| {
8948            HawDBError::Storage("search segment descriptor missing document_count".to_string())
8949        })?,
8950        segments,
8951    })
8952}
8953
8954fn validate_search_segment_payload_ranges(segments: &[SearchSegmentDescriptorEntry]) -> Result<()> {
8955    let physical_range_count = segments
8956        .iter()
8957        .filter(|segment| segment.payload_range.is_some())
8958        .count();
8959    if physical_range_count != 0 && physical_range_count != segments.len() {
8960        return Err(HawDBError::Storage(
8961            "search segment descriptor has incomplete physical payload ranges".to_string(),
8962        ));
8963    }
8964    let mut previous_end = 0u64;
8965    for (expected_id, segment) in segments.iter().enumerate() {
8966        if segment.segment_id != expected_id as u64 {
8967            return Err(HawDBError::Storage(format!(
8968                "search segment descriptor expected segment id {expected_id}, got {}",
8969                segment.segment_id
8970            )));
8971        }
8972        let Some(range) = segment.payload_range else {
8973            continue;
8974        };
8975        if range.artifact_id != SEARCH_SEGMENT_PAYLOAD_ARTIFACT_ID {
8976            return Err(HawDBError::Storage(format!(
8977                "search segment {} references unsupported payload artifact {}",
8978                segment.segment_id, range.artifact_id
8979            )));
8980        }
8981        if range.offset < previous_end {
8982            return Err(HawDBError::Storage(format!(
8983                "search segment {} payload range overlaps the previous segment",
8984                segment.segment_id
8985            )));
8986        }
8987        previous_end = range.offset.checked_add(range.length).ok_or_else(|| {
8988            HawDBError::Storage(format!(
8989                "search segment {} payload range overflows",
8990                segment.segment_id
8991            ))
8992        })?;
8993    }
8994    Ok(())
8995}
8996
8997fn decode_search_segment_documents(payload: &[u8]) -> Result<Vec<SearchDocument>> {
8998    decode_search_segment_documents_bounded(payload, u64::MAX)
8999}
9000
9001fn decode_search_segment_documents_bounded(
9002    payload: &[u8],
9003    max_uncompressed_bytes: u64,
9004) -> Result<Vec<SearchDocument>> {
9005    let text = decode_search_snapshot_text_bounded(payload, max_uncompressed_bytes)?;
9006    let mut documents = Vec::new();
9007    for line in text.lines() {
9008        if line == "HAWDB_SEARCH_SEGMENT_V1" {
9009            continue;
9010        }
9011        let fields = line.split('\t').collect::<Vec<_>>();
9012        match fields.as_slice() {
9013            ["doc", ..] => documents.push(decode_search_document_line(line)?),
9014            [""] => {}
9015            _ => {
9016                return Err(HawDBError::Storage(format!(
9017                    "invalid search segment payload line: {line}"
9018                )));
9019            }
9020        }
9021    }
9022    Ok(documents)
9023}
9024
9025fn validate_search_segment_documents(
9026    segment: &SearchSegmentDescriptorEntry,
9027    documents: &[SearchDocument],
9028) -> Result<()> {
9029    if documents.len() != segment.document_count {
9030        return Err(HawDBError::Storage(format!(
9031            "search segment {} decoded {} documents, expected {}",
9032            segment.segment_id,
9033            documents.len(),
9034            segment.document_count
9035        )));
9036    }
9037    let first = documents.first().map(|document| document.id.as_str());
9038    let last = documents.last().map(|document| document.id.as_str());
9039    if first != Some(segment.first_document_id.as_str())
9040        || last != Some(segment.last_document_id.as_str())
9041    {
9042        return Err(HawDBError::Storage(format!(
9043            "search segment {} document bounds do not match its descriptor",
9044            segment.segment_id
9045        )));
9046    }
9047    if documents.windows(2).any(|pair| pair[0].id >= pair[1].id) {
9048        return Err(HawDBError::Storage(format!(
9049            "search segment {} documents are not strictly ordered",
9050            segment.segment_id
9051        )));
9052    }
9053    Ok(())
9054}
9055
9056#[cfg(test)]
9057fn encode_segment_values(values: &BTreeSet<String>) -> String {
9058    values
9059        .iter()
9060        .map(|value| encode_string(value))
9061        .collect::<Vec<_>>()
9062        .join(",")
9063}
9064
9065fn decode_segment_values(input: &str) -> Result<BTreeSet<String>> {
9066    if input.is_empty() {
9067        return Ok(BTreeSet::new());
9068    }
9069    input.split(',').map(decode_string).collect()
9070}
9071
9072/// The value column of a V4 descriptor field whose value set is omitted.
9073const SEARCH_SEGMENT_OMITTED_VALUES: &str = "~";
9074
9075/// Header of a descriptor that may contain omitted value sets (#1746).
9076/// Readers before #1746 reject it, so the selector that references it
9077/// requires reader version 4 (`docs/SEARCH_PROJECTION_MANIFEST_VERSION.md`).
9078const SEARCH_SEGMENT_DESCRIPTOR_V4_HEADER: &str = "HAWDB_SEARCH_SEGMENTS_V4";
9079
9080fn decode_segment_value_summary(
9081    input: &str,
9082    omitted_values_allowed: bool,
9083    bound_value_summaries: bool,
9084) -> Result<(BTreeSet<String>, bool)> {
9085    if input == SEARCH_SEGMENT_OMITTED_VALUES {
9086        if !omitted_values_allowed {
9087            return Err(HawDBError::Storage(
9088                "search segment descriptor omits a value summary before V4".to_string(),
9089            ));
9090        }
9091        return Ok((BTreeSet::new(), true));
9092    }
9093    if bound_value_summaries && segment_values_exceed_summary_bounds(input) {
9094        // Each hex pair is one value byte. Validate the column without
9095        // materializing the values it would have retained.
9096        for value in input.split(',') {
9097            if value.len() % 2 != 0 || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
9098                return Err(HawDBError::Storage(format!(
9099                    "invalid search segment descriptor hex value of {} bytes",
9100                    value.len()
9101                )));
9102            }
9103        }
9104        return Ok((BTreeSet::new(), true));
9105    }
9106    Ok((decode_segment_values(input)?, false))
9107}
9108
9109/// Whether a hex value column exceeds the segment value-summary bounds. Each
9110/// encoded value has two hex digits per byte.
9111fn segment_values_exceed_summary_bounds(input: &str) -> bool {
9112    if input.is_empty() {
9113        return false;
9114    }
9115    let mut total = 0usize;
9116    for value in input.split(',') {
9117        let bytes = value.len() / 2;
9118        total = total.saturating_add(bytes);
9119        if bytes > SEARCH_SEGMENT_VALUE_SUMMARY_MAX_VALUE_BYTES
9120            || total > SEARCH_SEGMENT_VALUE_SUMMARY_MAX_FIELD_BYTES
9121        {
9122            return true;
9123        }
9124    }
9125    false
9126}
9127
9128#[cfg(test)]
9129fn encode_search_numeric_range(range: Option<SearchNumericRange>) -> (String, String) {
9130    range
9131        .map(|range| (range.min.to_string(), range.max.to_string()))
9132        .unwrap_or_else(|| (String::new(), String::new()))
9133}
9134
9135#[cfg(test)]
9136fn encode_search_timestamp_range(range: Option<SearchTimestampRange>) -> (String, String) {
9137    range
9138        .map(|range| {
9139            (
9140                range.min_epoch_millis.to_string(),
9141                range.max_epoch_millis.to_string(),
9142            )
9143        })
9144        .unwrap_or_else(|| (String::new(), String::new()))
9145}
9146
9147fn decode_search_numeric_range(raw_min: &str, raw_max: &str) -> Result<Option<SearchNumericRange>> {
9148    match (raw_min.is_empty(), raw_max.is_empty()) {
9149        (true, true) => Ok(None),
9150        (false, false) => {
9151            let min = parse_finite_f64(raw_min, "search segment field numeric min")?;
9152            let max = parse_finite_f64(raw_max, "search segment field numeric max")?;
9153            if min > max {
9154                return Err(HawDBError::Storage(
9155                    "search segment field numeric min is greater than max".to_string(),
9156                ));
9157            }
9158            Ok(Some(SearchNumericRange { min, max }))
9159        }
9160        _ => Err(HawDBError::Storage(
9161            "search segment field numeric range is incomplete".to_string(),
9162        )),
9163    }
9164}
9165
9166fn decode_search_timestamp_range(
9167    raw_min: &str,
9168    raw_max: &str,
9169) -> Result<Option<SearchTimestampRange>> {
9170    match (raw_min.is_empty(), raw_max.is_empty()) {
9171        (true, true) => Ok(None),
9172        (false, false) => {
9173            let min_epoch_millis =
9174                parse_i64(raw_min, "search segment field timestamp min epoch millis")?;
9175            let max_epoch_millis =
9176                parse_i64(raw_max, "search segment field timestamp max epoch millis")?;
9177            if min_epoch_millis > max_epoch_millis {
9178                return Err(HawDBError::Storage(
9179                    "search segment field timestamp min is greater than max".to_string(),
9180                ));
9181            }
9182            Ok(Some(SearchTimestampRange {
9183                min_epoch_millis,
9184                max_epoch_millis,
9185            }))
9186        }
9187        _ => Err(HawDBError::Storage(
9188            "search segment field timestamp range is incomplete".to_string(),
9189        )),
9190    }
9191}
9192
9193fn parse_finite_f64(raw: &str, name: &str) -> Result<f64> {
9194    let value = raw
9195        .parse::<f64>()
9196        .map_err(|_| HawDBError::Storage(format!("invalid {name}: {raw}")))?;
9197    if value.is_finite() {
9198        Ok(value)
9199    } else {
9200        Err(HawDBError::Storage(format!("invalid {name}: {raw}")))
9201    }
9202}
9203
9204fn encode_string(input: &str) -> String {
9205    input
9206        .as_bytes()
9207        .iter()
9208        .map(|byte| format!("{byte:02x}"))
9209        .collect()
9210}
9211
9212fn decode_string(input: &str) -> Result<String> {
9213    if !input.len().is_multiple_of(2) {
9214        return Err(HawDBError::Storage(format!(
9215            "invalid hex string length: {}",
9216            input.len()
9217        )));
9218    }
9219    let mut bytes = Vec::with_capacity(input.len() / 2);
9220    for offset in (0..input.len()).step_by(2) {
9221        let byte = input
9222            .get(offset..offset + 2)
9223            .and_then(|pair| u8::from_str_radix(pair, 16).ok())
9224            .ok_or_else(|| HawDBError::Storage(format!("invalid hex string at byte {offset}")))?;
9225        bytes.push(byte);
9226    }
9227    String::from_utf8(bytes).map_err(|error| HawDBError::Storage(error.to_string()))
9228}
9229
9230fn split_checksum(text: &str) -> Result<(&str, u64)> {
9231    let Some((body, footer)) = text.rsplit_once("checksum\t") else {
9232        return Err(HawDBError::Storage(
9233            "search projection missing checksum footer".to_string(),
9234        ));
9235    };
9236    let checksum = parse_u64(footer.trim(), "search projection checksum")?;
9237    Ok((body, checksum))
9238}
9239
9240fn encode_search_snapshot_text(text: &str) -> Result<Vec<u8>> {
9241    let compressed =
9242        hawdb_storage::compression::encode_all(text.as_bytes(), SEARCH_COMPRESSION_LEVEL).map_err(
9243            |error| {
9244                HawDBError::or_stop(&error, || {
9245                    HawDBError::Storage(format!("zstd compression failed: {error}"))
9246                })
9247            },
9248        )?;
9249    let compressed_checksum = checksum_bytes(&compressed);
9250    let uncompressed_checksum = checksum_bytes(text.as_bytes());
9251    let header = search_snapshot_compression_header(
9252        uncompressed_checksum,
9253        compressed_checksum,
9254        text.len(),
9255        compressed.len(),
9256    );
9257    let mut encoded = header.into_bytes();
9258    encoded.extend_from_slice(&compressed);
9259    Ok(encoded)
9260}
9261
9262fn search_snapshot_compression_header(
9263    uncompressed_checksum: u64,
9264    compressed_checksum: u64,
9265    uncompressed_len: usize,
9266    compressed_len: usize,
9267) -> String {
9268    format!(
9269        "{SEARCH_COMPRESSION_HEADER}\ncodec\tzstd\nuncompressed_checksum\t{uncompressed_checksum}\ncompressed_checksum\t{compressed_checksum}\nuncompressed_len\t{}\ncompressed_len\t{}\n\n",
9270        uncompressed_len,
9271        compressed_len
9272    )
9273}
9274
9275fn read_search_snapshot_text(path: &Path) -> Result<String> {
9276    let bytes = fs::read(path)?;
9277    decode_search_snapshot_envelope(&bytes)
9278}
9279
9280fn decode_search_snapshot_envelope(bytes: &[u8]) -> Result<String> {
9281    if !bytes.starts_with(SEARCH_COMPRESSION_HEADER.as_bytes()) {
9282        return Err(HawDBError::Storage(
9283            "search projection is missing the V1 compressed envelope".to_string(),
9284        ));
9285    }
9286    decode_search_snapshot_text(bytes)
9287}
9288
9289fn decode_search_snapshot_text(bytes: &[u8]) -> Result<String> {
9290    decode_search_snapshot_text_bounded(bytes, u64::MAX)
9291}
9292
9293struct SnapshotHeader {
9294    compressed_len: Option<usize>,
9295    compressed_checksum: Option<u64>,
9296    uncompressed_len: Option<usize>,
9297    uncompressed_checksum: Option<u64>,
9298}
9299
9300fn parse_snapshot_header(header: &str) -> Result<SnapshotHeader> {
9301    let mut codec = None;
9302    let mut compressed_checksum = None;
9303    let mut uncompressed_checksum = None;
9304    let mut compressed_len = None;
9305    let mut uncompressed_len = None;
9306    let mut seen_fields = BTreeSet::new();
9307    for line in header.lines() {
9308        if line == SEARCH_COMPRESSION_HEADER {
9309            continue;
9310        }
9311        let fields = line.split('\t').collect::<Vec<_>>();
9312        if !seen_fields.insert(fields[0]) {
9313            return Err(HawDBError::Storage(format!(
9314                "search projection compressed envelope has duplicate field: {}",
9315                fields[0]
9316            )));
9317        }
9318        match fields.as_slice() {
9319            ["codec", value] => codec = Some(*value),
9320            ["compressed_checksum", value] => {
9321                compressed_checksum = Some(parse_u64(value, "compressed checksum")?);
9322            }
9323            ["uncompressed_checksum", value] => {
9324                uncompressed_checksum = Some(parse_u64(value, "uncompressed checksum")?);
9325            }
9326            ["compressed_len", value] => {
9327                compressed_len = Some(parse_usize(value, "compressed length")?);
9328            }
9329            ["uncompressed_len", value] => {
9330                uncompressed_len = Some(parse_usize(value, "uncompressed length")?);
9331            }
9332            _ => {
9333                return Err(HawDBError::Storage(format!(
9334                    "search projection compressed envelope has invalid header line: {line}"
9335                )));
9336            }
9337        }
9338    }
9339    if codec != Some("zstd") {
9340        return Err(HawDBError::Storage(
9341            "search projection compressed envelope uses unsupported codec".to_string(),
9342        ));
9343    }
9344    Ok(SnapshotHeader {
9345        compressed_len,
9346        compressed_checksum,
9347        uncompressed_len,
9348        uncompressed_checksum,
9349    })
9350}
9351
9352fn decode_search_snapshot_text_bounded(
9353    bytes: &[u8],
9354    max_uncompressed_bytes: u64,
9355) -> Result<String> {
9356    decode_search_snapshot_text_bounded_with(bytes, max_uncompressed_bytes, |payload, expected| {
9357        let decoder =
9358            hawdb_storage::compression::Decoder::new(Cursor::new(payload)).map_err(|error| {
9359                HawDBError::or_stop(&error, || {
9360                    HawDBError::Storage(format!(
9361                        "search projection zstd decompression failed: {error}"
9362                    ))
9363                })
9364            })?;
9365        read_search_snapshot_decoder(decoder, expected)
9366    })
9367}
9368
9369fn decode_search_snapshot_text_admitted(
9370    bytes: &[u8],
9371    max_uncompressed_bytes: u64,
9372    memory: &hawdb_executor::QueryMemoryAccount,
9373    task: &RuntimeTaskContext,
9374) -> Result<String> {
9375    decode_search_snapshot_text_bounded_with(bytes, max_uncompressed_bytes, |payload, expected| {
9376        let decoder =
9377            build_memory::decoder::Decoder::with_account(Cursor::new(payload), memory, task)?;
9378        read_search_snapshot_decoder(decoder, expected)
9379    })
9380}
9381
9382fn decode_search_snapshot_text_bounded_with(
9383    bytes: &[u8],
9384    max_uncompressed_bytes: u64,
9385    decode: impl FnOnce(&[u8], usize) -> Result<Vec<u8>>,
9386) -> Result<String> {
9387    let Some(header_end) = bytes.windows(2).position(|window| window == b"\n\n") else {
9388        return Err(HawDBError::Storage(
9389            "search projection compressed envelope missing header terminator".to_string(),
9390        ));
9391    };
9392    let header = std::str::from_utf8(&bytes[..header_end]).map_err(|error| {
9393        HawDBError::or_stop(&error, || {
9394            HawDBError::Storage(format!(
9395                "search projection compressed envelope header is invalid: {error}"
9396            ))
9397        })
9398    })?;
9399    let payload = &bytes[header_end + 2..];
9400    let SnapshotHeader {
9401        compressed_len,
9402        compressed_checksum,
9403        uncompressed_len,
9404        uncompressed_checksum,
9405    } = parse_snapshot_header(header)?;
9406    let expected_compressed_len = compressed_len.ok_or_else(|| {
9407        HawDBError::Storage(
9408            "search projection compressed envelope missing compressed_len".to_string(),
9409        )
9410    })?;
9411    if payload.len() != expected_compressed_len {
9412        return Err(HawDBError::Storage(format!(
9413            "search projection compressed length mismatch: expected {expected_compressed_len}, got {}",
9414            payload.len()
9415        )));
9416    }
9417    let expected_compressed_checksum = compressed_checksum.ok_or_else(|| {
9418        HawDBError::Storage(
9419            "search projection compressed envelope missing compressed_checksum".to_string(),
9420        )
9421    })?;
9422    let actual_compressed_checksum = checksum_bytes(payload);
9423    if actual_compressed_checksum != expected_compressed_checksum {
9424        return Err(HawDBError::Storage(format!(
9425            "search projection compressed checksum mismatch: expected {expected_compressed_checksum}, got {actual_compressed_checksum}"
9426        )));
9427    }
9428    let expected_uncompressed_len = uncompressed_len.ok_or_else(|| {
9429        HawDBError::Storage(
9430            "search projection compressed envelope missing uncompressed_len".to_string(),
9431        )
9432    })?;
9433    if expected_uncompressed_len as u64 > max_uncompressed_bytes {
9434        return Err(HawDBError::Storage(format!(
9435            "search projection uncompressed payload requires {expected_uncompressed_len} bytes, exceeding {max_uncompressed_bytes}"
9436        )));
9437    }
9438    let decoded = decode(payload, expected_uncompressed_len)?;
9439    #[cfg(test)]
9440    compression_tests::record_decoded_bytes(decoded.len());
9441    if decoded.len() as u64 > max_uncompressed_bytes {
9442        return Err(HawDBError::Storage(format!(
9443            "search projection decompressed payload exceeded {max_uncompressed_bytes} bytes"
9444        )));
9445    }
9446    if decoded.len() != expected_uncompressed_len {
9447        return Err(HawDBError::Storage(format!(
9448            "search projection uncompressed length mismatch: expected {expected_uncompressed_len}, got {}",
9449            decoded.len()
9450        )));
9451    }
9452    let expected_uncompressed_checksum = uncompressed_checksum.ok_or_else(|| {
9453        HawDBError::Storage(
9454            "search projection compressed envelope missing uncompressed_checksum".to_string(),
9455        )
9456    })?;
9457    let actual_uncompressed_checksum = checksum_bytes(&decoded);
9458    if actual_uncompressed_checksum != expected_uncompressed_checksum {
9459        return Err(HawDBError::Storage(format!(
9460            "search projection uncompressed checksum mismatch: expected {expected_uncompressed_checksum}, got {actual_uncompressed_checksum}"
9461        )));
9462    }
9463    String::from_utf8(decoded).map_err(|error| {
9464        HawDBError::or_stop(&error, || {
9465            HawDBError::Storage(format!(
9466                "search projection decompressed payload is not valid UTF-8: {error}"
9467            ))
9468        })
9469    })
9470}
9471
9472fn read_search_snapshot_decoder(decoder: impl Read, expected_len: usize) -> Result<Vec<u8>> {
9473    let mut decoded = Vec::with_capacity(expected_len.min(1024 * 1024));
9474    // Probe one byte past the declared size to reject understated lengths.
9475    decoder
9476        .take((expected_len as u64).saturating_add(1))
9477        .read_to_end(&mut decoded)
9478        .map_err(|error| {
9479            HawDBError::or_stop(&error, || {
9480                HawDBError::Storage(format!(
9481                    "search projection zstd decompression failed: {error}"
9482                ))
9483            })
9484        })?;
9485    Ok(decoded)
9486}
9487
9488fn checksum_bytes(bytes: &[u8]) -> u64 {
9489    checksum_u64(bytes)
9490}
9491
9492fn elapsed_micros(started: hawdb_core::time::Instant) -> u64 {
9493    started.elapsed().as_micros().min(u64::MAX as u128) as u64
9494}
9495
9496fn parse_u64(input: &str, name: &str) -> Result<u64> {
9497    input
9498        .parse()
9499        .map_err(|_| HawDBError::Storage(format!("invalid {name}: {input}")))
9500}
9501
9502fn parse_i64(input: &str, name: &str) -> Result<i64> {
9503    input
9504        .parse()
9505        .map_err(|_| HawDBError::Storage(format!("invalid {name}: {input}")))
9506}
9507
9508fn parse_usize(input: &str, name: &str) -> Result<usize> {
9509    input
9510        .parse()
9511        .map_err(|_| HawDBError::Storage(format!("invalid {name}: {input}")))
9512}
9513
9514#[cfg(test)]
9515fn test_temp_dir() -> PathBuf {
9516    // Bazel sandboxes can reuse PIDs while sharing the host TMPDIR.
9517    // Use the per-action directory to keep fixture names independent.
9518    std::env::var_os("TEST_TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from)
9519}
9520
9521#[cfg(test)]
9522mod tests;
9523
9524mod graph_store_adapter;
9525
9526fn resident_exact_vector_search_capacity(
9527    document_count: usize,
9528    working_bytes: usize,
9529    max_document_id_bytes: usize,
9530) -> usize {
9531    use hawdb_executor::{VectorCandidate, VectorRawScore};
9532    let id = max_document_id_bytes;
9533    let candidates = working_bytes / (2 * size_of::<VectorCandidate>()).saturating_add(id).max(1);
9534    let lookup = document_count.saturating_mul(3 * size_of::<(&str, &SearchDocument)>());
9535    let rerank = working_bytes.saturating_sub(lookup)
9536        / size_of::<VectorCandidate>()
9537            .saturating_add(size_of::<VectorRawScore>())
9538            .saturating_add(id.saturating_mul(2))
9539            .max(1);
9540    candidates.min(rerank)
9541}