Skip to main content

hawdb_search/
out_of_core.rs

1// Copyright 2026 Nowledge
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use super::lexical_projection::{
16    manifest_generation as lexical_manifest_generation, LexicalCorpusStatistics,
17    LexicalProjectionConfig, LexicalProjectionReader, DEFAULT_MAX_MANIFEST_BYTES, MANIFEST_FILE,
18};
19use super::{
20    checksum_bytes, decode_search_snapshot_text_bounded, decode_string, encode_metadata,
21    encode_search_snapshot_text, encode_string, lexical_analyzer_digest, lexical_documents_digest,
22    rrf_child_score, search_empty_reasons, top_ranked_candidates, top_ranked_ids,
23    weighted_rrf_score, CompressedVectorSearchMode, SearchAccessControlContext,
24    SearchAnalyzerLexicon, SearchCandidateSetReport, SearchDocument, SearchEmbeddingManifest,
25    SearchFallbackReasonCode, SearchFieldPruningAccumulator, SearchHit, SearchHitHydration,
26    SearchIndex, SearchMode, SearchPageWindow, SearchPredicatePushdownReport,
27    SearchProjectionFreshness, SearchQueryOptions, SearchResultSet, SearchRetrieverReport,
28    SearchScoredCandidate, SearchSegmentDescriptor, SearchSegmentDescriptorEntry,
29    SearchTruncationReasonCode, VectorRelevanceQuery, VectorSearchExecutionOptions,
30    FULL_REINDEX_MARKER, METADATA_REPAIR_MARKER, SEARCH_SEGMENT_DESCRIPTOR_FILE,
31    SEARCH_SEGMENT_PAYLOAD_FILE,
32};
33use crate::bounded_file::{read_bound_file, read_bounded_file};
34use crate::error::{HawDBError, Result};
35use crate::projection_id_page;
36use crate::resident_documents::DocumentView;
37#[cfg(test)]
38use crate::{decode_search_segment_documents_bounded, validate_search_segment_documents};
39use crate::{
40    RuntimeCapabilities, RuntimeCapability, SearchLexicalSourcePolicy, SearchLexicalTermPolicy,
41};
42use crate::{SearchProjectionIdBatch, SearchProjectionKind, SearchProjectionPageGeneration};
43use hawdb_core::{ResourceBudgetError, ResourceBudgetKind, ResourceBudgetScope};
44use hawdb_storage::durability::durable_replace_file;
45use hawdb_storage::file_io::{self as fs, File, OpenOptions};
46use serde::{Deserialize, Serialize};
47use std::cmp::{Ordering as CmpOrdering, Reverse};
48use std::collections::{BTreeMap, BTreeSet, BinaryHeap};
49use std::io::{Read, Seek, SeekFrom, Write};
50use std::num::{NonZeroU64, NonZeroUsize};
51use std::path::{Path, PathBuf};
52use std::sync::atomic::{AtomicU64, Ordering};
53use std::sync::{Arc, Mutex};
54
55static OUT_OF_CORE_READER_SEQUENCE: AtomicU64 = AtomicU64::new(1);
56
57fn next_out_of_core_reader_id() -> u64 {
58    OUT_OF_CORE_READER_SEQUENCE.fetch_add(1, Ordering::Relaxed)
59}
60
61mod admitted_root;
62mod candidate_set;
63mod query_memory;
64mod query_output;
65pub use query_output::{SearchQueryError, SearchQueryResult, SearchRetainedOutput};
66mod query_ranking;
67mod score_collector;
68mod vector_query;
69use candidate_set::CandidateSet;
70use score_collector::{score_entries_refusal, BoundedScoreCollector};
71
72/// The reader option that bounds query score entries and windows.
73const MAX_SCORE_ENTRIES_OPTION: &str = "SearchOutOfCoreConfig.max_score_entries";
74
75/// Query terms of a hit hydrated without matched terms/spans.
76static NO_TERMS: BTreeSet<String> = BTreeSet::new();
77
78/// A search page, hydration-by-id or mutation-target request that would
79/// hydrate more documents than the reader admits.
80fn hydrated_documents_refusal(
81    owner: &str,
82    requested: usize,
83    budget: usize,
84    message: String,
85) -> HawDBError {
86    ResourceBudgetError {
87        resource: ResourceBudgetKind::MetadataEntries,
88        scope: ResourceBudgetScope::Operator,
89        owner: owner.into(),
90        memory_class: None,
91        requested: u64::try_from(requested).unwrap_or(u64::MAX),
92        used: 0,
93        budget: u64::try_from(budget).unwrap_or(u64::MAX),
94        budget_option: "SearchOutOfCoreConfig.max_hydrated_documents",
95        message,
96    }
97    .into()
98}
99
100/// Who asked [`SearchOutOfCoreReader::load_document_targets`] for documents.
101///
102/// The request names the budget owner and decides what an id the published
103/// projection does not contain means.
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105enum DocumentTargetRequest {
106    /// Hits produced by this reader's own index. A hit without a visible
107    /// document route is index damage.
108    SearchHits,
109    /// Hits of a text-only query, which never rescore a stored embedding:
110    /// their decimal-text vectors are left unparsed (#1917).
111    TextHits,
112    /// Ids named by the caller of [`SearchOutOfCoreReader::hydrate_documents`].
113    /// An id that is absent or deleted is the caller's mistake.
114    ById,
115    /// Ids named by the caller of [`SearchOutOfCoreReader::lookup_documents`].
116    /// An id that is absent or deleted is reported missing, not refused.
117    LookupById,
118    /// Ids a mutation writer derived against this reader (test-only today).
119    /// A missing one means the index disagrees with that writer's source.
120    #[cfg(test)]
121    MutationTargets,
122}
123
124impl DocumentTargetRequest {
125    /// Whether the loaded documents carry their stored embeddings.
126    fn embeddings(self) -> bool {
127        !matches!(self, Self::TextHits)
128    }
129
130    /// The operation named in messages; the budget owner is `search {operation}`.
131    fn operation(self) -> &'static str {
132        match self {
133            Self::SearchHits | Self::TextHits => "hydration",
134            Self::ById => "hydration by id",
135            Self::LookupById => "lookup by id",
136            #[cfg(test)]
137            Self::MutationTargets => "mutation target resolution",
138        }
139    }
140
141    /// What an id without a visible document route means: `None` when the
142    /// caller asked which ids are present, otherwise the refusal.
143    fn unknown_document(self, id: &str) -> Option<HawDBError> {
144        match self {
145            Self::ById => Some(HawDBError::Semantic(format!(
146                "search hydration by id requested document {id}, which the published search projection does not contain"
147            ))),
148            Self::LookupById => None,
149            Self::SearchHits | Self::TextHits => Some(HawDBError::Storage(format!(
150                "search document {id} is outside the published document ranges"
151            ))),
152            #[cfg(test)]
153            Self::MutationTargets => Some(HawDBError::Storage(format!(
154                "search document {id} is outside the published document ranges"
155            ))),
156        }
157    }
158}
159
160pub(crate) struct CandidateQuery<'a> {
161    pub(crate) text: &'a str,
162    pub(crate) embedding: Option<&'a [f32]>,
163    pub(crate) mode: SearchMode,
164    pub(crate) options: SearchQueryOptions,
165    pub(crate) task: &'a hawdb_core::RuntimeTaskContext,
166    pub(crate) permit: &'a hawdb_qos::RuntimePermit,
167}
168
169/// A complete native candidate reader retained privately until a separate
170/// source-E fence and durable selector can grant serving authority.
171#[derive(Clone)]
172pub(crate) struct CandidateView(Arc<SharedCandidateView>);
173
174struct SharedCandidateView {
175    opened: admitted_root::OpenedRoot,
176    // Close the reader and native pins before refunding the shared allocation.
177    _memory: hawdb_qos::RuntimeRetainedMemory,
178}
179
180impl std::fmt::Debug for CandidateView {
181    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
182        formatter
183            .debug_struct("CandidateView")
184            .field("document_count", &self.document_count())
185            .field("source_epoch", &self.source_epoch())
186            .field("generation", &self.generation())
187            .finish_non_exhaustive()
188    }
189}
190
191impl CandidateView {
192    pub(crate) fn write_vector_successor(
193        &self,
194        index: &SearchIndex,
195        previous: &crate::consumer::ConsumerProjection,
196        target: &SearchProjectionPublishLease,
197        task: hawdb_core::RuntimeTaskContext,
198        generation_bytes: NonZeroU64,
199        permit: Arc<hawdb_qos::RuntimePermit>,
200    ) -> Result<crate::snapshot_writer::SearchSnapshotWriteReport> {
201        if !self.shares_governor_with(&permit) {
202            return Err(HawDBError::Execution(
203                "vector successor requires its original governor".into(),
204            ));
205        }
206        self.0.opened.write_vector_successor(
207            index,
208            previous,
209            target,
210            task,
211            generation_bytes,
212            permit,
213        )
214    }
215
216    pub(crate) fn vector_index_query(
217        &self,
218        request: crate::VectorIndexQuery<'_>,
219        publication_generation: u64,
220        permit: &hawdb_qos::RuntimePermit,
221        task: &hawdb_core::RuntimeTaskContext,
222    ) -> SearchQueryResult<crate::VectorIndexRetainedOutput> {
223        self.0
224            .opened
225            .vector_index_query(request, publication_generation, permit, task)
226    }
227
228    pub(crate) fn prepare_consumer_update(
229        &self,
230        permit: Arc<hawdb_qos::RuntimePermit>,
231        options: SearchOutOfCoreGenerationBuildOptions,
232        limits: SearchUnorderedMutationLimits,
233        task: hawdb_core::RuntimeTaskContext,
234    ) -> Result<SearchOutOfCoreUnorderedMutationWriter<'_>> {
235        self.0
236            .opened
237            .prepare_consumer_update(permit, options, limits, task)
238    }
239
240    pub(crate) fn shares_governor_with(&self, permit: &hawdb_qos::RuntimePermit) -> bool {
241        self.0._memory.shares_governor_with(permit) && self.0.opened.shares_governor_with(permit)
242    }
243
244    pub(crate) fn probe_query(
245        &self,
246        query: CandidateQuery<'_>,
247    ) -> SearchQueryResult<SearchRetainedOutput> {
248        self.0.opened.probe_query(query)
249    }
250
251    pub(crate) fn document_count(&self) -> usize {
252        self.0.opened.document_count()
253    }
254
255    pub(crate) fn source_epoch(&self) -> Option<u64> {
256        self.0.opened.source_epoch()
257    }
258
259    pub(crate) fn generation(&self) -> u64 {
260        self.0.opened.generation()
261    }
262}
263
264#[derive(Clone, Copy)]
265pub(crate) enum StationaryRoot<'a> {
266    Born(&'a hawdb_storage::consumer_allocation::PendingConsumerGeneration),
267    Reopened(&'a hawdb_storage::consumer_allocation::ReopenedConsumerGeneration),
268}
269
270impl<'a> StationaryRoot<'a> {
271    fn generation_name(self) -> &'a str {
272        match self {
273            Self::Born(root) => root.generation_name(),
274            Self::Reopened(root) => root.generation_name(),
275        }
276    }
277    fn directory(
278        self,
279        task: &hawdb_core::RuntimeTaskContext,
280    ) -> Result<&'a hawdb_storage::file_io::SourceDirectory> {
281        match self {
282            Self::Born(root) => root.born_directory(),
283            Self::Reopened(root) => root.directory(task),
284        }
285    }
286}
287
288pub(crate) struct StationaryCandidateOpenContext<'a> {
289    pub(crate) stationary: StationaryRoot<'a>,
290    pub(crate) publication: &'a mut SearchProjectionPublishLease,
291    pub(crate) memory: &'a crate::build_memory::BuildMemory,
292    pub(crate) task: &'a hawdb_core::RuntimeTaskContext,
293    pub(crate) permit: &'a hawdb_qos::RuntimePermit,
294    pub(crate) expected_manifest: hawdb_storage::immutable_object::ObjectReference,
295    pub(crate) config: SearchOutOfCoreConfig,
296    pub(crate) max_artifact_read_bytes: NonZeroU64,
297}
298
299pub(crate) fn open_stationary_candidate(
300    context: StationaryCandidateOpenContext<'_>,
301) -> Result<CandidateView> {
302    let StationaryCandidateOpenContext {
303        stationary,
304        publication,
305        memory,
306        task,
307        permit,
308        expected_manifest,
309        config,
310        max_artifact_read_bytes,
311    } = context;
312    let project = publication.with_captured_directory(|directory| {
313        hawdb_storage::file_descriptors::ProjectFileDescriptors::from_open_context(
314            &directory.operation_context(),
315        )
316    });
317    let admission = crate::build_memory::read::ReadAdmission {
318        memory,
319        task,
320        permit: crate::build_memory::read::ReadPermit::Governed(permit),
321    };
322    let root = Path::new(stationary.generation_name());
323    let opened = admitted_root::open(admitted_root::OpenContext {
324        root,
325        publication: Some(publication),
326        stationary: Some(stationary),
327        expected_stationary_manifest: Some(expected_manifest),
328        config,
329        analyzer_lexicon: SearchAnalyzerLexicon::default(),
330        lexical_term_policy: SearchLexicalTermPolicy::default(),
331        lexical_source_policy: SearchLexicalSourcePolicy::default(),
332        admission: Some(&admission),
333        project: Some(&project),
334        max_artifact_read_bytes: max_artifact_read_bytes.get(),
335    })?;
336    let shared_bytes = std::mem::size_of::<SharedCandidateView>()
337        .checked_add(2 * std::mem::size_of::<usize>())
338        .ok_or_else(|| HawDBError::Execution("shared candidate allocation overflows".into()))?;
339    let memory = permit
340        .reserve_retained_memory(shared_bytes as u64)
341        .map_err(HawDBError::from_execution_error)?;
342    Ok(CandidateView(Arc::new(SharedCandidateView {
343        opened,
344        _memory: memory,
345    })))
346}
347pub(crate) mod artifact_key;
348mod epoch_advance;
349pub use epoch_advance::SearchProjectionEpochAdvanceReport;
350mod content_blocks;
351pub use content_blocks::SearchContentVerificationReport;
352mod generation_writer;
353mod hydration;
354mod metadata_query;
355mod postings;
356mod projection_scan;
357mod verified_body;
358pub use verified_body::{SearchBodyReadOptions, SearchVerifiedBody};
359pub(crate) mod mutation_run;
360mod publish_lease;
361mod reuse;
362mod root_registry;
363mod text_seed;
364#[cfg(feature = "vector-search")]
365mod vector_qualification;
366#[cfg(feature = "vector-search")]
367mod vector_reader;
368mod vector_segment;
369mod vector_serving;
370pub use generation_writer::{
371    GovernedSearchGenerationUpdate, GovernedSearchGenerationWriter, PreparedSearchPublication,
372    ScheduledSearchOutOfCoreSegmentCompactionReport, SearchAdmittedConsumerDocuments,
373    SearchBaselineComparisonLimits, SearchBaselineComparisonReport,
374    SearchComparedConsumerDocuments, SearchGenerationAdmission, SearchMatchedBaseline,
375    SearchMutationInspectionInput, SearchMutationInspectionStep, SearchMutationSortStep,
376    SearchMutationSortStepLimits, SearchMutationSortStepUsage, SearchOutOfCoreBaselineComparison,
377    SearchOutOfCoreDeltaComparison, SearchOutOfCoreGenerationBuildOptions,
378    SearchOutOfCoreGenerationBuildReport, SearchOutOfCoreGenerationUpdate,
379    SearchOutOfCoreGenerationWriter, SearchOutOfCoreMutationWriter,
380    SearchOutOfCorePreparedGeneration, SearchOutOfCorePreparedUpdate,
381    SearchOutOfCoreSegmentCompaction, SearchOutOfCoreSegmentCompactionPolicy,
382    SearchOutOfCoreSegmentCompactionReport, SearchOutOfCoreSegmentCompactionStopReason,
383    SearchOutOfCoreUnorderedMutationWriter, SearchOutOfCoreUnorderedReplacementWriter,
384    SearchStagingCleanupReport, SearchUnorderedMutationLimits, SearchUnorderedMutationReport,
385};
386pub(super) use publish_lease::SearchProjectionPublishLease;
387pub use text_seed::{SearchTextSeedOutput, SearchTextSeedReport};
388#[cfg(feature = "vector-search")]
389use vector_serving::vector_projection_error;
390use vector_serving::VectorScoreScan;
391
392pub(crate) const OUT_OF_CORE_MANIFEST_FILE: &str = "search_projection.out_of_core.manifest.hawdb";
393const OUT_OF_CORE_FORMAT: &str = "HAWDB_SEARCH_OUT_OF_CORE_V4";
394/// V4 gives per-segment metadata value postings explicit field semantics for
395/// reserved scalar fields (`out_of_core::postings`).
396const OUT_OF_CORE_LAYOUT_FORMAT: &str = "HAWDB_SEARCH_OUT_OF_CORE_LAYOUT_V4";
397/// V3 introduced plain metadata value postings. It remains readable; filters
398/// using V4's reserved-field semantics fall back to the metadata sidecar.
399const LEGACY_POSTINGS_OUT_OF_CORE_LAYOUT_FORMAT: &str = "HAWDB_SEARCH_OUT_OF_CORE_LAYOUT_V3";
400/// V2 stores raw vectors as binary rows (`out_of_core::vector_segment`) and
401/// has no postings. It remains readable; its filters scan the metadata.
402const POSTINGLESS_OUT_OF_CORE_LAYOUT_FORMAT: &str = "HAWDB_SEARCH_OUT_OF_CORE_LAYOUT_V2";
403/// V1 stored zstd-compressed decimal-text vector sidecars. Readers refuse it.
404const SUPERSEDED_OUT_OF_CORE_LAYOUT_FORMATS: &[&str] = &["HAWDB_SEARCH_OUT_OF_CORE_LAYOUT_V1"];
405pub(crate) const MAX_OUT_OF_CORE_MANIFEST_BYTES: u64 = 1024 * 1024;
406const MAX_MARKER_BYTES: u64 = 64 * 1024;
407const CANDIDATE_FILE_HEADER: &[u8; 8] = b"SKNCAND1";
408static CANDIDATE_SEQUENCE: AtomicU64 = AtomicU64::new(0);
409
410/// Default [`SearchOutOfCoreConfig::content_cache_bytes`]: about a thousand
411/// 16 KiB content blocks.
412pub(crate) const DEFAULT_CONTENT_CACHE_BYTES: u64 = 16 * 1024 * 1024;
413
414#[derive(Debug, Clone, PartialEq, Eq)]
415pub struct SearchOutOfCoreConfig {
416    pub max_compressed_segment_bytes: NonZeroU64,
417    pub max_uncompressed_segment_bytes: NonZeroU64,
418    pub max_descriptor_bytes: NonZeroU64,
419    /// Caller-selected encoded size bound for one mutation-run artifact.
420    pub max_mutation_run_bytes: NonZeroU64,
421    /// Aggregate mutation-run buffers, decoded ownership and validation indexes.
422    /// A refusal is typed `ResourceBudgetExceeded` and names this option.
423    /// Content artifacts and one-target hydration/analysis use their own limits.
424    pub max_mutation_working_bytes: NonZeroU64,
425    /// Total transient memory available for exact old-version reanalysis.
426    pub max_reanalysis_working_bytes: NonZeroU64,
427    /// External frequency-run bytes admitted during old-version reanalysis.
428    pub max_reanalysis_spill_bytes: NonZeroU64,
429    /// Bounded resident document header during streaming body operations.
430    pub max_document_header_bytes: NonZeroUsize,
431    /// Caller-selected encoded lexical manifest limit, including private decoding.
432    /// Prepared generation updates inherit this limit and require it to fit `isize`.
433    pub max_lexical_manifest_bytes: NonZeroU64,
434    pub max_candidate_spill_bytes: NonZeroU64,
435    pub max_candidate_block_bytes: NonZeroU64,
436    pub max_score_entries: NonZeroUsize,
437    /// Scored lexical terms per query; `lexical_query_term_policy` decides
438    /// what a longer analyzed query does.
439    pub max_lexical_query_terms: NonZeroUsize,
440    /// What a query above `max_lexical_query_terms` does: refused by default,
441    /// or reduced to its most selective terms and reported as
442    /// `text_query_terms_reduced` when the host opts in.
443    pub lexical_query_term_policy: crate::LexicalQueryTermPolicy,
444    /// Distinct analyzed lexical terms admitted before that selection. It
445    /// bounds query normalization and statistics reads; exceeding it fails.
446    /// Values below `max_lexical_query_terms` are raised to it.
447    pub max_lexical_query_analyzed_terms: NonZeroUsize,
448    pub max_vector_candidates: NonZeroUsize,
449    /// DiskANN navigation beam for ordinary Search queries that do not set one with
450    /// [`VectorSearchExecutionOptions::with_navigation_beam`]. A narrower beam
451    /// scores fewer vectors per segment graph at some recall cost (#1614). A
452    /// traversal that spreads over a graph small for the beam may finish with a
453    /// complete evaluation (#1970).
454    /// Defaults to 256. Canonical `vector_index_search` does not inherit this
455    /// reader setting and retains its separate single-graph recall budget.
456    pub default_navigation_beam: NonZeroUsize,
457    pub max_vector_search_working_bytes: NonZeroUsize,
458    pub max_vector_search_parallelism: NonZeroUsize,
459    pub max_hydrated_documents: NonZeroUsize,
460    pub max_hydrated_bytes: NonZeroU64,
461    pub max_matched_spans: NonZeroUsize,
462    pub max_matched_span_bytes: NonZeroU64,
463    /// Capacity of the reader's cache of verified, decompressed content blocks
464    /// and segment indexes (#1917), shared by every query and refresh of one
465    /// reader. Zero disables it. Cached bytes are owned by the cache, not by
466    /// a query: a query charges only its transient read and decode buffers.
467    pub content_cache_bytes: u64,
468    pub spill_directory: PathBuf,
469}
470
471impl Default for SearchOutOfCoreConfig {
472    fn default() -> Self {
473        Self {
474            max_compressed_segment_bytes: NonZeroU64::new(64 * 1024 * 1024).unwrap(),
475            max_uncompressed_segment_bytes: NonZeroU64::new(256 * 1024 * 1024).unwrap(),
476            max_descriptor_bytes: NonZeroU64::new(256 * 1024 * 1024).unwrap(),
477            max_mutation_run_bytes: NonZeroU64::new(64 * 1024 * 1024).unwrap(),
478            max_mutation_working_bytes: NonZeroU64::new(128 * 1024 * 1024).unwrap(),
479            max_reanalysis_working_bytes: NonZeroU64::new(128 * 1024 * 1024).unwrap(),
480            max_reanalysis_spill_bytes: NonZeroU64::new(4 * 1024 * 1024 * 1024).unwrap(),
481            max_document_header_bytes: NonZeroUsize::new(1024 * 1024).unwrap(),
482            max_lexical_manifest_bytes: NonZeroU64::new(DEFAULT_MAX_MANIFEST_BYTES).unwrap(),
483            max_candidate_spill_bytes: NonZeroU64::new(4 * 1024 * 1024 * 1024).unwrap(),
484            max_candidate_block_bytes: NonZeroU64::new(16 * 1024 * 1024).unwrap(),
485            max_score_entries: NonZeroUsize::new(1_000_000).unwrap(),
486            max_lexical_query_terms: NonZeroUsize::new(
487                crate::lexical_projection::DEFAULT_MAX_QUERY_TERMS,
488            )
489            .unwrap(),
490            lexical_query_term_policy: crate::LexicalQueryTermPolicy::Exact,
491            max_lexical_query_analyzed_terms: NonZeroUsize::new(
492                crate::lexical_projection::DEFAULT_MAX_QUERY_ANALYZED_TERMS,
493            )
494            .unwrap(),
495            max_vector_candidates: NonZeroUsize::new(1_024).unwrap(),
496            default_navigation_beam: NonZeroUsize::new(crate::DEFAULT_OUT_OF_CORE_NAVIGATION_BEAM)
497                .unwrap(),
498            max_vector_search_working_bytes: NonZeroUsize::new(64 * 1024 * 1024).unwrap(),
499            max_vector_search_parallelism: NonZeroUsize::MIN,
500            max_hydrated_documents: NonZeroUsize::new(1024).unwrap(),
501            max_hydrated_bytes: NonZeroU64::new(64 * 1024 * 1024).unwrap(),
502            max_matched_spans: NonZeroUsize::new(4096).unwrap(),
503            max_matched_span_bytes: NonZeroU64::new(8 * 1024 * 1024).unwrap(),
504            content_cache_bytes: DEFAULT_CONTENT_CACHE_BYTES,
505            spill_directory: std::env::temp_dir().join("hawdb-search"),
506        }
507    }
508}
509
510#[derive(Debug, Clone, Default, PartialEq, Eq)]
511pub struct SearchOutOfCoreMetrics {
512    pub segment_range_reads: u64,
513    pub segment_bytes_read: u64,
514    pub lexical_document_block_reads: u64,
515    pub lexical_document_bytes_read: u64,
516    pub metadata_segment_bytes_read: u64,
517    pub vector_segment_bytes_read: u64,
518    pub hydration_segment_bytes_read: u64,
519    pub peak_segment_document_bytes: u64,
520    pub peak_metadata_segment_bytes: u64,
521    pub peak_vector_segment_bytes: u64,
522    pub candidate_spill_bytes: u64,
523    pub candidate_block_reads: u64,
524    pub candidate_bytes_read: u64,
525    pub vector_bytes_read: u64,
526    pub rabitq_payload_bytes_read: u64,
527    /// Bodies processed through bounded staging without owned materialization.
528    pub streamed_documents: usize,
529    pub streamed_body_bytes: u64,
530    pub hydrated_documents: usize,
531    pub hydrated_bytes: u64,
532    /// Peak bytes charged to the query's working account by
533    /// [`SearchOutOfCoreReader::search_with_options_admitted`]; zero for
534    /// unaccounted ordinary reads.
535    pub query_memory_peak_bytes: u64,
536    /// Block-framed content segments (#1917): segment indexes read from disk
537    /// and served from the reader's content cache.
538    pub content_index_reads: u64,
539    pub content_index_cache_hits: u64,
540    /// Content blocks read, verified and inflated, and those served verified
541    /// from the reader's content cache.
542    pub content_blocks_read: u64,
543    pub content_block_cache_hits: u64,
544    pub content_block_bytes_inflated: u64,
545}
546
547/// Batched routes, `(artifact_index, segment)` per requested id in order.
548struct DocumentRoutes<'a> {
549    routes: Vec<Option<(usize, &'a SearchSegmentDescriptorEntry)>>,
550    _memory: Option<hawdb_executor::QueryMemoryLease>,
551}
552
553struct SearchDocumentSegmentRoute<'a> {
554    artifact_index: usize,
555    segment: &'a SearchSegmentDescriptorEntry,
556    lexical_document_bytes_read: u64,
557}
558
559#[derive(Debug, Clone, PartialEq)]
560pub struct SearchOutOfCoreOutput<H = SearchHit> {
561    pub result: SearchResultSet<H>,
562    pub metrics: SearchOutOfCoreMetrics,
563}
564
565/// A ranked hit bound to this reader's immutable content version.
566///
567/// No body or matched spans are loaded. Keep the originating reader alive for
568/// subsequent version-specific reads; this value alone does not retain a pin.
569#[derive(Debug, Clone, PartialEq)]
570pub struct SearchOutOfCoreCandidate {
571    pub scores: SearchScoredCandidate,
572    pub generation: u64,
573    pub content_segment_id: u64,
574}
575
576#[derive(Debug, Clone, PartialEq)]
577pub struct SearchOutOfCoreHydrationOutput {
578    pub documents: Vec<SearchDocument>,
579    pub metrics: SearchOutOfCoreMetrics,
580}
581
582/// The result of [`SearchOutOfCoreReader::lookup_documents`].
583///
584/// Every requested id appears exactly once: either as a document in
585/// `documents` or in `missing_document_ids`. Both lists follow request order.
586#[derive(Debug, Clone, PartialEq)]
587pub struct SearchOutOfCoreDocumentLookup {
588    /// The requested documents the published projection contains.
589    pub documents: Vec<SearchDocument>,
590    /// The requested ids the published projection does not contain, including
591    /// deleted ones.
592    pub missing_document_ids: Vec<String>,
593    pub metrics: SearchOutOfCoreMetrics,
594}
595
596/// A current document together with the immutable content segment that owns it.
597///
598/// Mutation preparation uses this identity to rewrite the affected content
599/// segment instead of applying a generation-wide tombstone.
600#[derive(Debug, Clone, PartialEq)]
601pub(crate) struct SearchOutOfCoreMutationTarget {
602    pub(crate) content_segment_id: u64,
603    pub(crate) document: SearchDocument,
604}
605
606#[cfg(test)]
607#[derive(Debug, Clone, PartialEq)]
608pub(crate) struct SearchOutOfCoreMutationTargetOutput {
609    pub(crate) targets: BTreeMap<String, SearchOutOfCoreMutationTarget>,
610    pub(crate) metrics: SearchOutOfCoreMetrics,
611}
612
613#[derive(Debug)]
614pub struct SearchOutOfCoreReader {
615    reader_id: u64,
616    root: PathBuf,
617    _project_files: hawdb_storage::file_descriptors::ProjectFileDescriptors,
618    config: SearchOutOfCoreConfig,
619    analyzer_lexicon: SearchAnalyzerLexicon,
620    manifest: SearchOutOfCoreManifestBody,
621    segments: Vec<SearchOutOfCoreSegmentReader>,
622    visibility: mutation_run::MutationVisibility,
623    lexical_source_policy: SearchLexicalSourcePolicy,
624    lexical_term_policy: SearchLexicalTermPolicy,
625    runtime_capabilities: RuntimeCapabilities,
626    /// Verified content blocks and indexes, shared across refreshes (#1917).
627    content_cache: content_blocks::ContentCache,
628}
629
630/// One immutable group of search artifacts selected by an out-of-core manifest.
631///
632/// The current manifest selects one group. Keeping the artifact closure separate
633/// from reader-wide identity and admission state is the boundary needed for
634/// incremental segment publication.
635#[derive(Debug, Clone)]
636pub(super) struct SearchOutOfCoreSegmentReader(
637    crate::build_memory::shared::Shared<SegmentReaderContents>,
638);
639
640// Share one complete immutable payload. A future retained admission can live
641// beside these values and follow every snapshot/reuse clone, rather than being
642// detached from independently cloned descriptor/layout/lexical metadata.
643#[derive(Debug)]
644pub(super) struct SegmentReaderContents {
645    content_segment_id: u64,
646    descriptor: crate::document_encoding::DecodedDescriptor,
647    payload: File,
648    payload_length: u64,
649    /// Selector-declared framing of `payload` (#1917).
650    content_encoding: content_blocks::ContentEncoding,
651    /// The payload's SHA-256 and generation: its content-cache identity.
652    payload_sha256: [u8; 32],
653    payload_generation: u64,
654    metadata_payload: File,
655    metadata_payload_length: u64,
656    vector_payload: File,
657    vector_payload_length: u64,
658    layout: SearchOutOfCoreLayoutBody,
659    lexical_projection: LexicalProjectionReader,
660    #[cfg(feature = "vector-search")]
661    rabitq_projection: Option<vector_reader::Projection>,
662    _source_pins: [Option<root_registry::ArtifactPin>; 3],
663    _layout_memory: Option<crate::build_memory::read::ReaderMemory>,
664    _reader_memory: Option<crate::build_memory::read::ReaderMemory>,
665}
666
667struct SegmentOpenContext<'a> {
668    cleanup_source: Option<&'a captured_cleanup::Source<'a>>,
669    capture: Option<&'a root_registry::PendingCapture<'a, 'a>>,
670    root: &'a Path,
671    config: &'a SearchOutOfCoreConfig,
672    analyzer_lexicon: &'a SearchAnalyzerLexicon,
673    lexical_source_policy: SearchLexicalSourcePolicy,
674    lexical_term_policy: SearchLexicalTermPolicy,
675    active_manifest: &'a SearchOutOfCoreManifestBody,
676    admission: Option<&'a crate::build_memory::read::ReadAdmission<'a>>,
677    max_artifact_read_bytes: u64,
678}
679
680impl std::ops::Deref for SearchOutOfCoreSegmentReader {
681    type Target = SegmentReaderContents;
682
683    fn deref(&self) -> &Self::Target {
684        &self.0
685    }
686}
687
688#[derive(Debug, Clone, Copy)]
689pub(super) struct PublishedOutOfCoreProjection {
690    pub(super) generation: u64,
691    pub(super) bytes_written: u64,
692}
693
694mod artifact_reference;
695mod captured_cleanup;
696mod manifest_version;
697#[cfg(test)]
698pub(crate) use captured_cleanup::set_snapshot_decode_limit_for_test;
699pub(crate) use captured_cleanup::VerificationWork;
700mod scratch_directory;
701use artifact_reference::{ArtifactObject, ResidentSnapshot, SegmentObjects};
702pub(crate) use scratch_directory::{ScratchDirectory, SpillFile};
703
704#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
705#[serde(deny_unknown_fields)]
706struct SearchOutOfCoreManifestBody<S = String> {
707    format: S,
708    /// Selector version of the writer, present only with
709    /// `min_reader_version`. Absent means version 1. See
710    /// `docs/SEARCH_PROJECTION_MANIFEST_VERSION.md` (#1763).
711    #[serde(
712        default = "manifest_version::base_version",
713        skip_serializing_if = "manifest_version::is_base_version"
714    )]
715    format_version: u16,
716    /// The lowest selector version that understands every field present.
717    /// Writers derive it from the fields in `stamp_reader_version`; a reader
718    /// with a lower version refuses the selector before decoding its fields.
719    #[serde(
720        default = "manifest_version::base_version",
721        skip_serializing_if = "manifest_version::is_base_version"
722    )]
723    min_reader_version: u16,
724    generation: u64,
725    resident_snapshot: Option<ResidentSnapshot>,
726    resident_snapshot_absent: bool,
727    segments: Vec<SearchOutOfCoreSegmentManifest<S>>,
728    #[serde(default)]
729    mutation_runs: Vec<SearchOutOfCoreMutationRunManifest<S>>,
730    document_count: usize,
731    documents_digest: u64,
732    source_graph_commit_epoch: Option<u64>,
733    /// Source epoch of the last content publication, present only after a
734    /// verified metadata-only advance (#1756) moved `source_graph_commit_epoch`
735    /// past it. The resident snapshot, lexical manifests and vector artifacts
736    /// of the closure keep this stamp; segments keep their own epochs.
737    #[serde(default, skip_serializing_if = "Option::is_none")]
738    content_source_graph_commit_epoch: Option<u64>,
739    import_source_graph_commit_epoch: Option<u64>,
740    embedding_model: Option<S>,
741    embedding_version: Option<S>,
742    embedding_dimension: Option<usize>,
743    #[serde(default, skip_serializing_if = "Option::is_none")]
744    vector_index_binding: Option<S>,
745    #[serde(
746        default,
747        skip_serializing_if = "crate::SearchVectorScoring::is_default"
748    )]
749    vector_scoring: crate::SearchVectorScoring,
750}
751
752/// One immutable artifact closure selected by an out-of-core manifest.
753///
754/// Segment-local identity stays with the files it validates. The active
755/// manifest owns the logical projection identity and will eventually select
756/// multiple entries as an incremental segment set.
757#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
758#[serde(deny_unknown_fields, bound(deserialize = "S: Deserialize<'de>"))]
759struct SearchOutOfCoreSegmentManifest<S = String> {
760    segment_id: u64,
761    level: u32,
762    generation: u64,
763    objects: SegmentObjects,
764    descriptor_file: S,
765    descriptor_len: u64,
766    descriptor_checksum: u64,
767    payload_file: S,
768    payload_len: u64,
769    metadata_payload_file: S,
770    metadata_payload_len: u64,
771    vector_payload_file: S,
772    vector_payload_len: u64,
773    layout_file: S,
774    layout_len: u64,
775    layout_checksum: u64,
776    lexical_manifest_file: S,
777    lexical_manifest_len: u64,
778    lexical_manifest_checksum: u64,
779    #[serde(default)]
780    rabitq_artifact_file: Option<S>,
781    // The existing artifact slot and filename grammar carry either backend.
782    // This digest selects the graph format; readers also check the definition.
783    #[serde(default, skip_serializing_if = "Option::is_none")]
784    diskann_source_digest: Option<[u8; 32]>,
785    #[serde(default)]
786    rabitq_artifact_len: Option<u64>,
787    #[serde(default)]
788    rabitq_artifact_checksum: Option<u64>,
789    #[serde(default)]
790    rabitq_source_digest: Option<u64>,
791    #[serde(default)]
792    rabitq_vector_document_count: Option<usize>,
793    #[serde(default)]
794    rabitq_payload_checksum: Option<u32>,
795    #[serde(default)]
796    rabitq_peak_build_working_bytes: Option<usize>,
797    document_count: usize,
798    documents_digest: u64,
799    source_graph_commit_epoch: Option<u64>,
800    /// `Some(4)` when the descriptor uses the V4 grammar, which can omit a
801    /// field's value set (#1746). Absent for V1-V3 descriptors. Its presence
802    /// raises the selector's `min_reader_version` to 4.
803    #[serde(default, skip_serializing_if = "Option::is_none")]
804    descriptor_version: Option<u16>,
805    /// How `payload_file` frames its descriptor segments. Absent means
806    /// `stream1`; `blocks1` requires selector version 3 (#1917).
807    #[serde(
808        default,
809        skip_serializing_if = "content_blocks::ContentEncoding::is_stream1"
810    )]
811    content_encoding: content_blocks::ContentEncoding,
812}
813
814/// The descriptor grammar that can omit a value set (#1746).
815pub(crate) const VALUE_SUMMARY_DESCRIPTOR_VERSION: u16 = 4;
816
817/// One immutable mutation artifact selected by the active manifest.
818///
819/// The artifact carries the target-specific retractions that will later drive
820/// shared visibility and live corpus statistics. Its identity remains separate
821/// from content segments because a delete may publish no replacement content.
822#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
823#[serde(deny_unknown_fields, bound(deserialize = "S: Deserialize<'de>"))]
824struct SearchOutOfCoreMutationRunManifest<S = String> {
825    generation: u64,
826    object: ArtifactObject,
827    file: S,
828    len: u64,
829    checksum: u64,
830    entry_count: usize,
831    analyzer_digest: u64,
832}
833
834#[derive(Debug, Serialize, Deserialize)]
835#[serde(deny_unknown_fields)]
836struct SearchOutOfCoreManifestEnvelope {
837    body: SearchOutOfCoreManifestBody,
838    checksum: u64,
839}
840
841#[derive(Debug, Serialize, Deserialize)]
842#[serde(deny_unknown_fields)]
843struct SearchOutOfCoreLayoutEnvelope {
844    body: SearchOutOfCoreLayoutBody,
845    checksum: u64,
846}
847
848#[derive(Debug, Clone, Serialize, Deserialize)]
849#[serde(deny_unknown_fields)]
850struct SearchOutOfCoreLayoutBody {
851    format: String,
852    generation: u64,
853    document_count: usize,
854    segments: Vec<SearchOutOfCoreSegmentLayout>,
855}
856
857#[derive(Debug, Clone, Serialize, Deserialize)]
858#[serde(deny_unknown_fields)]
859struct SearchOutOfCoreSegmentLayout {
860    segment_id: u64,
861    vector_ordinal_base: u64,
862    metadata: SearchOutOfCoreRange,
863    vectors: SearchOutOfCoreRange,
864    /// Follows `metadata` in the metadata artifact. Absent in V2 layouts and
865    /// for segments whose postings exceed the segment byte limit.
866    #[serde(default, skip_serializing_if = "Option::is_none")]
867    postings: Option<SearchOutOfCoreRange>,
868}
869
870#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
871#[serde(deny_unknown_fields)]
872struct SearchOutOfCoreRange {
873    offset: u64,
874    length: u64,
875    checksum: u64,
876    entry_count: usize,
877}
878
879#[derive(Debug)]
880struct SearchMetadataDocument {
881    id: String,
882    vector_ordinal: Option<u64>,
883    metadata: BTreeMap<String, String>,
884}
885
886#[derive(Debug)]
887struct SearchVectorDocument {
888    id: String,
889    embedding: Vec<f32>,
890}
891
892#[derive(Clone, Copy)]
893pub struct SearchOutOfCoreExecutionContext<'a> {
894    pub access_control: Option<&'a SearchAccessControlContext>,
895    pub compressed_vector_search_mode: CompressedVectorSearchMode,
896    pub vector_execution_options: VectorSearchExecutionOptions<'a>,
897}
898
899impl Default for SearchOutOfCoreExecutionContext<'_> {
900    fn default() -> Self {
901        Self::scalar()
902    }
903}
904
905impl SearchOutOfCoreExecutionContext<'_> {
906    fn scalar() -> Self {
907        Self {
908            access_control: None,
909            compressed_vector_search_mode: CompressedVectorSearchMode::Disabled,
910            vector_execution_options: VectorSearchExecutionOptions::default(),
911        }
912    }
913}
914
915impl SearchOutOfCoreManifestBody {
916    /// Reserve before serde can grow either vector, including invalid inputs
917    /// rejected only after decoding. Each record opens a JSON map or sequence.
918    /// Include validation's ID sets as well as the largest owned record type.
919    fn decode_capacity(bytes: &[u8], task: &hawdb_core::RuntimeTaskContext) -> Result<usize> {
920        use crate::build_memory::{checked_add, SET_ENTRY_BYTES};
921        let element = std::mem::size_of::<SearchOutOfCoreSegmentManifest>()
922            .max(std::mem::size_of::<SearchOutOfCoreMutationRunManifest>());
923        checked_add(
924            crate::build_control::json::decode_capacity(
925                bytes,
926                checked_add(element, SET_ENTRY_BYTES)?,
927                2,
928                task,
929            )?,
930            3 * 128,
931        )
932    }
933
934    fn encode(&self) -> Result<Vec<u8>> {
935        let mut manifest = self.clone();
936        manifest.stamp_reader_version();
937        manifest.validate_names()?;
938        let body = serde_json::to_vec(&manifest).map_err(|error| {
939            HawDBError::or_stop(&error, || {
940                HawDBError::Storage(format!(
941                    "failed to encode search out-of-core manifest: {error}"
942                ))
943            })
944        })?;
945        serde_json::to_vec(&SearchOutOfCoreManifestEnvelope {
946            body: manifest,
947            checksum: checksum_bytes(&body),
948        })
949        .map_err(|error| {
950            HawDBError::or_stop(&error, || {
951                HawDBError::Storage(format!(
952                    "failed to encode search out-of-core manifest envelope: {error}"
953                ))
954            })
955        })
956    }
957
958    fn decode(bytes: &[u8]) -> Result<Self> {
959        Self::decode_with_context(bytes, None)
960    }
961
962    fn decode_with_context(
963        bytes: &[u8],
964        task: Option<&hawdb_core::RuntimeTaskContext>,
965    ) -> Result<Self> {
966        Self::decode_for_reader_version(bytes, task, manifest_version::READER_VERSION)
967    }
968
969    /// Decode as a reader of selector version `supported`. A selector that
970    /// requires a newer reader is refused before its fields are decoded.
971    fn decode_for_reader_version(
972        bytes: &[u8],
973        task: Option<&hawdb_core::RuntimeTaskContext>,
974        supported: u16,
975    ) -> Result<Self> {
976        manifest_version::check_reader_version(bytes, supported)?;
977        let envelope = serde_json::from_slice::<SearchOutOfCoreManifestEnvelope>(bytes);
978        task.map_or(Ok(()), crate::build_control::checkpoint)?;
979        let envelope = envelope.map_err(|error| {
980            HawDBError::or_stop(&error, || {
981                HawDBError::Storage(format!("invalid search out-of-core manifest: {error}"))
982            })
983        })?;
984        if crate::build_control::json::checksum_with_context(&envelope.body, task)?
985            != envelope.checksum
986        {
987            return Err(HawDBError::Storage(
988                "search out-of-core manifest checksum mismatch".to_string(),
989            ));
990        }
991        envelope.body.validate_names_with_context(task)?;
992        Ok(envelope.body)
993    }
994
995    /// The lowest selector version that understands every field present.
996    /// Each optional field added after version 1 raises it only while the
997    /// field is present, so a selector without one stays readable by the
998    /// base reader.
999    fn required_reader_version(&self) -> u16 {
1000        if self
1001            .segments
1002            .iter()
1003            .any(|segment| segment.descriptor_version.is_some())
1004        {
1005            manifest_version::VALUE_SUMMARY_VERSION
1006        } else if self
1007            .segments
1008            .iter()
1009            .any(|segment| !segment.content_encoding.is_stream1())
1010        {
1011            manifest_version::CONTENT_BLOCKS_VERSION
1012        } else if self.content_source_graph_commit_epoch.is_some() {
1013            manifest_version::CONTENT_EPOCH_VERSION
1014        } else {
1015            manifest_version::BASE_VERSION
1016        }
1017    }
1018
1019    /// Set the version fields from the fields present. Every writer stamps
1020    /// the selector before it is serialized.
1021    fn stamp_reader_version(&mut self) {
1022        self.min_reader_version = self.required_reader_version();
1023        self.format_version = if self.min_reader_version == manifest_version::BASE_VERSION {
1024            manifest_version::BASE_VERSION
1025        } else {
1026            manifest_version::READER_VERSION
1027        };
1028    }
1029}
1030
1031/// Check the producer's declared artifact closure against the Consumer's
1032/// immutable references. The caller owns admission for `decode_capacity`, the
1033/// manifest bytes and the artifact list before invoking this validator.
1034pub(crate) fn validate_consumer_manifest_artifacts(
1035    bytes: &[u8],
1036    source_epoch: u64,
1037    artifacts: &[crate::consumer::generation_metadata::ArtifactReference<'_>],
1038    task: &hawdb_core::RuntimeTaskContext,
1039) -> Result<bool> {
1040    let manifest = SearchOutOfCoreManifestBody::decode_with_context(bytes, Some(task))?;
1041    if manifest.source_graph_commit_epoch != Some(source_epoch)
1042        || (manifest.resident_snapshot.is_none() && !manifest.resident_snapshot_absent)
1043    {
1044        return Err(HawDBError::StorageIntegrity(
1045            "consumer candidate manifest lacks the requested source epoch or resident absence proof"
1046                .into(),
1047        ));
1048    }
1049    let require = |name: &str, object: ArtifactObject| -> Result<()> {
1050        let index = artifacts
1051            .binary_search_by(|artifact| artifact.name.cmp(name))
1052            .map_err(|_| {
1053                HawDBError::StorageIntegrity(
1054                    "consumer candidate omits an artifact declared by its Search manifest".into(),
1055                )
1056            })?;
1057        if artifacts[index].reference != object.reference() {
1058            return Err(HawDBError::StorageIntegrity(
1059                "consumer candidate artifact reference differs from its Search manifest".into(),
1060            ));
1061        }
1062        Ok(())
1063    };
1064    if let Some(snapshot) = manifest.resident_snapshot {
1065        require(crate::SEARCH_SNAPSHOT_FILE, snapshot.object)?;
1066    }
1067    for segment in &manifest.segments {
1068        crate::build_control::checkpoint(task)?;
1069        for (name, object) in [
1070            (segment.descriptor_file.as_str(), segment.objects.descriptor),
1071            (segment.payload_file.as_str(), segment.objects.payload),
1072            (
1073                segment.metadata_payload_file.as_str(),
1074                segment.objects.metadata,
1075            ),
1076            (segment.vector_payload_file.as_str(), segment.objects.vector),
1077            (segment.layout_file.as_str(), segment.objects.layout),
1078            (
1079                segment.lexical_manifest_file.as_str(),
1080                segment.objects.lexical_manifest,
1081            ),
1082        ] {
1083            require(name, object)?;
1084        }
1085        require(
1086            &crate::lexical_projection::artifact_file(segment.objects.lexical_generation),
1087            segment.objects.lexical_payload,
1088        )?;
1089        if let Some(name) = &segment.rabitq_artifact_file {
1090            require(
1091                name,
1092                segment.objects.rabitq.ok_or_else(|| {
1093                    HawDBError::StorageIntegrity(
1094                        "consumer candidate manifest has an unbound RaBitQ artifact".into(),
1095                    )
1096                })?,
1097            )?;
1098        }
1099    }
1100    for run in &manifest.mutation_runs {
1101        crate::build_control::checkpoint(task)?;
1102        require(&run.file, run.object)?;
1103    }
1104    for artifact in artifacts {
1105        crate::build_control::checkpoint(task)?;
1106        let declared = (artifact.name == crate::SEARCH_SNAPSHOT_FILE
1107            && manifest.resident_snapshot.is_some())
1108            || manifest
1109                .segments
1110                .iter()
1111                .any(|segment| segment.object_for(artifact.name).is_some())
1112            || manifest
1113                .mutation_runs
1114                .iter()
1115                .any(|run| run.file == artifact.name);
1116        if !declared {
1117            return Err(HawDBError::StorageIntegrity(
1118                "consumer candidate contains an artifact absent from its Search manifest".into(),
1119            ));
1120        }
1121    }
1122    Ok(manifest.resident_snapshot_absent)
1123}
1124
1125/// Recover the producer's complete declared closure through its retained root.
1126pub(crate) struct ConsumerProducerReferences {
1127    pub manifest: hawdb_storage::immutable_object::ObjectReference,
1128    pub artifacts: Vec<(String, hawdb_storage::immutable_object::ObjectReference)>,
1129}
1130
1131pub(crate) fn consumer_producer_references(
1132    publication: &SearchProjectionPublishLease,
1133) -> Result<ConsumerProducerReferences> {
1134    use hawdb_storage::immutable_object::{ObjectKind, ObjectReference};
1135    let bytes = crate::bounded_file::read_bounded_open_file(
1136        publication.open_captured_child(OUT_OF_CORE_MANIFEST_FILE)?,
1137        OUT_OF_CORE_MANIFEST_FILE,
1138        MAX_OUT_OF_CORE_MANIFEST_BYTES,
1139    )?;
1140    let manifest = SearchOutOfCoreManifestBody::decode(&bytes)?;
1141    let mut artifacts = BTreeMap::new();
1142    if let Some(snapshot) = manifest.resident_snapshot {
1143        artifacts.insert(
1144            crate::SEARCH_SNAPSHOT_FILE.to_owned(),
1145            snapshot.object.reference(),
1146        );
1147    }
1148    for segment in &manifest.segments {
1149        for (name, object) in [
1150            (&segment.descriptor_file, segment.objects.descriptor),
1151            (&segment.payload_file, segment.objects.payload),
1152            (&segment.metadata_payload_file, segment.objects.metadata),
1153            (&segment.vector_payload_file, segment.objects.vector),
1154            (&segment.layout_file, segment.objects.layout),
1155            (
1156                &segment.lexical_manifest_file,
1157                segment.objects.lexical_manifest,
1158            ),
1159        ] {
1160            artifacts.insert(name.clone(), object.reference());
1161        }
1162        artifacts.insert(
1163            crate::lexical_projection::artifact_file(segment.objects.lexical_generation),
1164            segment.objects.lexical_payload.reference(),
1165        );
1166        if let Some(name) = &segment.rabitq_artifact_file {
1167            artifacts.insert(
1168                name.clone(),
1169                segment
1170                    .objects
1171                    .rabitq
1172                    .ok_or_else(|| {
1173                        HawDBError::StorageIntegrity("missing producer vector reference".into())
1174                    })?
1175                    .reference(),
1176            );
1177        }
1178    }
1179    for run in &manifest.mutation_runs {
1180        artifacts.insert(run.file.clone(), run.object.reference());
1181    }
1182    Ok(ConsumerProducerReferences {
1183        manifest: ObjectReference::for_bytes(ObjectKind::CheckpointArtifact, 1, &bytes),
1184        artifacts: artifacts.into_iter().collect(),
1185    })
1186}
1187
1188pub(crate) fn consumer_manifest_decode_capacity(
1189    bytes: &[u8],
1190    task: &hawdb_core::RuntimeTaskContext,
1191) -> Result<usize> {
1192    SearchOutOfCoreManifestBody::decode_capacity(bytes, task)
1193}
1194
1195impl<S: AsRef<str>> SearchOutOfCoreManifestBody<S> {
1196    fn validate_names(&self) -> Result<()> {
1197        self.validate_names_with_context(None)
1198    }
1199    fn validate_names_with_context(
1200        &self,
1201        task: Option<&hawdb_core::RuntimeTaskContext>,
1202    ) -> Result<()> {
1203        task.map_or(Ok(()), crate::build_control::checkpoint)?;
1204
1205        if self.format.as_ref() != OUT_OF_CORE_FORMAT
1206            || self.min_reader_version < manifest_version::BASE_VERSION
1207            || self.min_reader_version > manifest_version::READER_VERSION
1208            || self.format_version < self.min_reader_version
1209            || self.generation == 0
1210            || self.segments.is_empty()
1211        {
1212            return Err(HawDBError::Storage(
1213                "search out-of-core manifest header or segment set is invalid".to_string(),
1214            ));
1215        }
1216        if self.resident_snapshot_absent && self.resident_snapshot.is_some() {
1217            return Err(HawDBError::StorageIntegrity(
1218                "conflicting resident snapshot ownership states".into(),
1219            ));
1220        }
1221        if let Some(content) = self.content_source_graph_commit_epoch
1222            && !self
1223                .source_graph_commit_epoch
1224                .is_some_and(|source| content < source)
1225        {
1226            return Err(HawDBError::StorageIntegrity(
1227                "search out-of-core manifest advances its source epoch backwards".into(),
1228            ));
1229        }
1230        if self
1231            .resident_snapshot
1232            .is_some_and(|snapshot| snapshot.metadata_only)
1233            && self.vector_index_binding.is_none()
1234        {
1235            return Err(HawDBError::StorageIntegrity(
1236                "metadata-only snapshot requires a vector index binding".into(),
1237            ));
1238        }
1239        self.vector_scoring
1240            .validate(self.vector_index_binding.is_some())?;
1241        if let Some(encoded) = &self.vector_index_binding {
1242            let descriptor = crate::vector_index::decode(encoded.as_ref())?;
1243            if self.embedding_dimension != Some(descriptor.dimension().get() as usize) {
1244                return Err(HawDBError::StorageIntegrity(
1245                    "vector index manifest dimension mismatch".into(),
1246                ));
1247            }
1248        }
1249        let mut ids = BTreeSet::new();
1250        let mut content_document_count = 0usize;
1251        for segment in &self.segments {
1252            task.map_or(Ok(()), crate::build_control::checkpoint)?;
1253            if !ids.insert(segment.segment_id) {
1254                return Err(HawDBError::Storage(
1255                    "search out-of-core manifest has duplicate segment ids".to_string(),
1256                ));
1257            }
1258            content_document_count = content_document_count
1259                .checked_add(segment.document_count)
1260                .ok_or_else(|| {
1261                    HawDBError::Storage(
1262                        "search out-of-core manifest document count overflows".to_string(),
1263                    )
1264                })?;
1265            segment.validate_names()?;
1266        }
1267        let mut mutation_generations = BTreeSet::new();
1268        for run in &self.mutation_runs {
1269            task.map_or(Ok(()), crate::build_control::checkpoint)?;
1270            if run.generation > self.generation || !mutation_generations.insert(run.generation) {
1271                return Err(HawDBError::Storage(
1272                    "search out-of-core manifest has an invalid mutation-run generation"
1273                        .to_string(),
1274                ));
1275            }
1276            run.validate_names()?;
1277        }
1278        if self.document_count > content_document_count
1279            || (self.mutation_runs.is_empty() && content_document_count != self.document_count)
1280        {
1281            return Err(HawDBError::Storage(
1282                "search out-of-core manifest document count does not match its artifact closure"
1283                    .to_string(),
1284            ));
1285        }
1286        Ok(())
1287    }
1288}
1289
1290impl<S: AsRef<str>> SearchOutOfCoreMutationRunManifest<S> {
1291    fn validate_names(&self) -> Result<()> {
1292        if self.generation == 0
1293            || self.len == 0
1294            || self.entry_count == 0
1295            || self.object.byte_length != self.len
1296        {
1297            return Err(HawDBError::Storage(
1298                "search out-of-core mutation-run manifest metadata is invalid".to_string(),
1299            ));
1300        }
1301        let name = self.file.as_ref();
1302        if Path::new(name).file_name().and_then(|value| value.to_str()) != Some(name)
1303            || name != mutation_run::artifact_file(self.generation)
1304        {
1305            return Err(HawDBError::Storage(
1306                "search out-of-core manifest contains an invalid mutation-run artifact name"
1307                    .to_string(),
1308            ));
1309        }
1310        Ok(())
1311    }
1312}
1313
1314impl<S: AsRef<str>> SearchOutOfCoreSegmentManifest<S> {
1315    fn validate_names(&self) -> Result<()> {
1316        self.objects.validate(self)?;
1317        if self.generation == 0 {
1318            return Err(HawDBError::Storage(
1319                "search out-of-core segment generation is invalid".to_string(),
1320            ));
1321        }
1322        for name in [
1323            self.descriptor_file.as_ref(),
1324            self.payload_file.as_ref(),
1325            self.metadata_payload_file.as_ref(),
1326            self.vector_payload_file.as_ref(),
1327            self.layout_file.as_ref(),
1328            self.lexical_manifest_file.as_ref(),
1329        ] {
1330            if Path::new(name).file_name().and_then(|value| value.to_str()) != Some(name) {
1331                return Err(HawDBError::Storage(
1332                    "search out-of-core manifest contains an invalid artifact name".to_string(),
1333                ));
1334            }
1335        }
1336        if let Some(name) = self.rabitq_artifact_file.as_ref().map(AsRef::as_ref)
1337            && Path::new(name).file_name().and_then(|value| value.to_str()) != Some(name)
1338        {
1339            return Err(HawDBError::Storage(
1340                "search out-of-core manifest contains an invalid RaBitQ artifact name".to_string(),
1341            ));
1342        }
1343        if self.descriptor_file.as_ref()
1344            != format!("search_projection_segments.{}.hawdb", self.generation)
1345            || self.payload_file.as_ref()
1346                != format!(
1347                    "search_projection_segment_payloads.{}.hawdb",
1348                    self.generation
1349                )
1350            || self.metadata_payload_file.as_ref()
1351                != format!(
1352                    "search_projection_metadata_payloads.{}.hawdb",
1353                    self.generation
1354                )
1355            || self.vector_payload_file.as_ref()
1356                != format!(
1357                    "search_projection_vector_payloads.{}.hawdb",
1358                    self.generation
1359                )
1360            || self.layout_file.as_ref()
1361                != format!(
1362                    "search_projection_out_of_core_layout.{}.hawdb",
1363                    self.generation
1364                )
1365            || self.lexical_manifest_file.as_ref()
1366                != format!("search_lexical.manifest.{}.hawdb", self.generation)
1367        {
1368            return Err(HawDBError::Storage(
1369                "search out-of-core manifest artifact names do not match its generation"
1370                    .to_string(),
1371            ));
1372        }
1373        let rabitq_fields = [
1374            self.rabitq_artifact_file.is_some(),
1375            self.rabitq_artifact_len.is_some(),
1376            self.rabitq_artifact_checksum.is_some(),
1377            self.rabitq_source_digest.is_some(),
1378            self.rabitq_vector_document_count.is_some(),
1379            self.rabitq_payload_checksum.is_some(),
1380            self.rabitq_peak_build_working_bytes.is_some(),
1381        ];
1382        if rabitq_fields.iter().any(|present| *present)
1383            && rabitq_fields.iter().any(|present| !*present)
1384        {
1385            return Err(HawDBError::Storage(
1386                "search out-of-core manifest has an incomplete RaBitQ identity".to_string(),
1387            ));
1388        }
1389        if self.diskann_source_digest.is_some() && self.rabitq_artifact_file.is_none() {
1390            return Err(HawDBError::StorageIntegrity(
1391                "DiskANN identity has no candidate artifact".into(),
1392            ));
1393        }
1394        if let Some(name) = self.rabitq_artifact_file.as_ref().map(AsRef::as_ref)
1395            && name != format!("search_rabitq.{}.hawdb", self.generation)
1396        {
1397            return Err(HawDBError::Storage(
1398                "search out-of-core RaBitQ artifact does not match its generation".to_string(),
1399            ));
1400        }
1401        Ok(())
1402    }
1403}
1404
1405impl SearchOutOfCoreLayoutBody {
1406    fn encode(&self) -> Result<Vec<u8>> {
1407        let body = serde_json::to_vec(self).map_err(|error| {
1408            HawDBError::or_stop(&error, || {
1409                HawDBError::Storage(format!(
1410                    "failed to encode search out-of-core layout: {error}"
1411                ))
1412            })
1413        })?;
1414        serde_json::to_vec(&SearchOutOfCoreLayoutEnvelope {
1415            body: self.clone(),
1416            checksum: checksum_bytes(&body),
1417        })
1418        .map_err(|error| {
1419            HawDBError::or_stop(&error, || {
1420                HawDBError::Storage(format!(
1421                    "failed to encode search out-of-core layout envelope: {error}"
1422                ))
1423            })
1424        })
1425    }
1426
1427    fn decode(bytes: &[u8]) -> Result<Self> {
1428        Self::decode_with_context(bytes, None)
1429    }
1430
1431    fn decode_with_context(
1432        bytes: &[u8],
1433        task: Option<&hawdb_core::RuntimeTaskContext>,
1434    ) -> Result<Self> {
1435        task.map_or(Ok(()), crate::build_control::checkpoint)?;
1436        let envelope = serde_json::from_slice::<SearchOutOfCoreLayoutEnvelope>(bytes);
1437        task.map_or(Ok(()), crate::build_control::checkpoint)?;
1438        let envelope = envelope.map_err(|error| {
1439            HawDBError::or_stop(&error, || {
1440                HawDBError::Storage(format!("invalid search out-of-core layout: {error}"))
1441            })
1442        })?;
1443        let checksum = crate::build_control::json::checksum_with_context(&envelope.body, task);
1444        // CheckedWriter reports cancellation through serde's I/O error. Keep
1445        // that execution outcome from being classified as corrupt storage.
1446        task.map_or(Ok(()), crate::build_control::checkpoint)?;
1447        if checksum? != envelope.checksum {
1448            return Err(HawDBError::Storage(
1449                "search out-of-core layout checksum mismatch".into(),
1450            ));
1451        }
1452        Ok(envelope.body)
1453    }
1454
1455    fn validate(
1456        &self,
1457        manifest: &SearchOutOfCoreSegmentManifest,
1458        descriptor: &SearchSegmentDescriptor,
1459        max_compressed_segment_bytes: u64,
1460    ) -> Result<()> {
1461        if SUPERSEDED_OUT_OF_CORE_LAYOUT_FORMATS.contains(&self.format.as_str()) {
1462            return Err(HawDBError::Storage(format!(
1463                "search out-of-core layout {} uses a superseded vector sidecar format; \
1464                 rebuild the search projection to publish {OUT_OF_CORE_LAYOUT_FORMAT}",
1465                self.format
1466            )));
1467        }
1468        let postingless = self.format == POSTINGLESS_OUT_OF_CORE_LAYOUT_FORMAT;
1469        let legacy_postings = self.format == LEGACY_POSTINGS_OUT_OF_CORE_LAYOUT_FORMAT;
1470        if (self.format != OUT_OF_CORE_LAYOUT_FORMAT && !legacy_postings && !postingless)
1471            || (postingless && self.segments.iter().any(|layout| layout.postings.is_some()))
1472            || self.generation != manifest.generation
1473            || self.document_count != manifest.document_count
1474            || self.segments.len() != descriptor.segments.len()
1475        {
1476            return Err(HawDBError::Storage(
1477                "search out-of-core layout header does not match its manifest or descriptor"
1478                    .to_string(),
1479            ));
1480        }
1481        let mut metadata_end = 0u64;
1482        let mut vector_end = 0u64;
1483        let mut vector_ordinal_base = 0u64;
1484        for (layout, segment) in self.segments.iter().zip(&descriptor.segments) {
1485            if layout.segment_id != segment.segment_id
1486                || layout.vector_ordinal_base != vector_ordinal_base
1487                || layout.metadata.entry_count != segment.document_count
1488                || layout.vectors.entry_count > segment.document_count
1489            {
1490                return Err(HawDBError::Storage(format!(
1491                    "search out-of-core layout does not match segment {}",
1492                    segment.segment_id
1493                )));
1494            }
1495            validate_out_of_core_range(
1496                layout.metadata,
1497                metadata_end,
1498                manifest.metadata_payload_len,
1499                max_compressed_segment_bytes,
1500                segment.segment_id,
1501                "metadata",
1502            )?;
1503            validate_out_of_core_range(
1504                layout.vectors,
1505                vector_end,
1506                manifest.vector_payload_len,
1507                max_compressed_segment_bytes,
1508                segment.segment_id,
1509                "vector",
1510            )?;
1511            metadata_end = layout.metadata.offset + layout.metadata.length;
1512            if let Some(postings) = layout.postings {
1513                if postings.entry_count != segment.document_count {
1514                    return Err(HawDBError::Storage(format!(
1515                        "search out-of-core layout postings do not match segment {}",
1516                        segment.segment_id
1517                    )));
1518                }
1519                // Postings are optional: a range over this reader's segment
1520                // budget is not an error; the reader scans that segment's
1521                // metadata instead (`visit_postings_segment`).
1522                validate_out_of_core_range(
1523                    postings,
1524                    metadata_end,
1525                    manifest.metadata_payload_len,
1526                    u64::MAX,
1527                    segment.segment_id,
1528                    "postings",
1529                )?;
1530                metadata_end = postings.offset + postings.length;
1531            }
1532            vector_end = layout.vectors.offset + layout.vectors.length;
1533            vector_ordinal_base = vector_ordinal_base
1534                .checked_add(layout.vectors.entry_count as u64)
1535                .ok_or_else(|| {
1536                    HawDBError::Storage("search vector ordinal range overflow".to_string())
1537                })?;
1538        }
1539        if metadata_end != manifest.metadata_payload_len
1540            || vector_end != manifest.vector_payload_len
1541        {
1542            return Err(HawDBError::Storage(
1543                "search out-of-core sidecar layout does not cover its payload files".to_string(),
1544            ));
1545        }
1546        Ok(())
1547    }
1548}
1549
1550impl SearchOutOfCoreSegmentReader {
1551    fn validate_pinned_paths(
1552        &self,
1553        root: &Path,
1554        manifest: &SearchOutOfCoreSegmentManifest,
1555    ) -> Result<()> {
1556        let lexical_file =
1557            crate::lexical_projection::artifact_file(self.lexical_projection.generation());
1558        for (file, expected_len) in [
1559            (manifest.descriptor_file.as_str(), manifest.descriptor_len),
1560            (manifest.payload_file.as_str(), manifest.payload_len),
1561            (
1562                manifest.metadata_payload_file.as_str(),
1563                manifest.metadata_payload_len,
1564            ),
1565            (
1566                manifest.vector_payload_file.as_str(),
1567                manifest.vector_payload_len,
1568            ),
1569            (manifest.layout_file.as_str(), manifest.layout_len),
1570            (
1571                manifest.lexical_manifest_file.as_str(),
1572                manifest.lexical_manifest_len,
1573            ),
1574            (
1575                lexical_file.as_str(),
1576                self.lexical_projection.artifact_len(),
1577            ),
1578        ] {
1579            if fs::metadata(root.join(file))?.len() != expected_len {
1580                return Err(HawDBError::Storage(
1581                    "pinned search artifact length changed".into(),
1582                ));
1583            }
1584        }
1585        if let Some((file, expected_len)) = manifest
1586            .rabitq_artifact_file
1587            .as_deref()
1588            .zip(manifest.rabitq_artifact_len)
1589            && fs::metadata(root.join(file))?.len() != expected_len
1590        {
1591            return Err(HawDBError::Storage(
1592                "pinned RaBitQ artifact length changed".into(),
1593            ));
1594        }
1595        Ok(())
1596    }
1597
1598    #[cfg(test)]
1599    fn open(
1600        root: &Path,
1601        config: &SearchOutOfCoreConfig,
1602        analyzer_lexicon: &SearchAnalyzerLexicon,
1603        lexical_source_policy: SearchLexicalSourcePolicy,
1604        lexical_term_policy: SearchLexicalTermPolicy,
1605        active_manifest: &SearchOutOfCoreManifestBody,
1606        manifest: &SearchOutOfCoreSegmentManifest,
1607    ) -> Result<Self> {
1608        Self::open_with_read_admission(
1609            SegmentOpenContext {
1610                cleanup_source: None,
1611                capture: None,
1612                root,
1613                config,
1614                analyzer_lexicon,
1615                lexical_source_policy,
1616                lexical_term_policy,
1617                active_manifest,
1618                admission: None,
1619                max_artifact_read_bytes: u64::MAX,
1620            },
1621            manifest,
1622        )
1623    }
1624
1625    fn open_with_read_admission(
1626        context: SegmentOpenContext<'_>,
1627        manifest: &SearchOutOfCoreSegmentManifest,
1628    ) -> Result<Self> {
1629        let SegmentOpenContext {
1630            cleanup_source,
1631            capture,
1632            root,
1633            config,
1634            analyzer_lexicon,
1635            lexical_source_policy,
1636            lexical_term_policy,
1637            active_manifest,
1638            admission,
1639            max_artifact_read_bytes,
1640        } = context;
1641        if cleanup_source.is_some()
1642            && (capture.is_some() || admission.is_some_and(|admission| !admission.is_synchronous()))
1643        {
1644            return Err(HawDBError::Execution(
1645                "incompatible captured cleanup/read admission modes".into(),
1646            ));
1647        }
1648        if admission.is_some_and(|admission| admission.is_synchronous()) && cleanup_source.is_none()
1649        {
1650            return Err(HawDBError::Execution(
1651                "synchronous metadata requires captured publication custody".into(),
1652            ));
1653        }
1654        let reader_memory = admission
1655            .map(|context| {
1656                use crate::build_memory::{
1657                    checked_add as add, checked_mul as mul, reserved::native_path,
1658                };
1659                let native = mul(add(native_path::bytes(root)?, 4096)?, 4)?;
1660                context.retained(add(
1661                    add(
1662                        std::mem::size_of::<SegmentReaderContents>(),
1663                        2 * std::mem::size_of::<usize>(),
1664                    )?,
1665                    native,
1666                )?)
1667            })
1668            .transpose()?;
1669        let source_pins = match capture {
1670            Some(capture) => capture.pin_segment(manifest)?,
1671            None => [None, None, None],
1672        };
1673        #[cfg(not(feature = "vector-search"))]
1674        let _ = active_manifest;
1675        let read_captured = |name: &str, object: ArtifactObject, checksum: u64, maximum: u64| {
1676            let capture = capture.expect("captured branch owns source custody");
1677            let admission = admission.expect("captured branch owns read admission");
1678            admission.require_read_limit(object.byte_length, max_artifact_read_bytes)?;
1679            let file = capture.open_artifact(name, object.reference())?;
1680            admission.read_file_range(
1681                &file,
1682                object.byte_length,
1683                maximum,
1684                crate::build_memory::read::FileRange {
1685                    offset: 0,
1686                    length: object.byte_length,
1687                    checksum,
1688                },
1689            )
1690        };
1691        let descriptor_path = match admission {
1692            Some(context) => Some(crate::build_memory::path::OwnedPath::join(
1693                root,
1694                Path::new(&manifest.descriptor_file),
1695                context.memory,
1696                context.task,
1697            )?),
1698            None => None,
1699        };
1700        let descriptor_bytes = match admission {
1701            Some(_) if capture.is_some() => read_captured(
1702                &manifest.descriptor_file,
1703                manifest.objects.descriptor,
1704                manifest.descriptor_checksum,
1705                config.max_descriptor_bytes.get(),
1706            )?,
1707            Some(context) if cleanup_source.is_some() => cleanup_source.unwrap().read_admitted(
1708                &manifest.descriptor_file,
1709                manifest.objects.descriptor,
1710                manifest.descriptor_checksum,
1711                config.max_descriptor_bytes.get(),
1712                context,
1713            )?,
1714            Some(context) => {
1715                context.require_read_limit(manifest.descriptor_len, max_artifact_read_bytes)?;
1716                context.read_bound(
1717                    descriptor_path.as_ref().expect("admitted path"),
1718                    manifest.descriptor_len,
1719                    manifest.descriptor_checksum,
1720                    config.max_descriptor_bytes.get(),
1721                )?
1722            }
1723
1724            None if cleanup_source.is_some() => {
1725                crate::build_memory::read::ReadBytes::unaccounted(cleanup_source.unwrap().read(
1726                    &manifest.descriptor_file,
1727                    manifest.objects.descriptor,
1728                    manifest.descriptor_checksum,
1729                    config.max_descriptor_bytes.get(),
1730                )?)
1731            }
1732            None => crate::build_memory::read::ReadBytes::unaccounted(read_bound_artifact(
1733                &root.join(&manifest.descriptor_file),
1734                manifest.descriptor_len,
1735                manifest.descriptor_checksum,
1736                config.max_descriptor_bytes.get(),
1737                "search segment descriptor",
1738            )?),
1739        };
1740        let descriptor_text = std::str::from_utf8(&descriptor_bytes).map_err(|error| {
1741            HawDBError::or_stop(&error, || {
1742                HawDBError::Storage(format!("search segment descriptor is not UTF-8: {error}"))
1743            })
1744        })?;
1745        let v4 = descriptor_text.starts_with(crate::SEARCH_SEGMENT_DESCRIPTOR_V4_HEADER)
1746            && descriptor_text[crate::SEARCH_SEGMENT_DESCRIPTOR_V4_HEADER.len()..]
1747                .starts_with('\n');
1748        match manifest.descriptor_version {
1749            None if !v4 => {}
1750            Some(VALUE_SUMMARY_DESCRIPTOR_VERSION) if v4 => {}
1751            version => {
1752                return Err(HawDBError::Storage(format!(
1753                    "search segment descriptor grammar does not match manifest descriptor version {version:?}"
1754                )))
1755            }
1756        }
1757        let descriptor =
1758            crate::document_encoding::DecodedDescriptor::decode(descriptor_text, admission)?;
1759        drop(descriptor_bytes);
1760        drop(descriptor_path);
1761        if descriptor.document_count != manifest.document_count {
1762            return Err(HawDBError::Storage(format!(
1763                "search out-of-core manifest expects {} documents, descriptor has {}",
1764                manifest.document_count, descriptor.document_count
1765            )));
1766        }
1767        for segment in &descriptor.segments {
1768            let range = segment.payload_range.ok_or_else(|| {
1769                HawDBError::Storage(format!(
1770                    "search segment {} has no physical payload range",
1771                    segment.segment_id
1772                ))
1773            })?;
1774            if range.length > config.max_compressed_segment_bytes.get() {
1775                return Err(HawDBError::Storage(format!(
1776                    "search segment {} requires {} compressed bytes, exceeding {}",
1777                    segment.segment_id, range.length, config.max_compressed_segment_bytes
1778                )));
1779            }
1780            if range.offset.saturating_add(range.length) > manifest.payload_len {
1781                return Err(HawDBError::Storage(format!(
1782                    "search segment {} exceeds the published payload length",
1783                    segment.segment_id
1784                )));
1785            }
1786        }
1787
1788        let payload = match admission {
1789            Some(context) if capture.is_some() => {
1790                context.require_read_limit(manifest.payload_len, max_artifact_read_bytes)?;
1791                capture
1792                    .unwrap()
1793                    .open_artifact(&manifest.payload_file, manifest.objects.payload.reference())?
1794            }
1795            Some(context) if cleanup_source.is_some() => cleanup_source.unwrap().open_admitted(
1796                &manifest.payload_file,
1797                manifest.objects.payload,
1798                context,
1799            )?,
1800            Some(context) => {
1801                let path = crate::build_memory::path::OwnedPath::join(
1802                    root,
1803                    Path::new(&manifest.payload_file),
1804                    context.memory,
1805                    context.task,
1806                )?;
1807                context.open_bound_length(&path, manifest.payload_len, max_artifact_read_bytes)?
1808            }
1809            None if cleanup_source.is_some() => cleanup_source
1810                .unwrap()
1811                .open(&manifest.payload_file, manifest.objects.payload)?,
1812            None => open_exact_length_artifact(
1813                &root.join(&manifest.payload_file),
1814                manifest.payload_len,
1815                "search out-of-core payload",
1816            )?,
1817        };
1818
1819        let layout_path = match admission {
1820            Some(context) => Some(crate::build_memory::path::OwnedPath::join(
1821                root,
1822                Path::new(&manifest.layout_file),
1823                context.memory,
1824                context.task,
1825            )?),
1826            None => None,
1827        };
1828        let layout_bytes = match admission {
1829            Some(_) if capture.is_some() => read_captured(
1830                &manifest.layout_file,
1831                manifest.objects.layout,
1832                manifest.layout_checksum,
1833                config.max_descriptor_bytes.get(),
1834            )?,
1835            Some(context) if cleanup_source.is_some() => cleanup_source.unwrap().read_admitted(
1836                &manifest.layout_file,
1837                manifest.objects.layout,
1838                manifest.layout_checksum,
1839                config.max_descriptor_bytes.get(),
1840                context,
1841            )?,
1842            Some(context) => {
1843                context.require_read_limit(manifest.layout_len, max_artifact_read_bytes)?;
1844                context.read_bound(
1845                    layout_path.as_ref().expect("admitted layout path"),
1846                    manifest.layout_len,
1847                    manifest.layout_checksum,
1848                    config.max_descriptor_bytes.get(),
1849                )?
1850            }
1851
1852            None if cleanup_source.is_some() => {
1853                crate::build_memory::read::ReadBytes::unaccounted(cleanup_source.unwrap().read(
1854                    &manifest.layout_file,
1855                    manifest.objects.layout,
1856                    manifest.layout_checksum,
1857                    config.max_descriptor_bytes.get(),
1858                )?)
1859            }
1860            None => crate::build_memory::read::ReadBytes::unaccounted(read_bound_artifact(
1861                &root.join(&manifest.layout_file),
1862                manifest.layout_len,
1863                manifest.layout_checksum,
1864                config.max_descriptor_bytes.get(),
1865                "search out-of-core layout",
1866            )?),
1867        };
1868        let layout_memory = admission
1869            .map(|context| {
1870                let bytes = crate::build_control::json::decode_capacity(
1871                    &layout_bytes,
1872                    std::mem::size_of::<SearchOutOfCoreSegmentLayout>(),
1873                    1,
1874                    context.task,
1875                )?;
1876                context.retained(bytes)
1877            })
1878            .transpose()?;
1879        let layout = match admission {
1880            Some(context) => {
1881                SearchOutOfCoreLayoutBody::decode_with_context(&layout_bytes, Some(context.task))?
1882            }
1883            None => SearchOutOfCoreLayoutBody::decode(&layout_bytes)?,
1884        };
1885        drop(layout_bytes);
1886        drop(layout_path);
1887        layout.validate(
1888            manifest,
1889            &descriptor,
1890            config.max_compressed_segment_bytes.get(),
1891        )?;
1892        let vector_count = manifest
1893            .rabitq_artifact_file
1894            .as_ref()
1895            .map(|_| {
1896                layout.segments.iter().try_fold(0usize, |count, segment| {
1897                    if let Some(context) = admission {
1898                        crate::build_control::checkpoint(context.task)?;
1899                    }
1900                    count
1901                        .checked_add(segment.vectors.entry_count)
1902                        .ok_or_else(|| {
1903                            HawDBError::Storage("search vector count exceeds address space".into())
1904                        })
1905                })
1906            })
1907            .transpose()?;
1908        if manifest.rabitq_vector_document_count != vector_count {
1909            return Err(HawDBError::Storage(
1910                "search out-of-core RaBitQ vector count does not match the sidecar layout"
1911                    .to_string(),
1912            ));
1913        }
1914
1915        let open_payload = |name: &str, object: ArtifactObject, label: &str| -> Result<File> {
1916            let len = object.byte_length;
1917            match admission {
1918                Some(context) if capture.is_some() => {
1919                    context.require_read_limit(len, max_artifact_read_bytes)?;
1920                    capture.unwrap().open_artifact(name, object.reference())
1921                }
1922                Some(context) if cleanup_source.is_some() => {
1923                    cleanup_source.unwrap().open_admitted(name, object, context)
1924                }
1925                Some(context) => {
1926                    let path = crate::build_memory::path::OwnedPath::join(
1927                        root,
1928                        Path::new(name),
1929                        context.memory,
1930                        context.task,
1931                    )?;
1932                    context.open_bound_length(&path, len, max_artifact_read_bytes)
1933                }
1934                None if cleanup_source.is_some() => cleanup_source.unwrap().open(name, object),
1935                None => open_exact_length_artifact(&root.join(name), len, label),
1936            }
1937        };
1938        let metadata_payload = open_payload(
1939            &manifest.metadata_payload_file,
1940            manifest.objects.metadata,
1941            "search out-of-core metadata payload",
1942        )?;
1943        let vector_payload = open_payload(
1944            &manifest.vector_payload_file,
1945            manifest.objects.vector,
1946            "search out-of-core vector payload",
1947        )?;
1948        let lexical_path = admission
1949            .map(|context| {
1950                crate::build_memory::path::OwnedPath::join(
1951                    root,
1952                    Path::new(&manifest.lexical_manifest_file),
1953                    context.memory,
1954                    context.task,
1955                )
1956            })
1957            .transpose()?;
1958        let lexical_manifest_bytes = match admission {
1959            Some(_) if capture.is_some() => read_captured(
1960                &manifest.lexical_manifest_file,
1961                manifest.objects.lexical_manifest,
1962                manifest.lexical_manifest_checksum,
1963                config.max_lexical_manifest_bytes.get(),
1964            )?,
1965            Some(context) if cleanup_source.is_some() => cleanup_source.unwrap().read_admitted(
1966                &manifest.lexical_manifest_file,
1967                manifest.objects.lexical_manifest,
1968                manifest.lexical_manifest_checksum,
1969                config.max_lexical_manifest_bytes.get(),
1970                context,
1971            )?,
1972            Some(context) => {
1973                context
1974                    .require_read_limit(manifest.lexical_manifest_len, max_artifact_read_bytes)?;
1975                context.read_bound(
1976                    lexical_path.as_ref().expect("admitted lexical path"),
1977                    manifest.lexical_manifest_len,
1978                    manifest.lexical_manifest_checksum,
1979                    config.max_lexical_manifest_bytes.get(),
1980                )?
1981            }
1982
1983            None if cleanup_source.is_some() => {
1984                crate::build_memory::read::ReadBytes::unaccounted(cleanup_source.unwrap().read(
1985                    &manifest.lexical_manifest_file,
1986                    manifest.objects.lexical_manifest,
1987                    manifest.lexical_manifest_checksum,
1988                    config.max_lexical_manifest_bytes.get(),
1989                )?)
1990            }
1991            None => crate::build_memory::read::ReadBytes::unaccounted(read_bound_artifact(
1992                &root.join(&manifest.lexical_manifest_file),
1993                manifest.lexical_manifest_len,
1994                manifest.lexical_manifest_checksum,
1995                config.max_lexical_manifest_bytes.get(),
1996                "search lexical manifest",
1997            )?),
1998        };
1999        let lexical_config = LexicalProjectionConfig {
2000            max_manifest_bytes: config.max_lexical_manifest_bytes,
2001            max_term_bytes: lexical_term_policy.max_term_bytes(),
2002            max_document_source_bytes: lexical_source_policy.max_document_source_bytes(),
2003            max_document_tokens: lexical_source_policy.max_document_tokens(),
2004            max_spill_bytes: config.max_reanalysis_spill_bytes,
2005            max_query_score_entries: config.max_score_entries,
2006            max_query_terms: config.max_lexical_query_terms,
2007            query_term_policy: config.lexical_query_term_policy,
2008            max_query_analyzed_terms: config.max_lexical_query_analyzed_terms,
2009            ..LexicalProjectionConfig::default()
2010        };
2011        let lexical_projection = match admission {
2012            Some(context) => LexicalProjectionReader::load_admitted_manifest_bytes(
2013                crate::lexical_projection::ReaderOpenContext {
2014                    captured_file: if let Some(source) = cleanup_source {
2015                        let _name = context.scratch(3 * 128)?;
2016                        let name = crate::lexical_projection::artifact_file(
2017                            manifest.objects.lexical_generation,
2018                        );
2019                        Some((
2020                            manifest.objects.lexical_generation,
2021                            source.open_admitted(
2022                                &name,
2023                                manifest.objects.lexical_payload,
2024                                context,
2025                            )?,
2026                        ))
2027                    } else {
2028                        capture
2029                            .map(|capture| -> Result<_> {
2030                                let _name_memory = context.scratch(3 * 128)?;
2031                                let name = crate::lexical_projection::artifact_file(
2032                                    manifest.objects.lexical_generation,
2033                                );
2034                                if name.capacity() > 128 {
2035                                    return Err(HawDBError::Execution(
2036                                        "lexical name exceeds admission".into(),
2037                                    ));
2038                                }
2039                                Ok((
2040                                    manifest.objects.lexical_generation,
2041                                    capture.open_artifact(
2042                                        &name,
2043                                        manifest.objects.lexical_payload.reference(),
2044                                    )?,
2045                                ))
2046                            })
2047                            .transpose()?
2048                    },
2049                    root,
2050                    identity: crate::lexical_projection::ReaderIdentity {
2051                        source_epoch: manifest.source_graph_commit_epoch,
2052                        analyzer_digest: crate::lexical_projection::analyzer_digest_with_context(
2053                            analyzer_lexicon,
2054                            context.task,
2055                        )?,
2056                        documents_digest: manifest.documents_digest,
2057                    },
2058                    config: lexical_config,
2059                    admission: context,
2060                    max_artifact_read_bytes,
2061                },
2062                &lexical_manifest_bytes,
2063            )?,
2064            None if cleanup_source.is_some() => {
2065                LexicalProjectionReader::load_captured_manifest_bytes(
2066                    &lexical_manifest_bytes,
2067                    manifest.source_graph_commit_epoch,
2068                    lexical_analyzer_digest(analyzer_lexicon),
2069                    manifest.documents_digest,
2070                    lexical_config,
2071                    cleanup_source.unwrap().open(
2072                        &crate::lexical_projection::artifact_file(
2073                            manifest.objects.lexical_generation,
2074                        ),
2075                        manifest.objects.lexical_payload,
2076                    )?,
2077                    manifest.objects.lexical_generation,
2078                )?
2079                .map(|reader| {
2080                    Arc::into_inner(reader).ok_or_else(|| {
2081                        HawDBError::Storage("captured lexical reader unexpectedly shared".into())
2082                    })
2083                })
2084                .transpose()?
2085            }
2086            None => LexicalProjectionReader::load_manifest_bytes(
2087                root,
2088                &lexical_manifest_bytes,
2089                manifest.source_graph_commit_epoch,
2090                lexical_analyzer_digest(analyzer_lexicon),
2091                manifest.documents_digest,
2092                lexical_config,
2093            )?
2094            .map(|reader| {
2095                Arc::into_inner(reader).ok_or_else(|| {
2096                    HawDBError::Storage("new lexical segment reader was unexpectedly shared".into())
2097                })
2098            })
2099            .transpose()?,
2100        }
2101        .ok_or_else(|| {
2102            HawDBError::Storage(
2103                "published search lexical projection does not match the out-of-core manifest"
2104                    .into(),
2105            )
2106        })?;
2107        if lexical_projection.generation() != manifest.objects.lexical_generation
2108            || lexical_projection.artifact_len() != manifest.objects.lexical_payload.byte_length
2109        {
2110            return Err(HawDBError::StorageIntegrity(
2111                "lexical data differs from its producer reference".into(),
2112            ));
2113        }
2114        drop(lexical_manifest_bytes);
2115        drop(lexical_path);
2116
2117        #[cfg(feature = "vector-search")]
2118        let rabitq_projection = vector_reader::open(
2119            root,
2120            active_manifest,
2121            manifest,
2122            config.max_vector_search_working_bytes.get(),
2123            admission,
2124            max_artifact_read_bytes,
2125            match (
2126                capture,
2127                cleanup_source,
2128                manifest.rabitq_artifact_file.as_deref(),
2129            ) {
2130                (Some(capture), _, Some(name)) => Some(
2131                    capture.open_artifact(
2132                        name,
2133                        manifest
2134                            .objects
2135                            .rabitq
2136                            .expect("validated vector reference")
2137                            .reference(),
2138                    )?,
2139                ),
2140                (_, Some(source), Some(name)) => Some(match admission {
2141                    Some(admission) => source.open_admitted(
2142                        name,
2143                        manifest.objects.rabitq.expect("validated vector reference"),
2144                        admission,
2145                    )?,
2146                    None => source.open(
2147                        name,
2148                        manifest.objects.rabitq.expect("validated vector reference"),
2149                    )?,
2150                }),
2151                _ => None,
2152            },
2153        )?;
2154        #[cfg(not(feature = "vector-search"))]
2155        if let Some(context) = admission {
2156            if let Some(name) = manifest.rabitq_artifact_file.as_deref() {
2157                let path = crate::build_memory::path::OwnedPath::join(
2158                    root,
2159                    Path::new(name),
2160                    context.memory,
2161                    context.task,
2162                )?;
2163                let length = manifest
2164                    .rabitq_artifact_len
2165                    .expect("validated vector length");
2166                let checksum = manifest
2167                    .rabitq_artifact_checksum
2168                    .expect("validated vector checksum");
2169                let file = match (capture, cleanup_source) {
2170                    (Some(capture), _) => context.visit_file_bound(
2171                        capture.open_artifact(
2172                            name,
2173                            manifest
2174                                .objects
2175                                .rabitq
2176                                .expect("validated vector reference")
2177                                .reference(),
2178                        )?,
2179                        length,
2180                        checksum,
2181                        max_artifact_read_bytes,
2182                        |_| Ok(()),
2183                    )?,
2184                    (None, Some(source)) => context.visit_file_bound(
2185                        source.open_admitted(
2186                            name,
2187                            manifest.objects.rabitq.expect("validated vector reference"),
2188                            context,
2189                        )?,
2190                        length,
2191                        checksum,
2192                        max_artifact_read_bytes,
2193                        |_| Ok(()),
2194                    )?,
2195                    (None, None) => context.visit_bound(
2196                        &path,
2197                        length,
2198                        checksum,
2199                        max_artifact_read_bytes,
2200                        |_| Ok(()),
2201                    )?,
2202                };
2203                drop(file);
2204            }
2205        } else if let Some(source) = cleanup_source {
2206            if let Some(name) = manifest.rabitq_artifact_file.as_deref() {
2207                drop(source.open(
2208                    name,
2209                    manifest.objects.rabitq.expect("validated vector reference"),
2210                )?);
2211            }
2212        } else {
2213            verify_rabitq_artifact(root, manifest)?;
2214        }
2215
2216        Ok(Self(crate::build_memory::shared::Shared::new(
2217            SegmentReaderContents {
2218                _source_pins: source_pins,
2219                content_segment_id: manifest.segment_id,
2220                descriptor,
2221                payload,
2222                payload_length: manifest.payload_len,
2223                content_encoding: manifest.content_encoding,
2224                payload_sha256: manifest.objects.payload.sha256(),
2225                payload_generation: manifest.generation,
2226                metadata_payload,
2227                metadata_payload_length: manifest.metadata_payload_len,
2228                vector_payload,
2229                vector_payload_length: manifest.vector_payload_len,
2230                layout,
2231                lexical_projection,
2232                #[cfg(feature = "vector-search")]
2233                rabitq_projection,
2234                _layout_memory: layout_memory,
2235                _reader_memory: reader_memory,
2236            },
2237        )))
2238    }
2239}
2240
2241impl SearchOutOfCoreReader {
2242    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
2243        Self::open_with_config_and_analyzer(
2244            path,
2245            SearchOutOfCoreConfig::default(),
2246            SearchAnalyzerLexicon::default(),
2247        )
2248    }
2249
2250    pub fn open_with_config(path: impl AsRef<Path>, config: SearchOutOfCoreConfig) -> Result<Self> {
2251        Self::open_with_config_and_analyzer(path, config, SearchAnalyzerLexicon::default())
2252    }
2253
2254    pub fn open_with_config_and_analyzer(
2255        path: impl AsRef<Path>,
2256        config: SearchOutOfCoreConfig,
2257        analyzer_lexicon: SearchAnalyzerLexicon,
2258    ) -> Result<Self> {
2259        Self::open_with_term_policy(
2260            path,
2261            config,
2262            analyzer_lexicon,
2263            SearchLexicalTermPolicy::default(),
2264        )
2265    }
2266
2267    /// Opens a generation under host-selected resource and lexical term limits.
2268    ///
2269    /// An insufficient term policy fails before returning a usable reader. The
2270    /// actual dictionary requirements are checked, not a writer-declared cap.
2271    pub fn open_with_term_policy(
2272        path: impl AsRef<Path>,
2273        config: SearchOutOfCoreConfig,
2274        analyzer_lexicon: SearchAnalyzerLexicon,
2275        lexical_term_policy: SearchLexicalTermPolicy,
2276    ) -> Result<Self> {
2277        Self::open_with_lexical_policies(
2278            path,
2279            config,
2280            analyzer_lexicon,
2281            lexical_term_policy,
2282            SearchLexicalSourcePolicy::default(),
2283        )
2284    }
2285
2286    /// Opens with explicit source admission for target reanalysis and later updates.
2287    pub fn open_with_source_policy(
2288        path: impl AsRef<Path>,
2289        config: SearchOutOfCoreConfig,
2290        analyzer_lexicon: SearchAnalyzerLexicon,
2291        lexical_source_policy: SearchLexicalSourcePolicy,
2292    ) -> Result<Self> {
2293        Self::open_with_lexical_policies(
2294            path,
2295            config,
2296            analyzer_lexicon,
2297            SearchLexicalTermPolicy::default(),
2298            lexical_source_policy,
2299        )
2300    }
2301
2302    /// Opens a generation with explicit host-selected lexical policies.
2303    ///
2304    /// Source admission governs old-version reanalysis, compaction and subsequent
2305    /// writes. It is never widened from an artifact declaration.
2306    pub fn open_with_lexical_policies(
2307        path: impl AsRef<Path>,
2308        config: SearchOutOfCoreConfig,
2309        analyzer_lexicon: SearchAnalyzerLexicon,
2310        lexical_term_policy: SearchLexicalTermPolicy,
2311        lexical_source_policy: SearchLexicalSourcePolicy,
2312    ) -> Result<Self> {
2313        admitted_root::open(admitted_root::OpenContext {
2314            root: path.as_ref(),
2315            publication: None,
2316            stationary: None,
2317            expected_stationary_manifest: None,
2318            config,
2319            analyzer_lexicon,
2320            lexical_term_policy,
2321            lexical_source_policy,
2322            admission: None,
2323            project: None,
2324            max_artifact_read_bytes: u64::MAX,
2325        })?
2326        .into_ordinary()
2327    }
2328
2329    pub(super) fn primary_segment(&self) -> &SearchOutOfCoreSegmentReader {
2330        // Logical-manifest metadata remains shared. Any data-plane operation
2331        // must iterate the complete artifact set instead of using this helper.
2332        self.segments
2333            .first()
2334            .expect("validated search manifest has at least one segment")
2335    }
2336
2337    pub fn lexical_term_policy(&self) -> SearchLexicalTermPolicy {
2338        self.lexical_term_policy
2339    }
2340
2341    pub fn lexical_source_policy(&self) -> SearchLexicalSourcePolicy {
2342        self.lexical_source_policy
2343    }
2344
2345    /// Changes admission for subsequent queries and prepared updates.
2346    ///
2347    /// Lowering below the open generation's actual term requirement fails and
2348    /// leaves the previous policy intact. Exclusive access prevents changes
2349    /// during a query; already prepared updates keep their own snapshot.
2350    pub fn set_lexical_term_policy(&mut self, policy: SearchLexicalTermPolicy) -> Result<()> {
2351        for artifact in &self.segments {
2352            artifact
2353                .lexical_projection
2354                .validate_term_limit(policy.max_term_bytes())?;
2355        }
2356        self.lexical_term_policy = policy;
2357        Ok(())
2358    }
2359
2360    /// Changes source admission for later generation updates.
2361    ///
2362    /// This does not affect reading an already published generation because
2363    /// source admission is a host-owned write policy.
2364    pub fn set_lexical_source_policy(&mut self, policy: SearchLexicalSourcePolicy) {
2365        self.lexical_source_policy = policy;
2366    }
2367
2368    pub fn document_count(&self) -> usize {
2369        self.manifest.document_count
2370    }
2371
2372    pub fn projection_payload_bytes(&self) -> u64 {
2373        self.manifest.segments.iter().fold(0u64, |total, segment| {
2374            total
2375                .saturating_add(segment.descriptor_len)
2376                .saturating_add(segment.payload_len)
2377                .saturating_add(segment.metadata_payload_len)
2378                .saturating_add(segment.vector_payload_len)
2379                .saturating_add(segment.layout_len)
2380                .saturating_add(segment.lexical_manifest_len)
2381                .saturating_add(segment.rabitq_artifact_len.unwrap_or_default())
2382        })
2383    }
2384
2385    #[doc(hidden)]
2386    pub fn config(&self) -> &SearchOutOfCoreConfig {
2387        &self.config
2388    }
2389
2390    /// Occupancy and hit counters of this reader's content cache (#1917),
2391    /// or `None` when `content_cache_bytes` is zero.
2392    pub fn content_cache_snapshot(&self) -> Option<hawdb_storage::cache::SegmentCacheSnapshot> {
2393        self.content_cache.snapshot()
2394    }
2395
2396    pub fn generation(&self) -> u64 {
2397        self.manifest.generation
2398    }
2399
2400    /// Process-local identity for detecting an out-of-core source replacement
2401    /// or generation advance between independently acquired ID pages.
2402    #[doc(hidden)]
2403    pub fn page_generation(&self) -> SearchProjectionPageGeneration {
2404        SearchProjectionPageGeneration::OutOfCore {
2405            reader: self.reader_id,
2406            generation: self.generation(),
2407        }
2408    }
2409
2410    /// Working-memory admission for one sequential ID-block decode and the
2411    /// bounded candidate/page control structures. ID bytes receive separate
2412    /// retained-memory reservations before they are copied.
2413    #[doc(hidden)]
2414    pub fn projection_id_page_working_memory_bytes(&self, limit: usize) -> Result<usize> {
2415        let block = self.segments.iter().try_fold(0usize, |largest, segment| {
2416            Ok::<_, HawDBError>(
2417                largest.max(segment.lexical_projection.document_id_page_memory_bytes()?),
2418            )
2419        })?;
2420        let entry_bytes = std::mem::size_of::<String>()
2421            .checked_add(std::mem::size_of::<hawdb_qos::RuntimeRetainedMemory>())
2422            .ok_or_else(|| HawDBError::Execution("projection ID page capacity overflow".into()))?;
2423        let candidates = limit
2424            .saturating_add(1)
2425            .checked_mul(entry_bytes + crate::build_memory::SET_ENTRY_BYTES)
2426            .ok_or_else(|| HawDBError::Execution("projection ID page capacity overflow".into()))?;
2427        let page_vectors = limit
2428            .saturating_add(1)
2429            .checked_mul(entry_bytes)
2430            .ok_or_else(|| HawDBError::Execution("projection ID page capacity overflow".into()))?;
2431        block
2432            .checked_add(candidates)
2433            .and_then(|bytes| bytes.checked_add(page_vectors))
2434            .ok_or_else(|| HawDBError::Execution("projection ID page capacity overflow".into()))
2435    }
2436
2437    /// Lists a globally ordered page using only per-segment lexical document
2438    /// mappings. Content, metadata, and vector payload files are not read.
2439    #[doc(hidden)]
2440    pub fn list_projection_ids(
2441        &self,
2442        kinds: &BTreeSet<SearchProjectionKind>,
2443        after: Option<&str>,
2444        limit: usize,
2445        task: &hawdb_core::RuntimeTaskContext,
2446        permit: &hawdb_qos::RuntimePermit,
2447    ) -> Result<SearchProjectionIdBatch> {
2448        task.checkpoint().map_err(HawDBError::RuntimeTaskStopped)?;
2449        let wanted = limit.saturating_add(1);
2450        let mut ids = BTreeMap::<String, hawdb_qos::RuntimeRetainedMemory>::new();
2451        for segment in &self.segments {
2452            task.checkpoint().map_err(HawDBError::RuntimeTaskStopped)?;
2453            segment.lexical_projection.visit_document_ids_with_task(
2454                kinds,
2455                after,
2456                task,
2457                &mut |id| {
2458                    if ids.len() == wanted
2459                        && ids
2460                            .last_key_value()
2461                            .is_some_and(|(largest, _)| id > largest)
2462                    {
2463                        return Ok(false);
2464                    }
2465                    if !self.visibility.is_visible(segment.content_segment_id, id)
2466                        || !projection_id_page::requested_kind(id, kinds)
2467                    {
2468                        return Ok(true);
2469                    }
2470                    if ids.contains_key(id) {
2471                        return Err(HawDBError::Storage(format!(
2472                            "search out-of-core segment set has duplicate document {id}"
2473                        )));
2474                    }
2475                    let memory = permit
2476                        .reserve_retained_memory(u64::try_from(id.len()).unwrap_or(u64::MAX))
2477                        .map_err(HawDBError::from)?;
2478                    ids.insert(id.to_string(), memory);
2479                    if ids.len() > wanted {
2480                        ids.pop_last();
2481                    }
2482                    Ok(true)
2483                },
2484            )?;
2485        }
2486        task.checkpoint().map_err(HawDBError::RuntimeTaskStopped)?;
2487        Ok(projection_id_page::finish_ids(
2488            ids.into_iter().collect(),
2489            limit,
2490        ))
2491    }
2492
2493    /// Attaches a newer durable head, sharing unchanged immutable content handles.
2494    ///
2495    /// Retained content paths and lengths are checked before their handles are
2496    /// reused. Changed heads decode and checksum every mutation run; target
2497    /// reanalysis is reused only for the same run and exact content references,
2498    /// with an unchanged global embedding identity. Fresh opens validate the
2499    /// complete closure. Published artifacts must remain immutable while readers
2500    /// exist. On failure this reader retains its previously pinned generation.
2501    pub fn refresh(&mut self) -> Result<SearchOutOfCoreRefreshReport> {
2502        let (closure, report) = self.prepare_refresh()?;
2503        if let Some(closure) = closure {
2504            self.manifest = closure.manifest;
2505            self.segments = closure.segments;
2506            self.visibility = closure.visibility;
2507        }
2508        Ok(report)
2509    }
2510
2511    /// Publishes a refreshed reader without changing existing snapshot owners.
2512    /// Unchanged content retains its native artifact pins and shared allocations;
2513    /// no reader or document corpus is cloned on snapshot acquisition.
2514    pub fn refresh_shared(reader: &mut Arc<Self>) -> Result<SearchOutOfCoreRefreshReport> {
2515        let (closure, report) = reader.prepare_refresh()?;
2516        if let Some(closure) = closure {
2517            let next = Self {
2518                reader_id: reader.reader_id,
2519                root: reader.root.clone(),
2520                _project_files: reader._project_files.clone(),
2521                config: reader.config.clone(),
2522                analyzer_lexicon: reader.analyzer_lexicon.clone(),
2523                manifest: closure.manifest,
2524                segments: closure.segments,
2525                visibility: closure.visibility,
2526                lexical_source_policy: reader.lexical_source_policy,
2527                lexical_term_policy: reader.lexical_term_policy,
2528                runtime_capabilities: reader.runtime_capabilities,
2529                content_cache: reader.content_cache.clone(),
2530            };
2531            *reader = Arc::new(next);
2532        }
2533        Ok(report)
2534    }
2535
2536    fn prepare_refresh(
2537        &self,
2538    ) -> Result<(Option<LoadedArtifactClosure>, SearchOutOfCoreRefreshReport)> {
2539        let bytes = read_bounded_file(
2540            &self.root.join(OUT_OF_CORE_MANIFEST_FILE),
2541            MAX_OUT_OF_CORE_MANIFEST_BYTES,
2542        )?;
2543        let manifest = SearchOutOfCoreManifestBody::decode(&bytes)?;
2544        if manifest == self.manifest {
2545            for (segment, reference) in self.segments.iter().zip(&manifest.segments) {
2546                segment.validate_pinned_paths(&self.root, reference)?;
2547            }
2548            for run in &manifest.mutation_runs {
2549                if fs::metadata(self.root.join(&run.file))?.len() != run.len {
2550                    return Err(HawDBError::Storage(
2551                        "pinned mutation-run artifact length changed".into(),
2552                    ));
2553                }
2554            }
2555            return Ok((
2556                None,
2557                SearchOutOfCoreRefreshReport {
2558                    generation: manifest.generation,
2559                    generation_changed: false,
2560                    validated_retractions: 0,
2561                    reused_retractions: self.visibility.retractions().count(),
2562                    opened_content_segments: 0,
2563                    reused_content_segments: self.segments.len(),
2564                },
2565            ));
2566        }
2567        if manifest.generation <= self.manifest.generation {
2568            return Err(HawDBError::Storage(
2569                "search durable head regressed or changed an existing generation".into(),
2570            ));
2571        }
2572        let closure = load_artifact_closure_for_manifest(
2573            &self.root,
2574            &self.config,
2575            &self.analyzer_lexicon,
2576            self.lexical_term_policy,
2577            self.lexical_source_policy,
2578            manifest,
2579            Some(reuse::View::from_reader(self)),
2580        )?;
2581        let report = closure.refresh;
2582        Ok((Some(closure), report))
2583    }
2584
2585    #[cfg(all(test, feature = "full-text-search"))]
2586    pub(crate) fn artifact_count(&self) -> usize {
2587        self.manifest.segments.len()
2588    }
2589
2590    pub fn source_graph_commit_epoch(&self) -> Option<u64> {
2591        self.manifest.source_graph_commit_epoch
2592    }
2593
2594    pub(super) fn can_append_after(
2595        &self,
2596        first_document_id: &str,
2597        memory: &crate::build_memory::BuildMemory,
2598        task: &hawdb_core::RuntimeTaskContext,
2599    ) -> Result<bool> {
2600        let mut generations = Vec::new();
2601        let mut generation_memory = memory.retained.reserve(0)?;
2602        crate::build_memory::reserve_capacity(
2603            &mut generations,
2604            self.manifest.segments.len(),
2605            &mut generation_memory,
2606        )?;
2607        for segment in &self.manifest.segments {
2608            crate::build_control::checkpoint(task)?;
2609            generations.push(segment.generation);
2610        }
2611        generations.sort_unstable();
2612        if generations.windows(2).any(|pair| pair[0] == pair[1]) {
2613            return Err(HawDBError::Storage(
2614                "search generation contains duplicate document content artifacts".into(),
2615            ));
2616        }
2617        let mut previous_last_document_id = None;
2618        let mut ordered = true;
2619        for artifact in &self.segments {
2620            crate::build_control::checkpoint(task)?;
2621            let descriptor_first = artifact.descriptor.segments.first();
2622            let descriptor_last = artifact.descriptor.segments.last();
2623            let lexical_bounds = artifact.lexical_projection.document_id_bounds();
2624            match (descriptor_first, descriptor_last, lexical_bounds) {
2625                (None, None, None) => continue,
2626                (Some(first), Some(last), Some((lexical_first, lexical_last)))
2627                    if first.first_document_id == lexical_first
2628                        && last.last_document_id == lexical_last => {}
2629                _ => {
2630                    return Err(HawDBError::Storage(
2631                        "search generation update requires descriptor and lexical document ranges to agree"
2632                            .to_string(),
2633                    ));
2634                }
2635            }
2636            for segment in &artifact.descriptor.segments {
2637                if previous_last_document_id
2638                    .is_some_and(|previous| previous >= segment.first_document_id.as_str())
2639                {
2640                    ordered = false;
2641                }
2642                previous_last_document_id = Some(segment.last_document_id.as_str());
2643            }
2644        }
2645        Ok(
2646            ordered
2647                && previous_last_document_id.is_none_or(|previous| previous < first_document_id),
2648        )
2649    }
2650
2651    pub fn import_source_graph_commit_epoch(&self) -> Option<u64> {
2652        self.manifest.import_source_graph_commit_epoch
2653    }
2654
2655    pub fn embedding_manifest(&self) -> Option<SearchEmbeddingManifest> {
2656        self.manifest
2657            .embedding_model
2658            .as_ref()
2659            .zip(self.manifest.embedding_dimension)
2660            .map(|(model, dimension)| SearchEmbeddingManifest {
2661                model: model.clone(),
2662                version: self.manifest.embedding_version.clone(),
2663                dimension,
2664            })
2665    }
2666
2667    /// Scoring policy sealed into this immutable projection.
2668    pub fn vector_scoring(&self) -> crate::SearchVectorScoring {
2669        self.manifest.vector_scoring
2670    }
2671
2672    /// Decode the field binding sealed into this immutable projection.
2673    pub fn vector_index_descriptor(&self) -> Result<Option<hawdb_core::VectorIndexDescriptor>> {
2674        self.manifest
2675            .vector_index_binding
2676            .as_deref()
2677            .map(crate::vector_index::decode)
2678            .transpose()
2679    }
2680
2681    pub fn analyzer_lexicon(&self) -> &SearchAnalyzerLexicon {
2682        &self.analyzer_lexicon
2683    }
2684
2685    /// Runs one generation cleanup pass over this reader's projection root
2686    /// with explicit limits, under the root's publication exclusion.
2687    ///
2688    /// Publications already run a pass with their configured limits; this
2689    /// call lets a host retry one that reported `retry_required`, for example
2690    /// with a larger `max_verification_bytes` after a restart, when no file of
2691    /// the active closure has been verified by this process yet. If another
2692    /// owner is publishing, the pass is deferred and nothing is deleted. The
2693    /// active closure is verified before anything is deleted.
2694    pub fn retry_projection_cleanup(
2695        &self,
2696        options: crate::SearchProjectionCleanupOptions,
2697    ) -> crate::SearchProjectionCleanupReport {
2698        let mut state = crate::generation_cleanup::SearchProjectionCleanupState::default();
2699        match SearchProjectionPublishLease::acquire_for_cleanup(&self.root) {
2700            Ok(publication) => state.run_under_publication(
2701                &self.root,
2702                options,
2703                &publication,
2704                &self.analyzer_lexicon,
2705                None,
2706            ),
2707            Err(_) => state.defer_for_publication(options),
2708        }
2709    }
2710
2711    pub fn production_qualification_identity(
2712        &self,
2713    ) -> super::SearchProjectionQualificationIdentity {
2714        super::SearchProjectionQualificationIdentity {
2715            projection_generation: self.manifest.generation,
2716            source_graph_commit_epoch: self.manifest.source_graph_commit_epoch,
2717            document_count: self.manifest.document_count,
2718            documents_digest: self.manifest.documents_digest,
2719            analyzer_digest: lexical_analyzer_digest(&self.analyzer_lexicon),
2720            embedding_model: self.manifest.embedding_model.clone(),
2721            embedding_version: self.manifest.embedding_version.clone(),
2722            embedding_dimension: self.manifest.embedding_dimension,
2723        }
2724    }
2725
2726    pub fn vector_projection_qualification_identity(
2727        &self,
2728    ) -> Option<super::VectorProjectionQualificationIdentity> {
2729        #[cfg(feature = "vector-search")]
2730        {
2731            if self.has_diskann_projection() {
2732                return self.diskann_qualification().map(|(identity, _)| identity);
2733            }
2734            let projection = self.primary_segment().rabitq_projection.as_ref()?;
2735            let manifest = projection.manifest();
2736            Some(super::VectorProjectionQualificationIdentity {
2737                projection_generation: manifest.identity.generation,
2738                source_graph_commit_epoch: manifest.identity.source_epoch,
2739                document_count: manifest.document_count,
2740                source_digest: manifest.source_digest,
2741                payload_bytes: manifest.payload_bytes,
2742                payload_checksum: manifest.payload_checksum,
2743                format_version: manifest.format_version,
2744                algorithm: manifest.algorithm.to_owned(),
2745                bit_width: manifest.bit_width,
2746                dimension: manifest.dimension,
2747                transform_seed: manifest.transform_seed,
2748                embedding_model: manifest.identity.embedding_model.clone(),
2749                embedding_version: manifest.identity.embedding_version.clone(),
2750                file_backed: true,
2751            })
2752        }
2753        #[cfg(not(feature = "vector-search"))]
2754        {
2755            None
2756        }
2757    }
2758
2759    pub fn vector_projection_resource_evidence(
2760        &self,
2761    ) -> Option<super::VectorProjectionResourceEvidence> {
2762        #[cfg(feature = "vector-search")]
2763        {
2764            if self.has_diskann_projection() {
2765                return self.diskann_qualification().map(|(_, resources)| resources);
2766            }
2767            let projection = self.primary_segment().rabitq_projection.as_ref()?;
2768            let manifest = projection.manifest();
2769            let raw_vector_bytes = (manifest.document_count as u64)
2770                .saturating_mul(manifest.dimension as u64)
2771                .saturating_mul(std::mem::size_of::<f32>() as u64);
2772            Some(super::VectorProjectionResourceEvidence {
2773                segment_count: manifest.segment_count,
2774                requested_segment_rows: manifest.requested_segment_rows,
2775                admitted_segment_rows: manifest.admitted_segment_rows,
2776                configured_build_working_bytes: manifest.configured_build_working_bytes,
2777                peak_build_working_bytes: manifest.peak_build_working_bytes,
2778                raw_vector_bytes,
2779                projection_payload_bytes: manifest.payload_bytes,
2780                build_write_amplification_per_million: manifest
2781                    .payload_bytes
2782                    .saturating_mul(1_000_000)
2783                    .checked_div(raw_vector_bytes.max(1))
2784                    .unwrap_or(u64::MAX),
2785            })
2786        }
2787        #[cfg(not(feature = "vector-search"))]
2788        {
2789            None
2790        }
2791    }
2792
2793    pub fn resident_document_count(&self) -> usize {
2794        0
2795    }
2796
2797    pub fn set_runtime_capabilities(&mut self, capabilities: RuntimeCapabilities) {
2798        self.runtime_capabilities =
2799            crate::compiled_capabilities::effective_runtime_capabilities(capabilities);
2800    }
2801
2802    pub fn runtime_capabilities(&self) -> RuntimeCapabilities {
2803        self.runtime_capabilities
2804    }
2805
2806    /// Durably records that this projection needs a full reindex, under the
2807    /// same `.reindex_needed` marker the resident projection uses. Repeating a
2808    /// reason is a no-op; a different reason is appended. Only a full rebuild,
2809    /// which publishes a new projection directory, clears it.
2810    pub fn mark_full_reindex_needed(&self, reason: &str) -> Result<()> {
2811        self.write_control_marker(FULL_REINDEX_MARKER, reason, true)
2812    }
2813
2814    /// Durably records that this projection's metadata needs repair. The
2815    /// marker holds the latest reason, as on the resident projection.
2816    pub fn mark_metadata_repair_needed(&self, reason: &str) -> Result<()> {
2817        self.write_control_marker(METADATA_REPAIR_MARKER, reason, false)
2818    }
2819
2820    fn write_control_marker(&self, name: &str, reason: &str, append: bool) -> Result<()> {
2821        let path = self.root.join(name);
2822        let existing = read_marker_lines_bounded(&path, MAX_MARKER_BYTES)?;
2823        let lines = if append {
2824            if existing.iter().any(|line| line == reason) {
2825                return Ok(());
2826            }
2827            let mut lines = existing;
2828            lines.push(reason.to_string());
2829            lines
2830        } else {
2831            if existing == [reason] {
2832                return Ok(());
2833            }
2834            vec![reason.to_string()]
2835        };
2836        let content = lines.join("\n");
2837        if content.len() as u64 > MAX_MARKER_BYTES {
2838            return Err(HawDBError::Semantic(format!(
2839                "search marker {name} would exceed {MAX_MARKER_BYTES} bytes"
2840            )));
2841        }
2842        let temporary = self.root.join(format!("{name}.tmp"));
2843        {
2844            let mut file = File::create(&temporary)?;
2845            std::io::Write::write_all(&mut file, content.as_bytes())?;
2846            file.sync_all()?;
2847        }
2848        hawdb_storage::durability::durable_replace_file(&temporary, &path)?;
2849        Ok(())
2850    }
2851
2852    pub fn projection_freshness(&self) -> SearchProjectionFreshness {
2853        let read_marker = |name| {
2854            read_marker_lines_bounded(&self.root.join(name), MAX_MARKER_BYTES)
2855                .unwrap_or_else(|error| vec![format!("failed to read marker {name}: {error}")])
2856        };
2857        let full_reindex_reasons = read_marker(FULL_REINDEX_MARKER);
2858        let metadata_repair_reasons = read_marker(METADATA_REPAIR_MARKER);
2859        self.freshness_with_markers(full_reindex_reasons, metadata_repair_reasons)
2860    }
2861
2862    fn freshness_with_markers(
2863        &self,
2864        full_reindex_reasons: Vec<String>,
2865        metadata_repair_reasons: Vec<String>,
2866    ) -> SearchProjectionFreshness {
2867        SearchProjectionFreshness {
2868            document_count: self.manifest.document_count,
2869            import_source_graph_commit_epoch: self.manifest.import_source_graph_commit_epoch,
2870            source_graph_commit_epoch: self.manifest.source_graph_commit_epoch,
2871            durable_source_graph_commit_epoch: self.manifest.source_graph_commit_epoch,
2872            has_uncheckpointed_changes: false,
2873            full_reindex_needed: !full_reindex_reasons.is_empty(),
2874            full_reindex_reasons,
2875            metadata_repair_needed: !metadata_repair_reasons.is_empty(),
2876            metadata_repair_reasons,
2877            embedding_model: self.manifest.embedding_model.clone(),
2878            embedding_version: self.manifest.embedding_version.clone(),
2879            embedding_dimension: self.manifest.embedding_dimension,
2880        }
2881    }
2882
2883    pub fn search_with_options(
2884        &self,
2885        query_text: &str,
2886        query_embedding: Option<&[f32]>,
2887        mode: SearchMode,
2888        options: SearchQueryOptions,
2889    ) -> Result<SearchOutOfCoreOutput> {
2890        self.search_with_options_internal(
2891            query_text,
2892            query_embedding,
2893            mode,
2894            options,
2895            SearchOutOfCoreExecutionContext {
2896                compressed_vector_search_mode: self.default_compressed_vector_search_mode(),
2897                ..SearchOutOfCoreExecutionContext::scalar()
2898            },
2899        )
2900    }
2901
2902    /// Scores every eligible raw vector, bypassing approximate graph traversal.
2903    pub fn search_with_options_exact(
2904        &self,
2905        query_text: &str,
2906        query_embedding: Option<&[f32]>,
2907        mode: SearchMode,
2908        options: SearchQueryOptions,
2909    ) -> Result<SearchOutOfCoreOutput> {
2910        self.search_with_options_internal(
2911            query_text,
2912            query_embedding,
2913            mode,
2914            options,
2915            SearchOutOfCoreExecutionContext {
2916                vector_execution_options: VectorSearchExecutionOptions::default()
2917                    .with_exact_search(),
2918                ..SearchOutOfCoreExecutionContext::scalar()
2919            },
2920        )
2921    }
2922
2923    pub fn search_with_options_compressed_vector_projection_mode(
2924        &self,
2925        query_text: &str,
2926        query_embedding: Option<&[f32]>,
2927        mode: SearchMode,
2928        options: SearchQueryOptions,
2929        compressed_vector_search_mode: CompressedVectorSearchMode,
2930    ) -> Result<SearchOutOfCoreOutput> {
2931        self.search_with_options_internal(
2932            query_text,
2933            query_embedding,
2934            mode,
2935            options,
2936            SearchOutOfCoreExecutionContext {
2937                access_control: None,
2938                compressed_vector_search_mode,
2939                vector_execution_options: VectorSearchExecutionOptions::default(),
2940            },
2941        )
2942    }
2943
2944    pub fn search_with_options_compressed_vector_projection_context(
2945        &self,
2946        query_text: &str,
2947        query_embedding: Option<&[f32]>,
2948        mode: SearchMode,
2949        options: SearchQueryOptions,
2950        compressed_vector_search_mode: CompressedVectorSearchMode,
2951        task_context: &crate::RuntimeTaskContext,
2952    ) -> Result<SearchOutOfCoreOutput> {
2953        self.search_with_options_internal(
2954            query_text,
2955            query_embedding,
2956            mode,
2957            options,
2958            SearchOutOfCoreExecutionContext {
2959                access_control: None,
2960                compressed_vector_search_mode,
2961                vector_execution_options: VectorSearchExecutionOptions::bounded(
2962                    NonZeroUsize::new(
2963                        self.config
2964                            .max_vector_search_parallelism
2965                            .get()
2966                            .min(task_context.admitted_parallelism().get()),
2967                    )
2968                    .expect("out-of-core vector parallelism is non-zero"),
2969                    self.config.max_vector_search_working_bytes.get(),
2970                    Some(task_context),
2971                ),
2972            },
2973        )
2974    }
2975
2976    pub fn search_with_options_compressed_vector_projection_execution_options(
2977        &self,
2978        query_text: &str,
2979        query_embedding: Option<&[f32]>,
2980        mode: SearchMode,
2981        options: SearchQueryOptions,
2982        compressed_vector_search_mode: CompressedVectorSearchMode,
2983        vector_execution_options: VectorSearchExecutionOptions<'_>,
2984    ) -> Result<SearchOutOfCoreOutput> {
2985        self.search_with_options_internal(
2986            query_text,
2987            query_embedding,
2988            mode,
2989            options,
2990            SearchOutOfCoreExecutionContext {
2991                access_control: None,
2992                compressed_vector_search_mode,
2993                vector_execution_options,
2994            },
2995        )
2996    }
2997
2998    /// Serves like
2999    /// [`Self::search_with_options_compressed_vector_projection_execution_options`]
3000    /// under the caller's runtime admission. Every allocation that scales with
3001    /// the eligible set (candidate filters, score maps, rankings, fused
3002    /// candidates, segment buffers and hit hydration) is charged to one
3003    /// working account of `min(max_working_bytes, task memory reservation)`
3004    /// bytes. A query that does not fit, including a hybrid query without a
3005    /// rank window over a large eligible set, is refused with a typed
3006    /// memory-budget error rather than served above its admission.
3007    ///
3008    /// `vector_execution_options.task_context` is required and must be the
3009    /// context bound to `permit`. Returned hits are not charged: the caller
3010    /// owns the result payload budget.
3011    pub fn search_with_options_admitted(
3012        &self,
3013        query_text: &str,
3014        query_embedding: Option<&[f32]>,
3015        mode: SearchMode,
3016        options: SearchQueryOptions,
3017        execution: SearchOutOfCoreExecutionContext<'_>,
3018        permit: &hawdb_qos::RuntimePermit,
3019    ) -> Result<SearchOutOfCoreOutput> {
3020        let task = execution
3021            .vector_execution_options
3022            .task_context
3023            .ok_or_else(|| {
3024                HawDBError::Execution(
3025                    "admitted out-of-core search requires the permit's task context".into(),
3026                )
3027            })?;
3028        let working =
3029            query_memory::Working::new(execution.vector_execution_options.max_working_bytes, task)?;
3030        let io = crate::build_memory::read::QueryIoScope::acquire(task)?;
3031        let mut output = self.search_hits(
3032            query_text,
3033            query_embedding,
3034            mode,
3035            options,
3036            query_memory::Execution {
3037                base: execution,
3038                query: Some(working.context(task, permit, &io)),
3039                immutable_freshness: false,
3040                scratch: None,
3041                output: None,
3042            },
3043            SearchHitHydration::Documents,
3044        )?;
3045        output.metrics.query_memory_peak_bytes = working.peak_bytes();
3046        Ok(output)
3047    }
3048
3049    /// The largest eligible-set size an exact vector-only read under
3050    /// `working_bytes` of admitted working memory is guaranteed to serve, for
3051    /// eligible document IDs of at most `max_document_id_bytes` bytes.
3052    ///
3053    /// It is the smaller of the scan's duplicate-ID cap,
3054    /// `min(max_score_entries, working_bytes / 128) / 2` (262,144 at 64 MiB,
3055    /// as before #1722), and what the query account admits: one charged
3056    /// duplicate-ID entry per eligible document after this reader's fixed
3057    /// working set (one zstd decoder at the pinned level-3 window, the vector
3058    /// read run and segment head, cached candidate blocks, the candidate block
3059    /// directory, range validation and query metadata). It does not depend on
3060    /// the embedding dimension. A read of more eligible documents may be
3061    /// refused with a typed `ResourceBudgetExceeded` error; it is never
3062    /// truncated. The page's hit hydration is bounded separately by
3063    /// `max_hydrated_bytes` and must also fit the admission.
3064    pub fn exact_vector_search_capacity(
3065        &self,
3066        working_bytes: usize,
3067        max_document_id_bytes: usize,
3068    ) -> usize {
3069        // One level-3 zstd decoder (<= 2.75 MiB), a 256 KiB vector run, 64 KiB
3070        // range validation, the 8 KiB vector prefix and query metadata.
3071        const FIXED_BYTES: usize = 4 << 20;
3072        let uniqueness = vector_serving::admitted_score_entries(
3073            self.config.max_score_entries.get(),
3074            working_bytes,
3075        ) / 2;
3076        let id = max_document_id_bytes;
3077        let mut fixed = FIXED_BYTES
3078            .saturating_add(crate::build_memory::ID_SET_ROOT_BYTES)
3079            .saturating_add(
3080                self.manifest
3081                    .embedding_dimension
3082                    .unwrap_or_default()
3083                    .saturating_mul(2 * size_of::<f32>()),
3084            );
3085        let mut max_segment_documents = 0usize;
3086        for segment in self
3087            .segments
3088            .iter()
3089            .flat_map(|artifact| &artifact.descriptor.segments)
3090        {
3091            // The candidate block directory entry and its copied ID bounds.
3092            fixed = fixed
3093                .saturating_add(128)
3094                .saturating_add(segment.first_document_id.len())
3095                .saturating_add(segment.last_document_id.len());
3096            max_segment_documents = max_segment_documents.max(segment.document_count);
3097        }
3098        // One cached candidate block (raw bytes, read buffer and entries) and
3099        // one vector segment head (ordinals and IDs).
3100        fixed = fixed.saturating_add(
3101            max_segment_documents.saturating_mul(
3102                (2 * (id.saturating_add(12)))
3103                    .saturating_add(2 * size_of::<String>())
3104                    .saturating_add(id.saturating_add(4)),
3105            ),
3106        );
3107        let per_document = crate::build_memory::ID_SET_ENTRY_BYTES.saturating_add(id);
3108        uniqueness.min(working_bytes.saturating_sub(fixed) / per_document)
3109    }
3110
3111    pub fn search_with_options_access_control(
3112        &self,
3113        query_text: &str,
3114        query_embedding: Option<&[f32]>,
3115        mode: SearchMode,
3116        options: SearchQueryOptions,
3117        access_control: SearchAccessControlContext,
3118    ) -> Result<SearchOutOfCoreOutput> {
3119        self.search_with_options_internal(
3120            query_text,
3121            query_embedding,
3122            mode,
3123            options,
3124            SearchOutOfCoreExecutionContext {
3125                access_control: Some(&access_control),
3126                compressed_vector_search_mode: self.default_compressed_vector_search_mode(),
3127                vector_execution_options: VectorSearchExecutionOptions::default(),
3128            },
3129        )
3130    }
3131
3132    /// Hydrates the named documents in request order.
3133    ///
3134    /// The request is all-or-nothing. Duplicate ids and an id the published
3135    /// projection does not contain (including a deleted one) are
3136    /// `HawDBError::Semantic`; more ids than
3137    /// `SearchOutOfCoreConfig.max_hydrated_documents` is
3138    /// `ResourceBudgetExceeded` with owner `search hydration by id`.
3139    pub fn hydrate_documents(
3140        &self,
3141        document_ids: &[String],
3142    ) -> Result<SearchOutOfCoreHydrationOutput> {
3143        let requested = document_ids.iter().cloned().collect::<BTreeSet<_>>();
3144        // A repeated id is a malformed request, not storage damage.
3145        if requested.len() != document_ids.len() {
3146            return Err(HawDBError::Semantic(
3147                "search hydration document ids must be unique".to_string(),
3148            ));
3149        }
3150        let mut metrics = SearchOutOfCoreMetrics::default();
3151        let mut hydrated =
3152            self.load_document_targets(&requested, &mut metrics, DocumentTargetRequest::ById)?;
3153        let documents = document_ids
3154            .iter()
3155            .map(|id| {
3156                hydrated
3157                    .remove(id)
3158                    .map(|target| target.document)
3159                    .ok_or_else(|| {
3160                        HawDBError::Storage(format!(
3161                            "search document {id} was not found during bounded hydration"
3162                        ))
3163                    })
3164            })
3165            .collect::<Result<Vec<_>>>()?;
3166        metrics.hydrated_documents = documents.len();
3167        Ok(SearchOutOfCoreHydrationOutput { documents, metrics })
3168    }
3169
3170    /// Hydrates the named documents the published projection contains and
3171    /// reports the rest as missing, both in request order.
3172    ///
3173    /// Unlike [`Self::hydrate_documents`], an id the projection does not
3174    /// contain is not an error: an id that was never published and one hidden
3175    /// by deletion visibility are both reported in `missing_document_ids`.
3176    /// Duplicate ids are `HawDBError::Semantic`, and more ids than
3177    /// `SearchOutOfCoreConfig.max_hydrated_documents` is
3178    /// `ResourceBudgetExceeded` with owner `search lookup by id`. Absence is
3179    /// decided by the published document routes alone; an id they list whose
3180    /// document cannot be read or verified is still `HawDBError::Storage`.
3181    pub fn lookup_documents(
3182        &self,
3183        document_ids: &[String],
3184    ) -> Result<SearchOutOfCoreDocumentLookup> {
3185        let requested = document_ids.iter().cloned().collect::<BTreeSet<_>>();
3186        // A repeated id is a malformed request, as in hydration by id.
3187        if requested.len() != document_ids.len() {
3188            return Err(HawDBError::Semantic(
3189                "search lookup document ids must be unique".to_string(),
3190            ));
3191        }
3192        let mut metrics = SearchOutOfCoreMetrics::default();
3193        let mut found = self.load_document_targets(
3194            &requested,
3195            &mut metrics,
3196            DocumentTargetRequest::LookupById,
3197        )?;
3198        let mut documents = Vec::with_capacity(found.len());
3199        let mut missing_document_ids = Vec::new();
3200        for id in document_ids {
3201            match found.remove(id) {
3202                Some(target) => documents.push(target.document),
3203                None => missing_document_ids.push(id.clone()),
3204            }
3205        }
3206        metrics.hydrated_documents = documents.len();
3207        Ok(SearchOutOfCoreDocumentLookup {
3208            documents,
3209            missing_document_ids,
3210            metrics,
3211        })
3212    }
3213
3214    /// Resolves the current content segment for each requested document.
3215    ///
3216    /// The input is a `BTreeSet` so mutation preparation receives a unique,
3217    /// deterministic document-id order. Resolution performs the same bounded
3218    /// physical hydration as serving, while retaining the manifest segment
3219    /// identity required for a segment-local replacement or delete.
3220    ///
3221    /// No production caller resolves mutation targets yet: segment-local
3222    /// delta writes route through [`Self::resolve_mutation_segment`]. Public
3223    /// hydration by id shares the loader under its own budget owner.
3224    #[cfg(test)]
3225    pub(crate) fn resolve_mutation_targets(
3226        &self,
3227        document_ids: &BTreeSet<String>,
3228    ) -> Result<SearchOutOfCoreMutationTargetOutput> {
3229        let mut metrics = SearchOutOfCoreMetrics::default();
3230        let targets = self.load_document_targets(
3231            document_ids,
3232            &mut metrics,
3233            DocumentTargetRequest::MutationTargets,
3234        )?;
3235        metrics.hydrated_documents = targets.len();
3236        Ok(SearchOutOfCoreMutationTargetOutput { targets, metrics })
3237    }
3238
3239    /// Resolves the content segment that currently owns one document.
3240    ///
3241    /// This reads the lexical document-id index but does not hydrate the
3242    /// document payload. A caller that rebuilds the selected segment therefore
3243    /// pays for the segment stream exactly once.
3244    pub(crate) fn resolve_mutation_segment(&self, document_id: &str) -> Result<Option<u64>> {
3245        let Some(route) = self.segment_for_document(document_id)? else {
3246            return Ok(None);
3247        };
3248        let artifact = self.segments.get(route.artifact_index).ok_or_else(|| {
3249            HawDBError::Storage(format!(
3250                "search mutation target references unknown layer {}",
3251                route.artifact_index
3252            ))
3253        })?;
3254        Ok(Some(artifact.content_segment_id))
3255    }
3256
3257    #[cfg(test)]
3258    fn visit_documents_in_order(
3259        &self,
3260        consumer: &mut dyn FnMut(SearchDocument) -> Result<()>,
3261    ) -> Result<SearchOutOfCoreMetrics> {
3262        let mut metrics = SearchOutOfCoreMetrics::default();
3263        for artifact in &self.segments {
3264            for segment in &artifact.descriptor.segments {
3265                for document in self.read_hydration_segment(artifact, segment, &mut metrics)? {
3266                    consumer(document)?;
3267                }
3268            }
3269        }
3270        Ok(metrics)
3271    }
3272
3273    /// Scores and filters through the same path as full hits, without body hydration.
3274    pub fn search_candidates_with_options(
3275        &self,
3276        query_text: &str,
3277        query_embedding: Option<&[f32]>,
3278        mode: SearchMode,
3279        options: SearchQueryOptions,
3280    ) -> Result<SearchOutOfCoreOutput<SearchOutOfCoreCandidate>> {
3281        self.search_candidates_with_context(
3282            query_text,
3283            query_embedding,
3284            mode,
3285            options,
3286            Default::default(),
3287        )
3288    }
3289
3290    /// Selects candidate output with the same ACL and vector execution controls.
3291    pub fn search_candidates_with_context(
3292        &self,
3293        query_text: &str,
3294        query_embedding: Option<&[f32]>,
3295        mode: SearchMode,
3296        options: SearchQueryOptions,
3297        execution: SearchOutOfCoreExecutionContext<'_>,
3298    ) -> Result<SearchOutOfCoreOutput<SearchOutOfCoreCandidate>> {
3299        self.search_with_materializer(
3300            query_text,
3301            query_embedding,
3302            mode,
3303            options,
3304            execution,
3305            |candidates, _context, metrics| {
3306                candidates
3307                    .iter()
3308                    .map(|candidate| {
3309                        let route = self.segment_for_document(&candidate.id)?.ok_or_else(|| {
3310                            HawDBError::Storage(
3311                                "ranked candidate has no visible content version".into(),
3312                            )
3313                        })?;
3314                        metrics.lexical_document_bytes_read = metrics
3315                            .lexical_document_bytes_read
3316                            .saturating_add(route.lexical_document_bytes_read);
3317                        metrics.lexical_document_block_reads =
3318                            metrics.lexical_document_block_reads.saturating_add(1);
3319                        Ok(SearchOutOfCoreCandidate {
3320                            scores: candidate.clone(),
3321                            generation: self.manifest.generation,
3322                            content_segment_id: self.segments[route.artifact_index]
3323                                .content_segment_id,
3324                        })
3325                    })
3326                    .collect()
3327            },
3328        )
3329    }
3330
3331    /// Ranks exactly like the other search entry points, then materializes
3332    /// hits at the requested level. Use [`SearchHitHydration::ScoresOnly`]
3333    /// when only identifiers and scores are consumed.
3334    pub fn search_with_hydration(
3335        &self,
3336        query_text: &str,
3337        query_embedding: Option<&[f32]>,
3338        mode: SearchMode,
3339        options: SearchQueryOptions,
3340        execution: SearchOutOfCoreExecutionContext<'_>,
3341        hydration: SearchHitHydration,
3342    ) -> Result<SearchOutOfCoreOutput> {
3343        self.search_hits(
3344            query_text,
3345            query_embedding,
3346            mode,
3347            options,
3348            execution,
3349            hydration,
3350        )
3351    }
3352
3353    fn search_with_options_internal<'execution>(
3354        &self,
3355        query_text: &str,
3356        query_embedding: Option<&[f32]>,
3357        mode: SearchMode,
3358        options: SearchQueryOptions,
3359        execution: impl Into<query_memory::Execution<'execution>>,
3360    ) -> Result<SearchOutOfCoreOutput> {
3361        self.search_hits(
3362            query_text,
3363            query_embedding,
3364            mode,
3365            options,
3366            execution,
3367            SearchHitHydration::Documents,
3368        )
3369    }
3370
3371    fn search_hits<'execution>(
3372        &self,
3373        query_text: &str,
3374        query_embedding: Option<&[f32]>,
3375        mode: SearchMode,
3376        options: SearchQueryOptions,
3377        execution: impl Into<query_memory::Execution<'execution>>,
3378        hydration: SearchHitHydration,
3379    ) -> Result<SearchOutOfCoreOutput> {
3380        if options.limit > self.config.max_hydrated_documents.get() {
3381            return Err(hydrated_documents_refusal(
3382                "search hit hydration",
3383                options.limit,
3384                self.config.max_hydrated_documents.get(),
3385                format!(
3386                    "search hydration requested {} documents, exceeding {}",
3387                    options.limit, self.config.max_hydrated_documents
3388                ),
3389            ));
3390        }
3391        self.search_with_materializer(
3392            query_text,
3393            query_embedding,
3394            mode,
3395            options,
3396            execution,
3397            |candidates, context, metrics| {
3398                self.hydrate_hits(candidates, context, hydration, metrics)
3399            },
3400        )
3401    }
3402
3403    fn search_with_materializer<'execution, H>(
3404        &self,
3405        query_text: &str,
3406        query_embedding: Option<&[f32]>,
3407        mode: SearchMode,
3408        options: SearchQueryOptions,
3409        execution: impl Into<query_memory::Execution<'execution>>,
3410        materialize: impl FnOnce(
3411            &[SearchScoredCandidate],
3412            HitHydrationContext<'_>,
3413            &mut SearchOutOfCoreMetrics,
3414        ) -> Result<Vec<H>>,
3415    ) -> Result<SearchOutOfCoreOutput<H>> {
3416        let query_memory::Execution {
3417            base: execution,
3418            query,
3419            immutable_freshness,
3420            scratch,
3421            output,
3422        } = execution.into();
3423        let output_memory = query_output::Memory(output);
3424        // Native results require working admission. An ordinary admitted read
3425        // charges working memory while its caller owns the result budget.
3426        if output.is_some() && query.is_none() {
3427            return Err(HawDBError::Execution(
3428                "native query requires paired working and result admission".into(),
3429            ));
3430        }
3431        let SearchOutOfCoreExecutionContext {
3432            access_control,
3433            compressed_vector_search_mode,
3434            mut vector_execution_options,
3435        } = execution;
3436        // A per-query beam wins; otherwise the reader's configured default.
3437        vector_execution_options
3438            .navigation_beam
3439            .get_or_insert(self.config.default_navigation_beam);
3440        let task_context = vector_execution_options.task_context;
3441        if let Some(task_context) = task_context {
3442            task_context
3443                .checkpoint()
3444                .map_err(HawDBError::RuntimeTaskStopped)?;
3445        }
3446        if access_control.is_some() {
3447            self.runtime_capabilities
3448                .require(RuntimeCapability::AccessControl)?;
3449        }
3450        self.require_search_capabilities(mode)?;
3451        let page_score_limit = options
3452            .offset
3453            .checked_add(options.limit)
3454            .ok_or_else(|| HawDBError::Semantic("search offset and limit overflow".to_string()))?;
3455        let max_score_entries = self.config.max_score_entries.get();
3456        if page_score_limit > max_score_entries {
3457            return Err(score_entries_refusal(
3458                "search page window",
3459                page_score_limit,
3460                0,
3461                max_score_entries,
3462                MAX_SCORE_ENTRIES_OPTION,
3463                format!(
3464                    "search page window requires {page_score_limit} score entries, exceeding {max_score_entries}"
3465                ),
3466            ));
3467        }
3468        if let Some(window) = options
3469            .rank_window
3470            .filter(|window| *window > max_score_entries)
3471        {
3472            return Err(score_entries_refusal(
3473                "search rank window",
3474                window,
3475                0,
3476                max_score_entries,
3477                MAX_SCORE_ENTRIES_OPTION,
3478                format!(
3479                    "search rank window exceeds the admitted {max_score_entries} score entries"
3480                ),
3481            ));
3482        }
3483
3484        let metadata_filters = match access_control {
3485            Some(access_control) => access_control.effective_query_filters(&options)?,
3486            None => output_memory.map(&options.metadata_filters)?,
3487        };
3488        let policy_epoch = access_control
3489            .map(|access_control| access_control.policy_epoch)
3490            .or(options.policy_epoch);
3491        let mut normalized_terms = self.query_terms(query_text, query)?;
3492        let term_selection = (mode != SearchMode::Vector)
3493            .then(|| self.select_query_terms(&mut normalized_terms.values, query))
3494            .transpose()?
3495            .filter(|selection| selection.reduced());
3496        let query_terms = &normalized_terms.values;
3497        let mut predicate_pushdown = query_memory::Predicates::new(&metadata_filters, query)?;
3498        predicate_pushdown.report.parse_error =
3499            output_memory.optional(predicate_pushdown.report.parse_error.as_deref())?;
3500        let mut metrics = SearchOutOfCoreMetrics::default();
3501        let candidate_set = self.build_candidate_set(
3502            candidate_set::CandidateFilter {
3503                predicates: &predicate_pushdown.predicates,
3504                eligible: None,
3505            },
3506            &mut predicate_pushdown.report,
3507            &mut metrics,
3508            query,
3509            scratch,
3510            output_memory,
3511        )?;
3512        let filtered_document_count = candidate_set.cardinality();
3513        let candidate_report = SearchCandidateSetReport {
3514            id_space: output_memory.text("search_projection_document_id")?,
3515            representation: output_memory.text(candidate_set.representation())?,
3516            cardinality: filtered_document_count,
3517            exact: true,
3518            snapshot_source_graph_commit_epoch: self.manifest.source_graph_commit_epoch,
3519            policy_epoch,
3520            filtered_out_count: self
3521                .manifest
3522                .document_count
3523                .saturating_sub(filtered_document_count),
3524            metadata_filters: output_memory.map(&options.metadata_filters)?,
3525            metadata_predicate_pushdown: predicate_pushdown.report,
3526        };
3527
3528        let text_available = !query_terms.is_empty();
3529        let (mut text_fallback_reason_codes, mut text_fallback_reasons) =
3530            if !text_available && mode != SearchMode::Vector {
3531                (
3532                    output_memory.codes(&[SearchFallbackReasonCode::TextQueryEmpty])?,
3533                    output_memory.one_text("query text produced no searchable terms")?,
3534                )
3535            } else {
3536                (Vec::new(), Vec::new())
3537            };
3538        if let Some(selection) = term_selection {
3539            output_memory.push(
3540                &mut text_fallback_reason_codes,
3541                SearchFallbackReasonCode::TextQueryTermsReduced,
3542            )?;
3543            let reason = output_memory.format(format_args!("{selection}"))?;
3544            output_memory.push(&mut text_fallback_reasons, reason)?;
3545        }
3546
3547        let mut vector_fallback_reason_codes = Vec::new();
3548        let mut vector_fallback_reasons = Vec::new();
3549        let vector_available = match (query_embedding, self.manifest.embedding_dimension) {
3550            (Some(vector), Some(dimension)) if vector.len() == dimension => true,
3551            (Some(vector), Some(dimension)) => {
3552                output_memory.push(
3553                    &mut vector_fallback_reason_codes,
3554                    SearchFallbackReasonCode::VectorDimensionMismatch,
3555                )?;
3556                let reason = output_memory.format(format_args!(
3557                    "query embedding dimension {} does not match index dimension {dimension}",
3558                    vector.len()
3559                ))?;
3560                output_memory.push(&mut vector_fallback_reasons, reason)?;
3561                false
3562            }
3563            (Some(_), None) => {
3564                output_memory.push(
3565                    &mut vector_fallback_reason_codes,
3566                    SearchFallbackReasonCode::VectorIndexEmpty,
3567                )?;
3568                let reason = output_memory.text("index has no vector rows")?;
3569                output_memory.push(&mut vector_fallback_reasons, reason)?;
3570                false
3571            }
3572            (None, _) => {
3573                if mode != SearchMode::Text {
3574                    output_memory.push(
3575                        &mut vector_fallback_reason_codes,
3576                        SearchFallbackReasonCode::QueryEmbeddingMissing,
3577                    )?;
3578                    let reason = output_memory.text("query embedding not provided")?;
3579                    output_memory.push(&mut vector_fallback_reasons, reason)?;
3580                }
3581                false
3582            }
3583        };
3584
3585        let retained_text_limit = match mode {
3586            SearchMode::Text => Some(page_score_limit),
3587            SearchMode::Hybrid => options.rank_window,
3588            SearchMode::Vector => Some(0),
3589        };
3590        let text = if text_available && mode != SearchMode::Vector {
3591            Some(self.query_text_scores(
3592                query_terms,
3593                retained_text_limit,
3594                mode == SearchMode::Hybrid,
3595                &candidate_set,
3596                &mut metrics,
3597                query,
3598            )?)
3599        } else {
3600            None
3601        };
3602        let empty_scores = BTreeMap::new();
3603        let (
3604            text_scores,
3605            text_matching_count,
3606            lexical_postings_visited,
3607            lexical_bytes_read,
3608            lexical_blocks_skipped,
3609        ) = match &text {
3610            Some(scores) => (
3611                &scores.values,
3612                scores.matching_count,
3613                scores.postings_visited,
3614                scores.bytes_read,
3615                scores.blocks_skipped,
3616            ),
3617            None => (&empty_scores, 0, 0, 0, 0),
3618        };
3619
3620        let retained_vector_limit = match mode {
3621            SearchMode::Vector => Some(page_score_limit),
3622            SearchMode::Hybrid => options.rank_window,
3623            SearchMode::Text => Some(0),
3624        };
3625        let vector_scan = if vector_available && mode != SearchMode::Text {
3626            self.scan_vector_scores(
3627                query_embedding.expect("vector availability requires an embedding"),
3628                &candidate_set,
3629                retained_vector_limit,
3630                vector_serving::ScanOptions {
3631                    compressed: compressed_vector_search_mode,
3632                    execution: vector_execution_options,
3633                    #[cfg(feature = "vector-search")]
3634                    candidate_window: options.rank_window,
3635                    query,
3636                },
3637                &mut metrics,
3638            )?
3639        } else {
3640            VectorScoreScan::default()
3641        };
3642        let vector_fallback_reason_codes = output_memory.combine(
3643            &vector_fallback_reason_codes,
3644            &vector_scan.fallback_reason_codes,
3645        )?;
3646        let vector_fallback_reasons = output_memory
3647            .combine_strings(&vector_fallback_reasons, &vector_scan.fallback_reasons)?;
3648        let vector_scores = &vector_scan.scores;
3649
3650        let vector_ranks = query_ranking::Ranks::new(vector_scores, query)?;
3651        let text_ranks = query_ranking::Ranks::new(text_scores, query)?;
3652        let vector_window_ranks = vector_ranks.window(options.rank_window, query)?;
3653        let text_window_ranks = text_ranks.window(options.rank_window, query)?;
3654        let fallback_reason_codes =
3655            output_memory.combine(&vector_fallback_reason_codes, &text_fallback_reason_codes)?;
3656        let fallback_reasons =
3657            output_memory.combine_strings(&vector_fallback_reasons, &text_fallback_reasons)?;
3658
3659        let mut retrievers = output_memory.vec(2)?;
3660        retrievers.push(SearchRetrieverReport {
3661            name: output_memory.text("vector")?,
3662            backend: output_memory.text(&vector_scan.backend)?,
3663            backend_selection_reason: None,
3664            estimated_raw_vector_bytes: self.manifest.embedding_dimension.map(|dimension| {
3665                (dimension as u64)
3666                    .saturating_mul(std::mem::size_of::<f32>() as u64)
3667                    .saturating_mul(filtered_document_count as u64)
3668            }),
3669            filter_selectivity_per_million: None,
3670            available: vector_available && mode != SearchMode::Text,
3671            input_candidate_set: output_memory.candidate(&candidate_report)?,
3672            candidate_score_source: output_memory.text(
3673                if vector_available && mode != SearchMode::Text {
3674                    vector_scan.candidate_score_source.as_str()
3675                } else {
3676                    "none"
3677                },
3678            )?,
3679            final_score_source: output_memory.text(
3680                if vector_available && mode != SearchMode::Text {
3681                    "raw_vector"
3682                } else {
3683                    "none"
3684                },
3685            )?,
3686            generated_candidate_count: vector_scan.generated_candidate_count,
3687            candidate_scan_rounds: vector_scan.segment_scan_count,
3688            descriptor_pruned_count: candidate_report
3689                .metadata_predicate_pushdown
3690                .segment_pruned_document_count,
3691            scalar_filtered_count: candidate_report.filtered_out_count.saturating_sub(
3692                candidate_report
3693                    .metadata_predicate_pushdown
3694                    .segment_pruned_document_count,
3695            ),
3696            residual_filtered_count: 0,
3697            reranked_candidate_count: vector_scan.reranked_candidate_count,
3698            raw_vector_bytes_read: metrics.vector_bytes_read,
3699            candidate_scan_kernel: output_memory
3700                .optional(vector_scan.candidate_scan_kernel.as_deref())?,
3701            candidate_scan_worker_count: vector_scan.candidate_scan_worker_count,
3702            candidate_scan_segment_count: vector_scan.candidate_scan_segment_count,
3703            candidate_scan_scanned_segment_count: vector_scan.candidate_scan_scanned_segment_count,
3704            candidate_scan_scored_document_count: vector_scan.candidate_scan_scored_document_count,
3705            candidate_scan_filtered_document_count: vector_scan
3706                .candidate_scan_filtered_document_count,
3707            candidate_scan_scanned_block_count: vector_scan.candidate_scan_scanned_block_count,
3708            candidate_scan_skipped_block_count: vector_scan.candidate_scan_skipped_block_count,
3709            candidate_scan_adaptive_exact_scan_count: vector_scan
3710                .candidate_scan_adaptive_exact_scan_count,
3711            candidate_scan_payload_bytes_read: vector_scan.candidate_scan_payload_bytes_read,
3712            candidate_scan_admitted_working_bytes: vector_scan
3713                .candidate_scan_admitted_working_bytes,
3714            posting_bytes_read: 0,
3715            candidate_postings_visited: 0,
3716            candidate_blocks_skipped: 0,
3717            segmented_lexical_projection_used: false,
3718            index_covered_document_count: vector_scan.vector_document_count,
3719            index_candidate_document_count: vector_scan.vector_document_count,
3720            index_coverage_complete: true,
3721            candidate_count: vector_scan.matching_count,
3722            candidate_set: output_memory.retriever_set(
3723                vector_window_ranks.len(),
3724                self.manifest.source_graph_commit_epoch,
3725                policy_epoch,
3726            )?,
3727            fallback_reason_codes: output_memory.codes(&vector_fallback_reason_codes)?,
3728            fallback_reasons: output_memory.strings(&vector_fallback_reasons)?,
3729            candidate_top_ids: Vec::new(),
3730            top_hit_ids: output_memory.top_ids(&vector_window_ranks, options.limit)?,
3731            top_candidates: output_memory.top_candidates(
3732                &vector_window_ranks,
3733                vector_scores,
3734                options.limit,
3735            )?,
3736        });
3737        retrievers.push(SearchRetrieverReport {
3738            name: output_memory.text("text")?,
3739            backend: output_memory.text("segmented_bm25_text")?,
3740            backend_selection_reason: None,
3741            estimated_raw_vector_bytes: None,
3742            filter_selectivity_per_million: None,
3743            available: text_available && mode != SearchMode::Vector,
3744            input_candidate_set: output_memory.candidate(&candidate_report)?,
3745            candidate_score_source: output_memory.text(
3746                if text_available && mode != SearchMode::Vector {
3747                    "segmented_bm25"
3748                } else {
3749                    "none"
3750                },
3751            )?,
3752            final_score_source: output_memory.text(
3753                if text_available && mode != SearchMode::Vector {
3754                    "segmented_bm25"
3755                } else {
3756                    "none"
3757                },
3758            )?,
3759            generated_candidate_count: text_matching_count,
3760            candidate_scan_rounds: 0,
3761            descriptor_pruned_count: candidate_report
3762                .metadata_predicate_pushdown
3763                .segment_pruned_document_count,
3764            scalar_filtered_count: candidate_report.filtered_out_count.saturating_sub(
3765                candidate_report
3766                    .metadata_predicate_pushdown
3767                    .segment_pruned_document_count,
3768            ),
3769            residual_filtered_count: 0,
3770            reranked_candidate_count: 0,
3771            raw_vector_bytes_read: 0,
3772            candidate_scan_kernel: None,
3773            candidate_scan_worker_count: 0,
3774            candidate_scan_segment_count: 0,
3775            candidate_scan_scanned_segment_count: 0,
3776            candidate_scan_scored_document_count: 0,
3777            candidate_scan_filtered_document_count: 0,
3778            candidate_scan_scanned_block_count: 0,
3779            candidate_scan_skipped_block_count: 0,
3780            candidate_scan_adaptive_exact_scan_count: 0,
3781            candidate_scan_payload_bytes_read: 0,
3782            candidate_scan_admitted_working_bytes: 0,
3783            posting_bytes_read: lexical_bytes_read,
3784            candidate_postings_visited: lexical_postings_visited,
3785            candidate_blocks_skipped: lexical_blocks_skipped,
3786            segmented_lexical_projection_used: true,
3787            index_covered_document_count: 0,
3788            index_candidate_document_count: 0,
3789            index_coverage_complete: true,
3790            candidate_count: text_matching_count,
3791            candidate_set: output_memory.retriever_set(
3792                text_window_ranks.len(),
3793                self.manifest.source_graph_commit_epoch,
3794                policy_epoch,
3795            )?,
3796            fallback_reason_codes: text_fallback_reason_codes,
3797            fallback_reasons: text_fallback_reasons,
3798            candidate_top_ids: Vec::new(),
3799            top_hit_ids: output_memory.top_ids(&text_window_ranks, options.limit)?,
3800            top_candidates: output_memory.top_candidates(
3801                &text_window_ranks,
3802                text_scores,
3803                options.limit,
3804            )?,
3805        });
3806
3807        for retriever in &mut retrievers {
3808            if retriever.name == "vector" {
3809                for candidate in &mut retriever.top_candidates {
3810                    candidate.score = self.vector_scoring().exposed(candidate.score);
3811                }
3812            }
3813        }
3814        let mut scored_candidates = query_ranking::Candidates::new(
3815            query_ranking::Inputs {
3816                vector_scores,
3817                text_scores,
3818                vector_ranks: &vector_ranks,
3819                text_ranks: &text_ranks,
3820                vector_window: &vector_window_ranks,
3821                text_window: &text_window_ranks,
3822                mode,
3823                weights: options.fusion_weights,
3824            },
3825            query,
3826        )?;
3827        let total_hits = match mode {
3828            SearchMode::Text => text_matching_count,
3829            SearchMode::Vector => vector_scan.matching_count,
3830            SearchMode::Hybrid => scored_candidates.values.len(),
3831        };
3832        let page_end = options.offset.saturating_add(options.limit);
3833        let truncated = total_hits > page_end;
3834        scored_candidates.page(options.offset, options.limit)?;
3835        for candidate in &mut scored_candidates.values {
3836            candidate.vector_score = self.vector_scoring().exposed(candidate.vector_score);
3837            if mode == SearchMode::Vector {
3838                candidate.score = candidate.vector_score;
3839            }
3840        }
3841        let page_candidates = &scored_candidates.values;
3842        let projection_freshness = if immutable_freshness {
3843            // Born construction checked the actual native directory. Saved
3844            // paths and later unrelated marker files cannot redirect this view.
3845            output_memory.immutable_freshness(self)?
3846        } else if output.is_some() {
3847            output_memory.freshness(&self.projection_freshness())?
3848        } else {
3849            self.projection_freshness()
3850        };
3851        let hydration = HitHydrationContext {
3852            query_terms,
3853            query_embedding,
3854            mode,
3855            fallback_reason_codes: &fallback_reason_codes,
3856            fallback_reasons: &fallback_reasons,
3857            projection_freshness: &projection_freshness,
3858            query,
3859            output_memory,
3860        };
3861        let hits = materialize(page_candidates, hydration, &mut metrics)?;
3862
3863        let truncation_reasons = if truncated && options.offset > 0 {
3864            let reason = output_memory.format(format_args!(
3865                "offset {} limit {} returned from {total_hits} matching hits",
3866                options.offset, options.limit
3867            ))?;
3868            output_memory.one_owned(reason)?
3869        } else if truncated {
3870            let reason = output_memory.format(format_args!(
3871                "limit {} returned from {total_hits} matching hits",
3872                options.limit
3873            ))?;
3874            output_memory.one_owned(reason)?
3875        } else {
3876            Vec::new()
3877        };
3878        let truncation_reason_codes = if truncated {
3879            output_memory.codes(&[SearchTruncationReasonCode::LimitExceeded])?
3880        } else {
3881            Vec::new()
3882        };
3883        let empty_state = query_output::report::Empty {
3884            empty: hits.is_empty(),
3885            documents: self.manifest.document_count,
3886            filtered: filtered_document_count,
3887            total: total_hits,
3888            page: SearchPageWindow {
3889                offset: options.offset,
3890                limit: options.limit,
3891            },
3892        };
3893        let empty_reasons =
3894            output_memory.empty_reasons(empty_state, &truncation_reasons, &fallback_reasons)?;
3895        let empty_reason_codes = output_memory.empty_codes(empty_state)?;
3896        if let Some(query) = query {
3897            query.checkpoint()?;
3898        }
3899        Ok(SearchOutOfCoreOutput {
3900            result: SearchResultSet {
3901                hits,
3902                total_hits,
3903                limit: options.limit,
3904                offset: options.offset,
3905                truncated,
3906                truncation_reason_codes,
3907                truncation_reasons,
3908                empty_reason_codes,
3909                empty_reasons,
3910                fallback_reason_codes,
3911                fallback_reasons,
3912                retrievers,
3913                candidate_set: candidate_report,
3914                rank_window: options.rank_window,
3915                fusion_weights: options.fusion_weights,
3916                document_count: self.manifest.document_count,
3917                filtered_document_count,
3918                projection_freshness,
3919            },
3920            metrics,
3921        })
3922    }
3923
3924    fn hydrate_hits(
3925        &self,
3926        candidates: &[SearchScoredCandidate],
3927        context: HitHydrationContext<'_>,
3928        level: SearchHitHydration,
3929        metrics: &mut SearchOutOfCoreMetrics,
3930    ) -> Result<Vec<SearchHit>> {
3931        if candidates.len() > self.config.max_hydrated_documents.get() {
3932            return Err(hydrated_documents_refusal(
3933                "search hit hydration",
3934                candidates.len(),
3935                self.config.max_hydrated_documents.get(),
3936                format!(
3937                    "search hydration requires {} documents, exceeding {}",
3938                    candidates.len(),
3939                    self.config.max_hydrated_documents
3940                ),
3941            ));
3942        }
3943        if level == SearchHitHydration::ScoresOnly {
3944            return self.score_only_hits(candidates, &context);
3945        }
3946        // Reported vector scores must equal the ranking scores' metric.
3947        let metric = self.vector_metric()?;
3948        // Matched spans are the only hit fields that need the stored body.
3949        let matches = level == SearchHitHydration::Documents && !context.query_terms.is_empty();
3950        let mut hydrated = if !matches {
3951            HydratedHits::Sidecars(hydration::sidecar::load(
3952                self,
3953                candidates,
3954                metrics,
3955                context.query,
3956            )?)
3957        } else {
3958            HydratedHits::Documents(hydration::query::Loaded::new(
3959                self,
3960                candidates,
3961                metrics,
3962                context.query,
3963                // Only vector and hybrid hits rescore the stored embedding.
3964                context.mode != SearchMode::Text,
3965            )?)
3966        };
3967        let query_scorer = if context.mode != SearchMode::Text && !candidates.is_empty() {
3968            context
3969                .query_embedding
3970                .map(|query| {
3971                    VectorRelevanceQuery::with_work(query, metric, || {
3972                        context.query.map_or(Ok(()), |query| query.checkpoint())
3973                    })
3974                })
3975                .transpose()?
3976                .map(|scorer| scorer.with_scoring(self.vector_scoring()))
3977        } else {
3978            None
3979        };
3980        let mut hits = context.output_memory.vec(candidates.len())?;
3981        let mut matched_span_count = 0usize;
3982        let mut matched_span_bytes = 0u64;
3983        for candidate in candidates {
3984            let document = hydrated.remove(&candidate.id).ok_or_else(|| {
3985                HawDBError::Storage(format!(
3986                    "search candidate {} was not found during late hydration",
3987                    candidate.id
3988                ))
3989            })?;
3990            let document: &SearchDocument = &document;
3991            let vector_score = if context.mode != SearchMode::Text {
3992                context
3993                    .query_embedding
3994                    .zip(document.embedding.as_deref())
3995                    .filter(|(query, embedding)| {
3996                        !embedding.is_empty() && query.len() == embedding.len()
3997                    })
3998                    .and_then(|(_, embedding)| query_scorer.as_ref()?.score(embedding))
3999                    .filter(|score| *score > 0.0)
4000                    .unwrap_or(0.0)
4001            } else {
4002                0.0
4003            };
4004            let matched = context.output_memory.matches(
4005                if matches {
4006                    context.query_terms
4007                } else {
4008                    &NO_TERMS
4009                },
4010                document,
4011                &self.analyzer_lexicon,
4012                query_output::matches::Limits {
4013                    count: self
4014                        .config
4015                        .max_matched_spans
4016                        .get()
4017                        .saturating_sub(matched_span_count),
4018                    bytes: self.config.max_matched_span_bytes.get(),
4019                    used: matched_span_bytes,
4020                },
4021            )?;
4022            let matched_spans = matched.spans;
4023            matched_span_count = matched_span_count.saturating_add(matched_spans.len());
4024            matched_span_bytes = matched_span_bytes.saturating_add(
4025                matched_spans
4026                    .iter()
4027                    .map(matched_span_bytes_for)
4028                    .sum::<u64>(),
4029            );
4030            hits.push(SearchHit {
4031                id: context.output_memory.text(&candidate.id)?,
4032                score: candidate.score,
4033                vector_score: self.vector_scoring().exposed(vector_score),
4034                text_score: candidate.text_score,
4035                rrf_score: candidate.rrf_score,
4036                vector_rrf_score: candidate.vector_rrf_score,
4037                text_rrf_score: candidate.text_rrf_score,
4038                vector_rank: candidate.vector_rank,
4039                text_rank: candidate.text_rank,
4040                kind: context
4041                    .output_memory
4042                    .optional(document.metadata.get("kind").map(String::as_str))?,
4043                external_id: context
4044                    .output_memory
4045                    .optional(document.metadata.get("external_id").map(String::as_str))?,
4046                source_id: context
4047                    .output_memory
4048                    .optional(document.metadata.get("source_id").map(String::as_str))?,
4049                matched_terms: matched.terms,
4050                matched_spans,
4051                fallback_reason_codes: context
4052                    .output_memory
4053                    .codes(context.fallback_reason_codes)?,
4054                fallback_reasons: context.output_memory.strings(context.fallback_reasons)?,
4055                projection_freshness: context
4056                    .output_memory
4057                    .freshness(context.projection_freshness)?,
4058            });
4059        }
4060        metrics.hydrated_documents = hits.len();
4061        Ok(hits)
4062    }
4063
4064    fn score_only_hits(
4065        &self,
4066        candidates: &[SearchScoredCandidate],
4067        context: &HitHydrationContext<'_>,
4068    ) -> Result<Vec<SearchHit>> {
4069        let mut hits = context.output_memory.vec(candidates.len())?;
4070        for candidate in candidates {
4071            if let Some(query) = context.query {
4072                query.checkpoint()?;
4073            }
4074            hits.push(SearchHit {
4075                id: context.output_memory.text(&candidate.id)?,
4076                score: candidate.score,
4077                vector_score: candidate.vector_score,
4078                text_score: candidate.text_score,
4079                rrf_score: candidate.rrf_score,
4080                vector_rrf_score: candidate.vector_rrf_score,
4081                text_rrf_score: candidate.text_rrf_score,
4082                vector_rank: candidate.vector_rank,
4083                text_rank: candidate.text_rank,
4084                kind: None,
4085                external_id: None,
4086                source_id: None,
4087                matched_terms: Vec::new(),
4088                matched_spans: Vec::new(),
4089                fallback_reason_codes: context
4090                    .output_memory
4091                    .codes(context.fallback_reason_codes)?,
4092                fallback_reasons: context.output_memory.strings(context.fallback_reasons)?,
4093                projection_freshness: context
4094                    .output_memory
4095                    .freshness(context.projection_freshness)?,
4096            });
4097        }
4098        Ok(hits)
4099    }
4100
4101    fn load_documents(
4102        &self,
4103        document_ids: &BTreeSet<String>,
4104        metrics: &mut SearchOutOfCoreMetrics,
4105        embeddings: bool,
4106    ) -> Result<BTreeMap<String, SearchDocument>> {
4107        Ok(self
4108            .load_document_targets(
4109                document_ids,
4110                metrics,
4111                if embeddings {
4112                    DocumentTargetRequest::SearchHits
4113                } else {
4114                    DocumentTargetRequest::TextHits
4115                },
4116            )?
4117            .into_iter()
4118            .map(|(id, target)| (id, target.document))
4119            .collect())
4120    }
4121
4122    fn load_document_targets(
4123        &self,
4124        document_ids: &BTreeSet<String>,
4125        metrics: &mut SearchOutOfCoreMetrics,
4126        request: DocumentTargetRequest,
4127    ) -> Result<BTreeMap<String, SearchOutOfCoreMutationTarget>> {
4128        let operation = request.operation();
4129        if document_ids.len() > self.config.max_hydrated_documents.get() {
4130            return Err(hydrated_documents_refusal(
4131                &format!("search {operation}"),
4132                document_ids.len(),
4133                self.config.max_hydrated_documents.get(),
4134                format!(
4135                    "search {operation} requires {} documents, exceeding {}",
4136                    document_ids.len(),
4137                    self.config.max_hydrated_documents
4138                ),
4139            ));
4140        }
4141        let mut segment_documents = BTreeMap::<(usize, u64), BTreeSet<String>>::new();
4142        // Every id with a visible route must load, whoever asked for it.
4143        let mut routed_documents = 0usize;
4144        let ids = document_ids.iter().map(String::as_str).collect::<Vec<_>>();
4145        let routes = self.segments_for_documents_with_context(&ids, None, metrics)?;
4146        for (id, route) in document_ids.iter().zip(&routes.routes) {
4147            let Some((artifact_index, segment)) = route else {
4148                match request.unknown_document(id) {
4149                    Some(error) => return Err(error),
4150                    None => continue,
4151                }
4152            };
4153            routed_documents += 1;
4154            segment_documents
4155                .entry((*artifact_index, segment.segment_id))
4156                .or_default()
4157                .insert(id.clone());
4158        }
4159        drop(routes);
4160        let mut targets = BTreeMap::<String, SearchOutOfCoreMutationTarget>::new();
4161        let mut hydrated_bytes = 0u64;
4162        for ((layer, segment_id), ids) in segment_documents {
4163            let artifact = self.segments.get(layer).ok_or_else(|| {
4164                HawDBError::Storage(format!(
4165                    "search {operation} references unknown layer {layer}"
4166                ))
4167            })?;
4168            let segment = self
4169                .segments
4170                .get(layer)
4171                .expect("layer was checked above")
4172                .descriptor
4173                .segments
4174                .get(segment_id as usize)
4175                .filter(|segment| segment.segment_id == segment_id)
4176                .ok_or_else(|| {
4177                    HawDBError::Storage(format!(
4178                        "search {operation} references unknown segment {segment_id}"
4179                    ))
4180                })?;
4181            let (documents, bytes) = artifact.read_selected_hydration_segment(
4182                &self.config,
4183                segment,
4184                hydration::Wanted {
4185                    ids: &ids,
4186                    embeddings: request.embeddings(),
4187                },
4188                hydrated_bytes,
4189                metrics,
4190                &self.content_cache,
4191            )?;
4192            // One count, the selection's, carries the budget across segments
4193            // and into the metric; it equals the selected documents' size.
4194            debug_assert_eq!(
4195                documents.iter().map(search_document_bytes).sum::<u64>(),
4196                bytes
4197            );
4198            hydrated_bytes = hydrated_bytes.checked_add(bytes).ok_or_else(|| {
4199                HawDBError::Storage(format!("search {operation} byte count overflow"))
4200            })?;
4201            // Selected decoding already enforces this cap; retain the
4202            // aggregate check as a consistency guard for that accounting.
4203            if hydrated_bytes > self.config.max_hydrated_bytes.get() {
4204                return Err(HawDBError::Storage(format!(
4205                    "search {operation} requires {hydrated_bytes} bytes, exceeding {}",
4206                    self.config.max_hydrated_bytes
4207                )));
4208            }
4209            for document in documents {
4210                let id = document.id.clone();
4211                if targets
4212                    .insert(
4213                        id.clone(),
4214                        SearchOutOfCoreMutationTarget {
4215                            content_segment_id: artifact.content_segment_id,
4216                            document,
4217                        },
4218                    )
4219                    .is_some()
4220                {
4221                    return Err(HawDBError::Storage(format!(
4222                        "search {operation} found duplicate document {id}"
4223                    )));
4224                }
4225            }
4226        }
4227        if targets.len() != routed_documents {
4228            return Err(HawDBError::Storage(format!(
4229                "search {operation} found {} of {routed_documents} routed documents",
4230                targets.len(),
4231            )));
4232        }
4233        metrics.hydrated_bytes = hydrated_bytes;
4234        Ok(targets)
4235    }
4236
4237    /// Routes `ids` (ascending and distinct) exactly like
4238    /// [`Self::segment_for_document_with_context`] routes each one, but
4239    /// probes each artifact's lexical document blocks with one ascending
4240    /// prober, so a block holding several ids is read and verified once
4241    /// instead of once per id (#1917). One block is held at a time. Block
4242    /// reads and bytes are added to `metrics`.
4243    fn segments_for_documents_with_context(
4244        &self,
4245        ids: &[&str],
4246        context: Option<crate::lexical_projection::QueryContext<'_>>,
4247        metrics: &mut SearchOutOfCoreMetrics,
4248    ) -> Result<DocumentRoutes<'_>> {
4249        debug_assert!(ids.is_sorted_by(|left, right| left < right));
4250        let checkpoint = || context.map_or(Ok(()), |context| context.checkpoint());
4251        checkpoint()?;
4252        let route_bytes = size_of::<Option<(usize, &SearchSegmentDescriptorEntry)>>();
4253        let _memory = context
4254            .map(|context| {
4255                context
4256                    .memory
4257                    .reserve(ids.len().saturating_mul(route_bytes))
4258            })
4259            .transpose()?;
4260        let mut routes = vec![None; ids.len()];
4261        for (artifact_index, artifact) in self.segments.iter().enumerate() {
4262            checkpoint()?;
4263            let mut prober = artifact.lexical_projection.document_id_prober(context);
4264            for (id, route) in ids.iter().zip(routes.iter_mut()) {
4265                checkpoint()?;
4266                if !self.visibility.is_visible(artifact.content_segment_id, id) {
4267                    continue;
4268                }
4269                let Ok(index) = artifact.descriptor.segments.binary_search_by(|segment| {
4270                    if segment.last_document_id.as_str() < *id {
4271                        CmpOrdering::Less
4272                    } else if segment.first_document_id.as_str() > *id {
4273                        CmpOrdering::Greater
4274                    } else {
4275                        CmpOrdering::Equal
4276                    }
4277                }) else {
4278                    continue;
4279                };
4280                let segment = artifact
4281                    .descriptor
4282                    .segments
4283                    .get(index)
4284                    .expect("binary search returned an existing descriptor segment");
4285                let probe = prober.probe(id)?;
4286                if probe.bytes_read > 0 {
4287                    metrics.lexical_document_block_reads =
4288                        metrics.lexical_document_block_reads.saturating_add(1);
4289                    metrics.lexical_document_bytes_read = metrics
4290                        .lexical_document_bytes_read
4291                        .saturating_add(probe.bytes_read);
4292                }
4293                if !probe.present {
4294                    continue;
4295                }
4296                if route.replace((artifact_index, segment)).is_some() {
4297                    return Err(HawDBError::Storage(format!(
4298                        "search out-of-core segment set has duplicate document {id}"
4299                    )));
4300                }
4301            }
4302        }
4303        checkpoint()?;
4304        Ok(DocumentRoutes { routes, _memory })
4305    }
4306
4307    fn segment_for_document(&self, id: &str) -> Result<Option<SearchDocumentSegmentRoute<'_>>> {
4308        self.segment_for_document_with_context(id, None)
4309    }
4310
4311    fn segment_for_document_with_context(
4312        &self,
4313        id: &str,
4314        context: Option<crate::lexical_projection::QueryContext<'_>>,
4315    ) -> Result<Option<SearchDocumentSegmentRoute<'_>>> {
4316        if let Some(context) = context {
4317            context.checkpoint()?;
4318        }
4319        let mut route = None;
4320        let mut lexical_document_bytes_read = 0u64;
4321        for (artifact_index, artifact) in self.segments.iter().enumerate() {
4322            if let Some(context) = context {
4323                context.checkpoint()?;
4324            }
4325            if !self.visibility.is_visible(artifact.content_segment_id, id) {
4326                continue;
4327            }
4328            let Ok(index) = artifact.descriptor.segments.binary_search_by(|segment| {
4329                if segment.last_document_id.as_str() < id {
4330                    CmpOrdering::Less
4331                } else if segment.first_document_id.as_str() > id {
4332                    CmpOrdering::Greater
4333                } else {
4334                    CmpOrdering::Equal
4335                }
4336            }) else {
4337                continue;
4338            };
4339            let segment = artifact
4340                .descriptor
4341                .segments
4342                .get(index)
4343                .expect("binary search returned an existing descriptor segment");
4344            let probe = match context {
4345                Some(context) => artifact
4346                    .lexical_projection
4347                    .probe_document_id_with_query(id, context)?,
4348                None => artifact.lexical_projection.probe_document_id(id)?,
4349            };
4350            lexical_document_bytes_read =
4351                lexical_document_bytes_read.saturating_add(probe.bytes_read);
4352            if !probe.present {
4353                continue;
4354            }
4355            if route.replace((artifact_index, segment)).is_some() {
4356                return Err(HawDBError::Storage(format!(
4357                    "search out-of-core segment set has duplicate document {id}"
4358                )));
4359            }
4360        }
4361        if let Some(context) = context {
4362            context.checkpoint()?;
4363        }
4364        Ok(
4365            route.map(|(artifact_index, segment)| SearchDocumentSegmentRoute {
4366                artifact_index,
4367                segment,
4368                lexical_document_bytes_read,
4369            }),
4370        )
4371    }
4372
4373    fn require_search_capabilities(&self, mode: SearchMode) -> Result<()> {
4374        match mode {
4375            SearchMode::Hybrid => {
4376                self.runtime_capabilities
4377                    .require(RuntimeCapability::VectorSearch)?;
4378                self.runtime_capabilities
4379                    .require(RuntimeCapability::FullTextSearch)
4380            }
4381            SearchMode::Vector => self
4382                .runtime_capabilities
4383                .require(RuntimeCapability::VectorSearch),
4384            SearchMode::Text => self
4385                .runtime_capabilities
4386                .require(RuntimeCapability::FullTextSearch),
4387        }
4388    }
4389
4390    #[cfg(test)]
4391    fn read_hydration_segment(
4392        &self,
4393        artifact: &SearchOutOfCoreSegmentReader,
4394        segment: &SearchSegmentDescriptorEntry,
4395        metrics: &mut SearchOutOfCoreMetrics,
4396    ) -> Result<Vec<SearchDocument>> {
4397        let range = segment.payload_range.ok_or_else(|| {
4398            HawDBError::Storage(format!(
4399                "search segment {} has no payload range",
4400                segment.segment_id
4401            ))
4402        })?;
4403        let documents = hydration::read_validated(
4404            hydration::RangeReader {
4405                file: &artifact.payload,
4406                offset: range.offset,
4407                remaining: range.length,
4408            },
4409            range.length,
4410            range.checksum,
4411            self.config.max_uncompressed_segment_bytes.get(),
4412            None,
4413            |text| {
4414                let mut documents = Vec::new();
4415                for line in std::io::BufRead::lines(text) {
4416                    let line = line?;
4417                    if line.starts_with("doc\t") {
4418                        documents.push(crate::decode_search_document_line(&line)?);
4419                    }
4420                }
4421                Ok(documents)
4422            },
4423        )
4424        .map_err(|error| match error {
4425            HawDBError::Storage(message) => HawDBError::Storage(format!(
4426                "search segment {} hydration {message}",
4427                segment.segment_id
4428            )),
4429            error => error,
4430        })?;
4431        metrics.segment_range_reads = metrics.segment_range_reads.saturating_add(1);
4432        metrics.segment_bytes_read = metrics.segment_bytes_read.saturating_add(range.length);
4433        metrics.hydration_segment_bytes_read = metrics
4434            .hydration_segment_bytes_read
4435            .saturating_add(range.length);
4436        validate_search_segment_documents(segment, &documents)?;
4437        metrics.peak_segment_document_bytes = metrics
4438            .peak_segment_document_bytes
4439            .max(documents.iter().map(search_document_bytes).sum());
4440        Ok(documents)
4441    }
4442
4443    fn read_metadata_segment(
4444        &self,
4445        artifact: &SearchOutOfCoreSegmentReader,
4446        segment: &SearchSegmentDescriptorEntry,
4447        metrics: &mut SearchOutOfCoreMetrics,
4448    ) -> Result<Vec<SearchMetadataDocument>> {
4449        self.read_metadata_segment_keys(artifact, segment, metrics, None)
4450    }
4451
4452    /// [`Self::read_metadata_segment`] decoding only the metadata `keys`, or
4453    /// every key when `None`.
4454    fn read_metadata_segment_keys(
4455        &self,
4456        artifact: &SearchOutOfCoreSegmentReader,
4457        segment: &SearchSegmentDescriptorEntry,
4458        metrics: &mut SearchOutOfCoreMetrics,
4459        keys: Option<&crate::MetadataKeys>,
4460    ) -> Result<Vec<SearchMetadataDocument>> {
4461        self.read_metadata_segment_with(
4462            artifact,
4463            segment,
4464            metrics,
4465            decode_search_snapshot_text_bounded,
4466            keys,
4467        )
4468    }
4469
4470    fn read_metadata_segment_admitted(
4471        &self,
4472        artifact: &SearchOutOfCoreSegmentReader,
4473        segment: &SearchSegmentDescriptorEntry,
4474        metrics: &mut SearchOutOfCoreMetrics,
4475        memory: &hawdb_executor::QueryMemoryAccount,
4476        task: &crate::RuntimeTaskContext,
4477    ) -> Result<Vec<SearchMetadataDocument>> {
4478        self.read_metadata_segment_with(
4479            artifact,
4480            segment,
4481            metrics,
4482            |payload, limit| {
4483                crate::decode_search_snapshot_text_admitted(payload, limit, memory, task)
4484            },
4485            None,
4486        )
4487    }
4488
4489    fn read_metadata_segment_with(
4490        &self,
4491        artifact: &SearchOutOfCoreSegmentReader,
4492        segment: &SearchSegmentDescriptorEntry,
4493        metrics: &mut SearchOutOfCoreMetrics,
4494        decode: impl FnOnce(&[u8], u64) -> Result<String>,
4495        keys: Option<&crate::MetadataKeys>,
4496    ) -> Result<Vec<SearchMetadataDocument>> {
4497        let range = Self::artifact_layout_range(artifact, segment.segment_id)?.metadata;
4498        let payload = read_out_of_core_payload_range(
4499            &artifact.metadata_payload,
4500            range,
4501            segment.segment_id,
4502            "metadata",
4503            metrics,
4504        )?;
4505        metrics.metadata_segment_bytes_read = metrics
4506            .metadata_segment_bytes_read
4507            .saturating_add(range.length);
4508        let text = decode(&payload, self.config.max_uncompressed_segment_bytes.get())?;
4509        metrics.peak_metadata_segment_bytes =
4510            metrics.peak_metadata_segment_bytes.max(text.len() as u64);
4511        let documents = decode_metadata_segment(&text, segment, range.entry_count, keys)?;
4512        let layout = Self::artifact_layout_range(artifact, segment.segment_id)?;
4513        let ordinals = documents
4514            .iter()
4515            .filter_map(|document| document.vector_ordinal)
4516            .collect::<Vec<_>>();
4517        if ordinals.len() != layout.vectors.entry_count
4518            || ordinals.iter().enumerate().any(|(offset, ordinal)| {
4519                *ordinal != layout.vector_ordinal_base.saturating_add(offset as u64)
4520            })
4521        {
4522            return Err(HawDBError::Storage(format!(
4523                "search segment {} metadata vector ordinals do not match its layout",
4524                segment.segment_id
4525            )));
4526        }
4527        Ok(documents)
4528    }
4529
4530    fn read_vector_segment(
4531        &self,
4532        artifact: &SearchOutOfCoreSegmentReader,
4533        segment: &SearchSegmentDescriptorEntry,
4534        metrics: &mut SearchOutOfCoreMetrics,
4535    ) -> Result<Vec<SearchVectorDocument>> {
4536        self.read_vector_segment_selected(artifact, segment, metrics, usize::MAX, |_| true)
4537    }
4538
4539    fn read_vector_segment_selected(
4540        &self,
4541        artifact: &SearchOutOfCoreSegmentReader,
4542        segment: &SearchSegmentDescriptorEntry,
4543        metrics: &mut SearchOutOfCoreMetrics,
4544        selected_capacity: usize,
4545        selected: impl FnMut(u64) -> bool,
4546    ) -> Result<Vec<SearchVectorDocument>> {
4547        let entry_count = Self::artifact_layout_range(artifact, segment.segment_id)?
4548            .vectors
4549            .entry_count;
4550        let mut documents = Vec::with_capacity(entry_count.min(selected_capacity));
4551        self.visit_vector_segment(artifact, segment, metrics, None, selected, |document| {
4552            documents.push(SearchVectorDocument {
4553                id: document.id.clone(),
4554                embedding: document.embedding.clone(),
4555            });
4556            Ok(())
4557        })?;
4558        Ok(documents)
4559    }
4560
4561    fn artifact_layout_range(
4562        artifact: &SearchOutOfCoreSegmentReader,
4563        segment_id: u64,
4564    ) -> Result<&SearchOutOfCoreSegmentLayout> {
4565        artifact
4566            .layout
4567            .segments
4568            .get(segment_id as usize)
4569            .filter(|layout| layout.segment_id == segment_id)
4570            .ok_or_else(|| {
4571                HawDBError::Storage(format!(
4572                    "search out-of-core layout has no segment {segment_id}"
4573                ))
4574            })
4575    }
4576}
4577
4578fn verify_rabitq_artifact(root: &Path, manifest: &SearchOutOfCoreSegmentManifest) -> Result<()> {
4579    let Some(file_name) = manifest.rabitq_artifact_file.as_deref() else {
4580        return Ok(());
4581    };
4582    let expected_len = manifest
4583        .rabitq_artifact_len
4584        .expect("validated RaBitQ identity has a length");
4585    let expected_checksum = manifest
4586        .rabitq_artifact_checksum
4587        .expect("validated RaBitQ identity has a checksum");
4588    let (actual_len, actual_checksum) = file_len_checksum_streaming(&root.join(file_name))?;
4589    if actual_len != expected_len || actual_checksum != expected_checksum {
4590        return Err(HawDBError::Storage(
4591            "search out-of-core RaBitQ artifact does not match its manifest".to_string(),
4592        ));
4593    }
4594    Ok(())
4595}
4596
4597#[cfg(feature = "vector-search")]
4598fn open_rabitq_projection(
4599    root: &Path,
4600    active_manifest: &SearchOutOfCoreManifestBody,
4601    manifest: &SearchOutOfCoreSegmentManifest,
4602    max_working_bytes: usize,
4603    captured_file: Option<File>,
4604) -> Result<Option<hawdb_vector_projection::FileProjection>> {
4605    if captured_file.is_none() {
4606        verify_rabitq_artifact(root, manifest)?;
4607    }
4608    let Some(file_name) = manifest.rabitq_artifact_file.as_deref() else {
4609        return Ok(None);
4610    };
4611    let peak_build_working_bytes = manifest
4612        .rabitq_peak_build_working_bytes
4613        .expect("validated RaBitQ identity has a build memory bound");
4614    if peak_build_working_bytes > max_working_bytes {
4615        return Err(HawDBError::Storage(format!(
4616            "search RaBitQ artifact requires {peak_build_working_bytes} build bytes, exceeding the serving admission {max_working_bytes}"
4617        )));
4618    }
4619    let projection = match captured_file {
4620        Some(mut file) => {
4621            let (length, checksum) = file_len_checksum_held(&mut file)?;
4622            if Some(length) != manifest.rabitq_artifact_len
4623                || Some(checksum) != manifest.rabitq_artifact_checksum
4624            {
4625                return Err(HawDBError::StorageIntegrity(
4626                    "captured vector CRC mismatch".into(),
4627                ));
4628            }
4629            hawdb_vector_projection::FileProjection::open_file(file, &root.join(file_name))
4630        }
4631        None => hawdb_vector_projection::FileProjection::open(root.join(file_name)),
4632    }
4633    .map_err(vector_projection_error)?;
4634    active_manifest
4635        .vector_scoring
4636        .validate(active_manifest.vector_index_binding.is_some())?;
4637    let artifact_manifest = projection.manifest();
4638    if let Some(encoded) = &active_manifest.vector_index_binding {
4639        let definition = crate::vector_index::decode(encoded)?;
4640        crate::vector_index::validate_projection(&definition, artifact_manifest)?;
4641    } else if artifact_manifest.metric != active_manifest.vector_scoring.metric(None).into() {
4642        return Err(HawDBError::StorageIntegrity(
4643            "RaBitQ artifact metric differs from its projection".into(),
4644        ));
4645    }
4646    let expected_identity = hawdb_vector_projection::ProjectionIdentity {
4647        generation: manifest.generation,
4648        source_epoch: manifest.source_graph_commit_epoch,
4649        embedding_model: active_manifest.embedding_model.clone(),
4650        embedding_version: active_manifest.embedding_version.clone(),
4651    };
4652    if artifact_manifest.identity != expected_identity
4653        || Some(artifact_manifest.dimension) != active_manifest.embedding_dimension
4654        || Some(artifact_manifest.document_count) != manifest.rabitq_vector_document_count
4655        || Some(artifact_manifest.source_digest) != manifest.rabitq_source_digest
4656        || Some(artifact_manifest.payload_checksum) != manifest.rabitq_payload_checksum
4657    {
4658        return Err(HawDBError::Storage(
4659            "search out-of-core RaBitQ identity does not match its generation".to_string(),
4660        ));
4661    }
4662    Ok(Some(projection))
4663}
4664
4665fn file_len_checksum_streaming(path: &Path) -> Result<(u64, u64)> {
4666    let mut file = File::open(path)?;
4667    file_len_checksum_held(&mut file)
4668}
4669
4670fn file_len_checksum_held(file: &mut File) -> Result<(u64, u64)> {
4671    file.seek(SeekFrom::Start(0))?;
4672    let expected_len = file.metadata()?.len();
4673    let mut hasher = hawdb_integrity::Crc32cHasher::new();
4674    let mut actual_len = 0u64;
4675    let mut buffer = [0u8; 64 * 1024];
4676    loop {
4677        let read = file.read(&mut buffer)?;
4678        if read == 0 {
4679            break;
4680        }
4681        hasher.update(&buffer[..read]);
4682        actual_len = actual_len.saturating_add(read as u64);
4683    }
4684    if actual_len != expected_len {
4685        return Err(HawDBError::Storage(
4686            "held search artifact changed while checksumming".into(),
4687        ));
4688    }
4689    file.seek(SeekFrom::Start(0))?;
4690    Ok((actual_len, hasher.finish()))
4691}
4692
4693// Cleanup needs the validated artifact closure even when its format is not
4694// ready for serving. This helper cannot construct a public query reader.
4695struct LoadedArtifactClosure {
4696    manifest: SearchOutOfCoreManifestBody,
4697    segments: Vec<SearchOutOfCoreSegmentReader>,
4698    visibility: mutation_run::MutationVisibility,
4699    refresh: SearchOutOfCoreRefreshReport,
4700    collections_memory: Option<crate::build_memory::read::ReaderMemory>,
4701}
4702
4703struct ClosureLoadContext<'a, 'execution> {
4704    validation_source: Option<&'a captured_cleanup::Source<'a>>,
4705    cleanup_source: Option<&'a captured_cleanup::Source<'a>>,
4706    capture: Option<&'a root_registry::PendingCapture<'a, 'execution>>,
4707    root: &'a Path,
4708    config: &'a SearchOutOfCoreConfig,
4709    analyzer_lexicon: &'a SearchAnalyzerLexicon,
4710    lexical_term_policy: SearchLexicalTermPolicy,
4711    lexical_source_policy: SearchLexicalSourcePolicy,
4712    previous: Option<reuse::View<'a>>,
4713    admission: Option<&'a crate::build_memory::read::ReadAdmission<'execution>>,
4714    max_artifact_read_bytes: u64,
4715}
4716
4717/// Target-validation work performed while attaching a durable search head.
4718#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4719pub struct SearchOutOfCoreRefreshReport {
4720    pub generation: u64,
4721    pub generation_changed: bool,
4722    pub validated_retractions: usize,
4723    pub reused_retractions: usize,
4724    pub opened_content_segments: usize,
4725    pub reused_content_segments: usize,
4726}
4727
4728fn load_artifact_closure_for_manifest(
4729    root: &Path,
4730    config: &SearchOutOfCoreConfig,
4731    analyzer_lexicon: &SearchAnalyzerLexicon,
4732    lexical_term_policy: SearchLexicalTermPolicy,
4733    lexical_source_policy: SearchLexicalSourcePolicy,
4734    manifest: SearchOutOfCoreManifestBody,
4735    previous: Option<reuse::View<'_>>,
4736) -> Result<LoadedArtifactClosure> {
4737    load_artifact_closure_with_context(
4738        ClosureLoadContext {
4739            cleanup_source: None,
4740            validation_source: None,
4741            capture: None,
4742            root,
4743            config,
4744            analyzer_lexicon,
4745            lexical_term_policy,
4746            lexical_source_policy,
4747            previous,
4748            admission: None,
4749            max_artifact_read_bytes: u64::MAX,
4750        },
4751        manifest,
4752    )
4753}
4754
4755fn load_artifact_closure_with_context(
4756    context: ClosureLoadContext<'_, '_>,
4757    manifest: SearchOutOfCoreManifestBody,
4758) -> Result<LoadedArtifactClosure> {
4759    let ClosureLoadContext {
4760        cleanup_source,
4761        validation_source,
4762        capture,
4763        root,
4764        config,
4765        analyzer_lexicon,
4766        lexical_term_policy,
4767        lexical_source_policy,
4768        previous,
4769        admission,
4770        max_artifact_read_bytes,
4771    } = context;
4772    if let (Some(source), Some(capture)) = (validation_source, capture) {
4773        source.validate_capture(capture)?;
4774    }
4775    if cleanup_source.is_some()
4776        && (capture.is_some()
4777            || previous.is_some()
4778            || admission.is_some_and(|admission| !admission.is_synchronous()))
4779    {
4780        return Err(HawDBError::Execution(
4781            "captured cleanup cannot use path-based reader reuse".into(),
4782        ));
4783    }
4784    if admission.is_some_and(|admission| admission.is_synchronous()) && cleanup_source.is_none() {
4785        return Err(HawDBError::Execution(
4786            "synchronous closure requires captured publication custody".into(),
4787        ));
4788    }
4789    let checkpoint = || {
4790        admission.map_or(Ok(()), |admission| {
4791            crate::build_control::checkpoint(admission.task)
4792        })
4793    };
4794    checkpoint()?;
4795    if admission.is_some() && previous.is_some() {
4796        return Err(HawDBError::Execution(
4797            "governed reuse requires source-root custody".into(),
4798        ));
4799    }
4800    let collections_memory = admission
4801        .map(|admission| {
4802            use crate::build_memory::{checked_add, checked_mul};
4803            admission.retained(checked_add(
4804                checked_mul(
4805                    manifest.segments.len(),
4806                    std::mem::size_of::<SearchOutOfCoreSegmentReader>(),
4807                )?,
4808                checked_mul(
4809                    manifest.mutation_runs.len(),
4810                    std::mem::size_of::<mutation_run::SearchMutationRun>(),
4811                )?,
4812            )?)
4813        })
4814        .transpose()?;
4815    let previous = previous.filter(|reader| {
4816        reader.manifest.embedding_dimension == manifest.embedding_dimension
4817            && reader.manifest.embedding_model == manifest.embedding_model
4818            && reader.manifest.embedding_version == manifest.embedding_version
4819    });
4820    let mut refresh = SearchOutOfCoreRefreshReport {
4821        generation: manifest.generation,
4822        generation_changed: true,
4823        validated_retractions: 0,
4824        reused_retractions: 0,
4825        opened_content_segments: 0,
4826        reused_content_segments: 0,
4827    };
4828    let opened_segments = manifest.segments.iter().map(|segment| {
4829        checkpoint()?;
4830        if let Some(previous) = previous
4831            && let Some(position) = previous
4832                .manifest
4833                .segments
4834                .iter()
4835                .position(|reference| reference == segment)
4836        {
4837            previous.segments[position].validate_pinned_paths(root, segment)?;
4838            refresh.reused_content_segments += 1;
4839            // Share immutable descriptor/layout metadata as well as file
4840            // handles, avoiding a corpus-sized ID-summary copy per refresh.
4841            return Ok(previous.segments[position].clone());
4842        }
4843        refresh.opened_content_segments += 1;
4844        match admission {
4845            Some(_) => SearchOutOfCoreSegmentReader::open_with_read_admission(
4846                SegmentOpenContext {
4847                    cleanup_source,
4848                    capture,
4849                    root,
4850                    config,
4851                    analyzer_lexicon,
4852                    lexical_source_policy,
4853                    lexical_term_policy,
4854                    active_manifest: &manifest,
4855                    admission,
4856                    max_artifact_read_bytes,
4857                },
4858                segment,
4859            ),
4860            None => SearchOutOfCoreSegmentReader::open_with_read_admission(
4861                SegmentOpenContext {
4862                    cleanup_source,
4863                    capture: None,
4864                    root,
4865                    config,
4866                    analyzer_lexicon,
4867                    lexical_source_policy,
4868                    lexical_term_policy,
4869                    active_manifest: &manifest,
4870                    admission: None,
4871                    max_artifact_read_bytes,
4872                },
4873                segment,
4874            ),
4875        }
4876    });
4877    let segments = if admission.is_some() {
4878        let mut segments = Vec::new();
4879        segments
4880            .try_reserve_exact(manifest.segments.len())
4881            .map_err(|error| {
4882                HawDBError::or_stop(&error, || {
4883                    HawDBError::Execution(format!("reader segment list allocation failed: {error}"))
4884                })
4885            })?;
4886        if segments.capacity() > manifest.segments.len() {
4887            return Err(HawDBError::Execution(
4888                "reader segment list exceeded admitted capacity".into(),
4889            ));
4890        }
4891        for segment in opened_segments {
4892            segments.push(segment?);
4893        }
4894        segments
4895    } else {
4896        opened_segments.collect::<Result<Vec<_>>>()?
4897    };
4898    let mut mutation_budget = mutation_run::MutationRunBudget::new(
4899        config.max_mutation_working_bytes.get(),
4900        manifest.mutation_runs.len(),
4901        manifest.segments.len(),
4902    )
4903    .map_err(|error| match (admission.is_some(), error) {
4904        (true, HawDBError::Storage(message)) => HawDBError::Execution(message),
4905        (_, error) => error,
4906    })?;
4907    let allocation_error = |message| {
4908        if admission.is_some() {
4909            HawDBError::Execution(message)
4910        } else {
4911            HawDBError::Storage(message)
4912        }
4913    };
4914    let mut mutation_runs = Vec::new();
4915    mutation_runs
4916        .try_reserve_exact(manifest.mutation_runs.len())
4917        .map_err(|error| {
4918            allocation_error(format!(
4919                "search mutation-run list allocation failed: {error}"
4920            ))
4921        })?;
4922    if mutation_runs.capacity() > manifest.mutation_runs.len() {
4923        return Err(allocation_error(
4924            "search mutation-run list exceeded admitted capacity".into(),
4925        ));
4926    }
4927    let analyzer_digest = if manifest.mutation_runs.is_empty() {
4928        0
4929    } else {
4930        match admission {
4931            Some(admission) => crate::lexical_projection::analyzer_digest_with_context(
4932                analyzer_lexicon,
4933                admission.task,
4934            )?,
4935            None => lexical_analyzer_digest(analyzer_lexicon),
4936        }
4937    };
4938    for run in &manifest.mutation_runs {
4939        checkpoint()?;
4940        let opened = match (admission, capture) {
4941            (Some(_), Some(capture)) => mutation_run::SearchMutationRun::open_for_capture(
4942                root,
4943                run,
4944                config.max_mutation_run_bytes.get(),
4945                analyzer_digest,
4946                &mut mutation_budget,
4947                capture,
4948                max_artifact_read_bytes,
4949            ),
4950            (Some(admission), None) if cleanup_source.is_some() => {
4951                mutation_run::SearchMutationRun::open_for_cleanup(
4952                    root,
4953                    run,
4954                    &mut mutation_budget,
4955                    cleanup_source.unwrap(),
4956                    admission,
4957                    (config.max_mutation_run_bytes.get(), max_artifact_read_bytes),
4958                    analyzer_digest,
4959                )
4960            }
4961            (Some(_), None) => mutation_run::SearchMutationRun::open_with_read_admission(
4962                root,
4963                run,
4964                config.max_mutation_run_bytes.get(),
4965                analyzer_digest,
4966                &mut mutation_budget,
4967                admission,
4968                max_artifact_read_bytes,
4969            ),
4970            (None, _) if cleanup_source.is_some() => {
4971                if run.len > config.max_mutation_run_bytes.get() {
4972                    return Err(HawDBError::Execution(
4973                        "captured cleanup mutation exceeds read ceiling".into(),
4974                    ));
4975                }
4976                mutation_run::SearchMutationRun::open_ordinary_file(
4977                    cleanup_source.unwrap().open(&run.file, run.object)?,
4978                    run,
4979                    config.max_mutation_run_bytes.get(),
4980                    analyzer_digest,
4981                    &mut mutation_budget,
4982                )
4983            }
4984            (None, _) => mutation_run::SearchMutationRun::open(
4985                root,
4986                run,
4987                config.max_mutation_run_bytes.get(),
4988                analyzer_digest,
4989                &mut mutation_budget,
4990            ),
4991        };
4992        mutation_runs.push(opened?);
4993    }
4994    let _validation_memory = admission
4995        .map(|admission| {
4996            use crate::build_memory::{checked_add, checked_mul, SET_ENTRY_BYTES};
4997            let entries = manifest
4998                .mutation_runs
4999                .iter()
5000                .try_fold(0usize, |count, run| {
5001                    checkpoint()?;
5002                    checked_add(count, run.entry_count)
5003                })?;
5004            admission.scratch(checked_mul(
5005                checked_add(manifest.segments.len(), entries)?,
5006                SET_ENTRY_BYTES,
5007            )?)
5008        })
5009        .transpose()?;
5010    match admission {
5011        Some(admission) => mutation_run::validate_closure_with_context(
5012            &manifest,
5013            &mutation_runs,
5014            Some(admission.task),
5015        )?,
5016        None => mutation_run::validate_closure(&manifest, &mutation_runs)?,
5017    }
5018    let targets_to_validate = mutation_runs
5019        .iter()
5020        .zip(&manifest.mutation_runs)
5021        .filter_map(|(run, reference)| {
5022            let reusable = previous
5023                .and_then(|reader| {
5024                    let index = reader
5025                        .manifest
5026                        .mutation_runs
5027                        .iter()
5028                        .position(|candidate| candidate == reference)?;
5029                    if run.entries().iter().all(|entry| {
5030                        let target = manifest
5031                            .segments
5032                            .iter()
5033                            .find(|segment| segment.segment_id == entry.target_segment_id);
5034                        target.is_some_and(|target| reader.manifest.segments.contains(target))
5035                    }) {
5036                        reader.visibility.vector_retraction_count(index)
5037                    } else {
5038                        None
5039                    }
5040                })
5041                .is_some_and(|count| run.record_vector_retraction_count(count).is_ok());
5042            if reusable {
5043                refresh.reused_retractions += run.entries().len();
5044                None
5045            } else {
5046                refresh.validated_retractions += run.entries().len();
5047                Some(run)
5048            }
5049        });
5050    mutation_run::validate_targets_with_admission(
5051        root,
5052        &segments,
5053        targets_to_validate,
5054        config,
5055        analyzer_lexicon,
5056        lexical_source_policy,
5057        mutation_run::TargetValidationContext {
5058            admission: admission.map(|admission| (admission, max_artifact_read_bytes)),
5059            source: validation_source.or(cleanup_source),
5060            capture,
5061        },
5062    )?;
5063    checkpoint()?;
5064    Ok(LoadedArtifactClosure {
5065        manifest,
5066        segments,
5067        visibility: mutation_run::MutationVisibility::from_validated_runs(mutation_runs),
5068        refresh,
5069        collections_memory,
5070    })
5071}
5072
5073pub(super) struct PublishedArtifactGenerations {
5074    pub(super) active_generation: u64,
5075    pub(super) lexical_generations: BTreeSet<u64>,
5076    pub(super) out_of_core_generations: BTreeSet<u64>,
5077    pub(super) rabitq_generations: BTreeSet<u64>,
5078}
5079
5080/// Returns the advanced source epoch when the selector records a verified
5081/// metadata-only advance past the snapshot's stamp (#1756).
5082pub(super) fn validate_resident_snapshot_identity(
5083    index: &SearchIndex,
5084    root: &Path,
5085) -> Result<Option<u64>> {
5086    let path = root.join(OUT_OF_CORE_MANIFEST_FILE);
5087    if !fs::try_exists(&path)? {
5088        return Ok(None);
5089    }
5090    let bytes = read_bounded_file(&path, MAX_OUT_OF_CORE_MANIFEST_BYTES)?;
5091    validate_resident_snapshot_manifest(index, &bytes)
5092}
5093
5094pub(super) fn validate_captured_resident_snapshot_identity(
5095    index: &SearchIndex,
5096    publication: &SearchProjectionPublishLease,
5097) -> Result<Option<u64>> {
5098    let file = match publication.open_captured_child(OUT_OF_CORE_MANIFEST_FILE) {
5099        Ok(file) => file,
5100        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
5101        Err(error) => return Err(error.into()),
5102    };
5103    let bytes = crate::bounded_file::read_bounded_open_file(
5104        file,
5105        OUT_OF_CORE_MANIFEST_FILE,
5106        MAX_OUT_OF_CORE_MANIFEST_BYTES,
5107    )?;
5108    validate_resident_snapshot_manifest(index, &bytes)
5109}
5110
5111pub(super) fn validate_registered_artifact_closure(
5112    index: &SearchIndex,
5113    publication: &SearchProjectionPublishLease,
5114) -> Result<()> {
5115    let task = hawdb_core::RuntimeTaskContext::default();
5116    let source = captured_cleanup::Source::new(
5117        publication,
5118        &task,
5119        captured_cleanup::Limits {
5120            artifact_bytes: u64::MAX,
5121            total_bytes: u64::MAX,
5122            files: usize::MAX,
5123        },
5124    );
5125    let bytes = source.head()?.ok_or_else(|| {
5126        HawDBError::StorageIntegrity("missing registered out-of-core manifest".into())
5127    })?;
5128    let manifest = SearchOutOfCoreManifestBody::decode(&bytes)?;
5129    let config = SearchOutOfCoreConfig::default();
5130    let closure = load_artifact_closure_with_context(
5131        ClosureLoadContext {
5132            cleanup_source: Some(&source),
5133            validation_source: Some(&source),
5134            capture: None,
5135            root: index
5136                .path
5137                .as_deref()
5138                .expect("persistent registered projection"),
5139            config: &config,
5140            analyzer_lexicon: &index.analyzer_lexicon,
5141            lexical_term_policy: Default::default(),
5142            lexical_source_policy: Default::default(),
5143            previous: None,
5144            admission: None,
5145            max_artifact_read_bytes: u64::MAX,
5146        },
5147        manifest,
5148    )?;
5149    if closure.manifest.source_graph_commit_epoch != index.source_graph_commit_epoch
5150        || closure.manifest.document_count != index.documents.len()
5151    {
5152        return Err(HawDBError::StorageIntegrity(
5153            "registered generation does not match its snapshot".into(),
5154        ));
5155    }
5156    Ok(())
5157}
5158
5159/// Compares the in-memory resident projection with the published selector.
5160/// Epochs compare by content stamp: the snapshot and the lexical and vector
5161/// artifacts it validates were written at the selector's content epoch, which
5162/// a metadata-only advance (#1756) leaves behind its source epoch.
5163pub(super) fn validate_resident_snapshot_manifest(
5164    index: &SearchIndex,
5165    bytes: &[u8],
5166) -> Result<Option<u64>> {
5167    let manifest = SearchOutOfCoreManifestBody::decode(bytes)?;
5168    let manifest_content_epoch = manifest
5169        .content_source_graph_commit_epoch
5170        .or(manifest.source_graph_commit_epoch);
5171    let embedding = index.embedding_manifest.as_ref();
5172    let summary = index.vector_document_summary;
5173    let digest = summary.map_or_else(
5174        || lexical_documents_digest(&index.documents),
5175        |summary| summary.documents_digest,
5176    );
5177    let snapshot_mismatch = summary.is_some_and(|summary| {
5178        !manifest.resident_snapshot.is_some_and(|snapshot| {
5179            snapshot.metadata_only
5180                && snapshot.vector_document_count == summary.vector_document_count
5181        })
5182    }) || manifest
5183        .resident_snapshot
5184        .is_some_and(|snapshot| snapshot.metadata_only != summary.is_some());
5185    if snapshot_mismatch
5186        || manifest.document_count != index.document_count()
5187        || manifest.documents_digest != digest
5188        || manifest_content_epoch != index.artifact_source_graph_commit_epoch()
5189        || manifest.import_source_graph_commit_epoch != index.import_source_graph_commit_epoch
5190        || manifest.vector_scoring != index.vector_scoring
5191        || manifest.embedding_dimension != index.embedding_dimension
5192        || manifest.vector_index_binding
5193            != index
5194                .vector_index_descriptor
5195                .as_ref()
5196                .map(crate::vector_index::encode)
5197        || manifest.embedding_model.as_deref() != embedding.map(|identity| identity.model.as_str())
5198        || manifest.embedding_version.as_deref()
5199            != embedding.and_then(|identity| identity.version.as_deref())
5200    {
5201        return Err(HawDBError::SearchProjectionMismatch {
5202            projection: index.path.clone(),
5203            message: "resident search snapshot does not match the published immutable projection; incremental catch-up cannot repair it: rebuild it from the graph into a new directory with EmbeddedStoreHandle::rebuild_out_of_core_search_projection, or rebuild a resident projection with Database::rebuild_search_projection".into(),
5204        });
5205    }
5206    Ok(manifest
5207        .content_source_graph_commit_epoch
5208        .and(manifest.source_graph_commit_epoch))
5209}
5210
5211#[cfg(test)]
5212pub(super) fn published_artifact_generations(
5213    root: &Path,
5214    analyzer_lexicon: &SearchAnalyzerLexicon,
5215) -> Result<Option<PublishedArtifactGenerations>> {
5216    let manifest_path = root.join(OUT_OF_CORE_MANIFEST_FILE);
5217    if !fs::try_exists(&manifest_path)? {
5218        return Ok(None);
5219    }
5220    let bytes = read_bounded_file(&manifest_path, MAX_OUT_OF_CORE_MANIFEST_BYTES)?;
5221    let manifest = SearchOutOfCoreManifestBody::decode(&bytes)?;
5222    let closure = load_artifact_closure_for_manifest(
5223        root,
5224        &SearchOutOfCoreConfig::default(),
5225        analyzer_lexicon,
5226        Default::default(),
5227        Default::default(),
5228        manifest,
5229        None,
5230    )?;
5231    Ok(Some(artifact_generations(&closure)))
5232}
5233
5234pub(super) struct CapturedGenerations {
5235    pub(super) generations: Option<PublishedArtifactGenerations>,
5236    pub(super) memory: Option<crate::build_memory::read::ReaderMemory>,
5237    pub(super) resident_vector_absence_verified: bool,
5238    pub(super) resident_vector_receipt_verified: bool,
5239    pub(super) work: captured_cleanup::VerificationWork,
5240}
5241
5242pub(super) fn captured_artifact_generations(
5243    root_label: &Path,
5244    publication: &SearchProjectionPublishLease,
5245    analyzer_lexicon: &SearchAnalyzerLexicon,
5246    task: &hawdb_core::RuntimeTaskContext,
5247    options: crate::SearchProjectionCleanupOptions,
5248    admission: Option<&crate::build_memory::read::ReadAdmission<'_>>,
5249) -> Result<CapturedGenerations> {
5250    let task = admission.map_or(task, |admission| admission.task);
5251    let limits = captured_cleanup::Limits {
5252        artifact_bytes: options.max_verification_bytes.get(),
5253        total_bytes: options.max_verification_bytes.get(),
5254        files: options.max_verification_files.get(),
5255    };
5256    let source = captured_cleanup::Source::new(publication, task, limits);
5257    let config = SearchOutOfCoreConfig::default();
5258    match admission {
5259        Some(admission) => {
5260            let capture = if admission.is_synchronous() {
5261                None
5262            } else {
5263                Some(publication.cleanup_capture(admission)?)
5264            };
5265            let Some(file) = source.head_file(Some(admission))? else {
5266                source.prove_no_projection_files(root_label, Some(admission))?;
5267                return Ok(CapturedGenerations {
5268                    generations: None,
5269                    memory: None,
5270                    resident_vector_absence_verified: true,
5271                    resident_vector_receipt_verified: false,
5272                    work: source.work(),
5273                });
5274            };
5275            let bytes = admission.read_unbound_file(
5276                &file,
5277                MAX_OUT_OF_CORE_MANIFEST_BYTES.min(limits.total_bytes),
5278            )?;
5279            let _decode =
5280                admission.retained(SearchOutOfCoreManifestBody::decode_capacity(&bytes, task)?)?;
5281            let manifest = SearchOutOfCoreManifestBody::decode_with_context(&bytes, Some(task))?;
5282            // Fresh relative names must match the selected references even if
5283            // the shared FD cache already holds an older unlinked native file.
5284            if !admission.is_synchronous() {
5285                source.verify_manifest(&manifest, Some(admission))?;
5286            }
5287            let resident_vector_absence_verified = source.verify_resident_vector_absence(
5288                manifest.resident_snapshot,
5289                manifest.resident_snapshot_absent,
5290                Some(admission),
5291            )?;
5292            let resident_vector_receipt_verified = manifest.resident_snapshot.is_some();
5293            let records = manifest
5294                .segments
5295                .len()
5296                .checked_mul(4)
5297                .and_then(|n| n.checked_add(manifest.mutation_runs.len()))
5298                .ok_or_else(|| HawDBError::Execution("cleanup retention size overflow".into()))?;
5299            let memory = admission.retained(crate::build_memory::checked_mul(
5300                records,
5301                crate::build_memory::SET_ENTRY_BYTES,
5302            )?)?;
5303            let closure = load_artifact_closure_with_context(
5304                ClosureLoadContext {
5305                    cleanup_source: admission.is_synchronous().then_some(&source),
5306                    validation_source: Some(&source),
5307                    capture: capture.as_ref(),
5308                    root: root_label,
5309                    config: &config,
5310                    analyzer_lexicon,
5311                    lexical_term_policy: Default::default(),
5312                    lexical_source_policy: Default::default(),
5313                    previous: None,
5314                    admission: Some(admission),
5315                    // The verification ceiling bounds re-hashing, which the
5316                    // source enforces (and which skips files this process
5317                    // already verified). Opening the closure only needs each
5318                    // artifact the manifest names; in-memory metadata reads
5319                    // keep their reader-configuration maxima (#1755).
5320                    max_artifact_read_bytes: limits
5321                        .artifact_bytes
5322                        .max(manifest.largest_closure_artifact()),
5323                },
5324                manifest,
5325            )?;
5326            Ok(CapturedGenerations {
5327                generations: Some(artifact_generations(&closure)),
5328                memory: Some(memory),
5329                resident_vector_absence_verified,
5330                resident_vector_receipt_verified,
5331                work: source.work(),
5332            })
5333        }
5334        None => {
5335            if task.memory_reservation().is_some() {
5336                return Err(HawDBError::Execution(
5337                    "bound cleanup requires the originating admission".into(),
5338                ));
5339            }
5340            let _io = task
5341                .acquire_io_wave(std::num::NonZeroUsize::MIN)
5342                .map_err(HawDBError::from_execution_error)?;
5343            let Some(bytes) = source.head()? else {
5344                source.prove_no_projection_files(root_label, None)?;
5345                return Ok(CapturedGenerations {
5346                    generations: None,
5347                    memory: None,
5348                    resident_vector_absence_verified: true,
5349                    resident_vector_receipt_verified: false,
5350                    work: source.work(),
5351                });
5352            };
5353            let manifest = SearchOutOfCoreManifestBody::decode_with_context(&bytes, Some(task))?;
5354            let resident_vector_absence_verified = source.verify_resident_vector_absence(
5355                manifest.resident_snapshot,
5356                manifest.resident_snapshot_absent,
5357                None,
5358            )?;
5359            let resident_vector_receipt_verified = manifest.resident_snapshot.is_some();
5360            let closure = load_artifact_closure_with_context(
5361                ClosureLoadContext {
5362                    cleanup_source: Some(&source),
5363                    validation_source: Some(&source),
5364                    capture: None,
5365                    root: root_label,
5366                    config: &config,
5367                    analyzer_lexicon,
5368                    lexical_term_policy: Default::default(),
5369                    lexical_source_policy: Default::default(),
5370                    previous: None,
5371                    admission: None,
5372                    max_artifact_read_bytes: limits.artifact_bytes,
5373                },
5374                manifest,
5375            )?;
5376            Ok(CapturedGenerations {
5377                generations: Some(artifact_generations(&closure)),
5378                memory: None,
5379                resident_vector_absence_verified,
5380                resident_vector_receipt_verified,
5381                work: source.work(),
5382            })
5383        }
5384    }
5385}
5386
5387impl SearchOutOfCoreManifestBody {
5388    /// Length of the largest artifact this manifest's closure names.
5389    fn largest_closure_artifact(&self) -> u64 {
5390        let segments = self.segments.iter().flat_map(|segment| {
5391            let objects = segment.objects;
5392            [
5393                objects.descriptor,
5394                objects.payload,
5395                objects.metadata,
5396                objects.vector,
5397                objects.layout,
5398                objects.lexical_manifest,
5399                objects.lexical_payload,
5400            ]
5401            .into_iter()
5402            .chain(objects.rabitq)
5403            .map(|object| object.byte_length)
5404        });
5405        let runs = self.mutation_runs.iter().map(|run| run.object.byte_length);
5406        segments.chain(runs).max().unwrap_or(0)
5407    }
5408}
5409
5410fn artifact_generations(closure: &LoadedArtifactClosure) -> PublishedArtifactGenerations {
5411    let manifest = &closure.manifest;
5412    let mut lexical_generations = BTreeSet::new();
5413    let mut out_of_core_generations = BTreeSet::new();
5414    let mut rabitq_generations = BTreeSet::new();
5415    for artifact in &manifest.segments {
5416        lexical_generations.insert(artifact.generation);
5417        lexical_generations.insert(artifact.objects.lexical_generation);
5418        out_of_core_generations.insert(artifact.generation);
5419        if artifact.rabitq_artifact_file.is_some() {
5420            rabitq_generations.insert(artifact.generation);
5421        }
5422    }
5423    out_of_core_generations.extend(manifest.mutation_runs.iter().map(|run| run.generation));
5424    PublishedArtifactGenerations {
5425        active_generation: manifest.generation,
5426        lexical_generations,
5427        out_of_core_generations,
5428        rabitq_generations,
5429    }
5430}
5431
5432struct ResidentProducerReferences {
5433    descriptor: ArtifactObject,
5434    payload: ArtifactObject,
5435    lexical_generation: u64,
5436    lexical: crate::lexical_projection::ProducerReferences,
5437}
5438
5439#[cfg(feature = "vector-search")]
5440pub(super) struct ResidentRaBitQArtifact {
5441    pub(super) reference: hawdb_storage::immutable_object::ObjectReference,
5442    pub(super) checksum: u64,
5443    pub(super) source_digest: u64,
5444    pub(super) vector_document_count: usize,
5445    pub(super) payload_checksum: u32,
5446    pub(super) peak_build_working_bytes: usize,
5447    pub(super) diskann_source_digest: Option<[u8; 32]>,
5448}
5449
5450pub(super) struct ResidentPublicationPlan {
5451    pub(super) generation: u64,
5452    /// Write only generation-named artifacts, publish the selector, then
5453    /// install the unsuffixed current names as aliases. See
5454    /// [`recover_resident_aliases`] for the reopen half of this protocol.
5455    pub(super) deferred_aliases: bool,
5456    #[cfg(feature = "vector-search")]
5457    pub(super) rabitq: Option<ResidentRaBitQArtifact>,
5458}
5459
5460pub(super) fn write_resident_artifacts(
5461    index: &SearchIndex,
5462    root: &Path,
5463    snapshot: &crate::snapshot_writer::SearchSnapshotWriteReport,
5464    plan: ResidentPublicationPlan,
5465    task: &hawdb_core::RuntimeTaskContext,
5466) -> Result<PublishedOutOfCoreProjection> {
5467    let generation = plan.generation;
5468    let memory = crate::build_memory::BuildMemory::new(task)?;
5469    let io = generation_writer::io::GenerationIo::new(&memory, task);
5470    let mut descriptor = SearchSegmentDescriptor::build(&index.documents);
5471    let (payload_name, descriptor_name) = if plan.deferred_aliases {
5472        (
5473            format!("search_projection_segment_payloads.{generation}.hawdb"),
5474            format!("search_projection_segments.{generation}.hawdb"),
5475        )
5476    } else {
5477        (
5478            SEARCH_SEGMENT_PAYLOAD_FILE.to_owned(),
5479            SEARCH_SEGMENT_DESCRIPTOR_FILE.to_owned(),
5480        )
5481    };
5482    let payload = super::write_search_segment_payloads(
5483        root,
5484        &payload_name,
5485        &index.documents,
5486        &mut descriptor,
5487        |file| ArtifactObject::from_reference(io.seal_file(file)?.reference),
5488    )?;
5489    let (descriptor_bytes, descriptor_object) = super::write_search_segment_descriptor_output(
5490        root,
5491        &descriptor_name,
5492        &descriptor,
5493        u64::MAX,
5494        |file| ArtifactObject::from_reference(io.seal_file(file)?.reference),
5495    )?;
5496    #[cfg(test)]
5497    resident_checkpoint_fault(ResidentCheckpointStep::SegmentArtifacts)?;
5498    let lexical_generation = generation;
5499    let writer = super::LexicalProjectionWriter::new(index.lexical_config)
5500        .with_context(memory.clone(), task.clone());
5501    let writer = if plan.deferred_aliases {
5502        writer.with_generation_manifest()
5503    } else {
5504        writer
5505    };
5506    let projection = writer.write(
5507        root,
5508        lexical_generation,
5509        index.source_graph_commit_epoch,
5510        lexical_analyzer_digest(&index.analyzer_lexicon),
5511        lexical_documents_digest(&index.documents),
5512        index.documents.values(),
5513        &index.analyzer_lexicon,
5514    )?;
5515    let lexical = projection.producer_references().ok_or_else(|| {
5516        HawDBError::StorageIntegrity(
5517            "resident checkpoint requires lexical producer references".into(),
5518        )
5519    })?;
5520    let producer_bytes = descriptor_bytes
5521        .saturating_add(payload.byte_length)
5522        .saturating_add(lexical.manifest.byte_length)
5523        .saturating_add(lexical.artifact.byte_length);
5524    index.replace_lexical_projection(Some(projection));
5525    #[cfg(test)]
5526    resident_checkpoint_fault(ResidentCheckpointStep::Lexical)?;
5527    let mut published = publish_out_of_core_projection(
5528        index,
5529        root,
5530        snapshot,
5531        &descriptor,
5532        plan,
5533        ResidentProducerReferences {
5534            descriptor: descriptor_object,
5535            payload,
5536            lexical_generation,
5537            lexical,
5538        },
5539        &io,
5540    )?;
5541    published.bytes_written = published.bytes_written.saturating_add(producer_bytes);
5542    Ok(published)
5543}
5544
5545fn publish_out_of_core_projection(
5546    index: &SearchIndex,
5547    root: &Path,
5548    snapshot: &crate::snapshot_writer::SearchSnapshotWriteReport,
5549    descriptor: &SearchSegmentDescriptor,
5550    plan: ResidentPublicationPlan,
5551    producer: ResidentProducerReferences,
5552    io: &generation_writer::io::GenerationIo<'_>,
5553) -> Result<PublishedOutOfCoreProjection> {
5554    let generation = plan.generation;
5555    #[cfg(feature = "vector-search")]
5556    let rabitq = plan.rabitq;
5557    if !descriptor.matches_documents(&index.documents) {
5558        return Err(HawDBError::Storage(
5559            "search segment descriptor does not match checkpoint documents".to_string(),
5560        ));
5561    }
5562    let descriptor_file = format!("search_projection_segments.{generation}.hawdb");
5563    let payload_file = format!("search_projection_segment_payloads.{generation}.hawdb");
5564    let metadata_payload_file = format!("search_projection_metadata_payloads.{generation}.hawdb");
5565    let vector_payload_file = format!("search_projection_vector_payloads.{generation}.hawdb");
5566    let layout_file = format!("search_projection_out_of_core_layout.{generation}.hawdb");
5567    let lexical_manifest_file = format!("search_lexical.manifest.{generation}.hawdb");
5568    let mut bytes_written = 0u64;
5569    if !plan.deferred_aliases {
5570        // Legacy registered order: current names were written first and are
5571        // linked to their generation names before the selector.
5572        for (current, generation_file) in [
5573            (SEARCH_SEGMENT_DESCRIPTOR_FILE, &descriptor_file),
5574            (SEARCH_SEGMENT_PAYLOAD_FILE, &payload_file),
5575            (MANIFEST_FILE, &lexical_manifest_file),
5576        ] {
5577            bytes_written = bytes_written
5578                .saturating_add(io.link(&root.join(current), &root.join(generation_file))?);
5579        }
5580    }
5581
5582    let (layout, metadata_object, vector_object) = write_out_of_core_sidecars(
5583        index,
5584        descriptor,
5585        generation,
5586        &root.join(&metadata_payload_file),
5587        &root.join(&vector_payload_file),
5588        io,
5589    )?;
5590    let metadata_payload_len = metadata_object.byte_length;
5591    let vector_payload_len = vector_object.byte_length;
5592    let layout_bytes = layout.encode()?;
5593    let layout_object = ArtifactObject::for_bytes(&layout_bytes);
5594    bytes_written = bytes_written.saturating_add(write_generation_artifact(
5595        &root.join(&layout_file),
5596        &layout_bytes,
5597    )?);
5598    bytes_written = bytes_written
5599        .saturating_add(metadata_payload_len)
5600        .saturating_add(vector_payload_len);
5601
5602    let descriptor_bytes = fs::read(root.join(&descriptor_file))?;
5603    let lexical_manifest_bytes = fs::read(root.join(&lexical_manifest_file))?;
5604    let lexical_payload_file =
5605        crate::lexical_projection::artifact_file(producer.lexical_generation);
5606    let lexical_manifest_object = ArtifactObject::from_reference(producer.lexical.manifest)?;
5607    let lexical_payload_object = ArtifactObject::from_reference(producer.lexical.artifact)?;
5608    #[cfg(test)]
5609    AFTER_RESIDENT_SIDECARS.with(|hook| {
5610        if let Some(index) = hook.take() {
5611            let snapshot_file = crate::resident_snapshot_file(generation);
5612            let name = [
5613                &metadata_payload_file,
5614                &vector_payload_file,
5615                &layout_file,
5616                &descriptor_file,
5617                &payload_file,
5618                &lexical_manifest_file,
5619                &lexical_payload_file,
5620                &snapshot_file,
5621            ][index];
5622            let path = root.join(name);
5623            let mut bytes = fs::read(&path).unwrap();
5624            bytes[0] ^= 1;
5625            fs::write(&path, bytes).unwrap();
5626        }
5627    });
5628    for (name, object) in [
5629        (&metadata_payload_file, metadata_object),
5630        (&vector_payload_file, vector_object),
5631        (&layout_file, layout_object),
5632        (&descriptor_file, producer.descriptor),
5633        (&payload_file, producer.payload),
5634        (&lexical_manifest_file, lexical_manifest_object),
5635        (&lexical_payload_file, lexical_payload_object),
5636    ] {
5637        io.verify_object(&root.join(name), object)?;
5638    }
5639    if plan.deferred_aliases {
5640        // The selector's receipt is the writer's in-memory reference. Bind it
5641        // to the installed generation snapshot before the selector names it.
5642        io.verify_object(
5643            &root.join(crate::resident_snapshot_file(generation)),
5644            ArtifactObject::from_reference(snapshot.encoded_object)?,
5645        )?;
5646    }
5647    // The writer counted the vectors it encoded into exactly these bytes;
5648    // cleanup uses the count only for a snapshot inode verified above.
5649    captured_cleanup::remember_resident_vector_count(
5650        snapshot.encoded_object,
5651        snapshot.vector_document_count,
5652    );
5653    #[cfg(feature = "vector-search")]
5654    if let Some(artifact) = rabitq.as_ref() {
5655        io.verify_object(
5656            &root.join(format!("search_rabitq.{generation}.hawdb")),
5657            ArtifactObject::from_reference(artifact.reference)?,
5658        )?;
5659    }
5660    let objects = SegmentObjects {
5661        lexical_generation: producer.lexical_generation,
5662        descriptor: producer.descriptor,
5663        payload: producer.payload,
5664        metadata: metadata_object,
5665        vector: vector_object,
5666        layout: layout_object,
5667        lexical_manifest: lexical_manifest_object,
5668        lexical_payload: lexical_payload_object,
5669        #[cfg(feature = "vector-search")]
5670        rabitq: rabitq
5671            .as_ref()
5672            .map(|artifact| ArtifactObject::from_reference(artifact.reference))
5673            .transpose()?,
5674        #[cfg(not(feature = "vector-search"))]
5675        rabitq: None,
5676    };
5677    let embedding = index.embedding_manifest.as_ref();
5678    let manifest = SearchOutOfCoreManifestBody {
5679        format: OUT_OF_CORE_FORMAT.to_string(),
5680        format_version: manifest_version::BASE_VERSION,
5681        min_reader_version: manifest_version::BASE_VERSION,
5682        generation,
5683        resident_snapshot: Some(ResidentSnapshot {
5684            object: ArtifactObject::from_reference(snapshot.encoded_object)?,
5685            vector_document_count: snapshot.vector_document_count,
5686            metadata_only: false,
5687        }),
5688        resident_snapshot_absent: false,
5689        segments: vec![SearchOutOfCoreSegmentManifest {
5690            #[cfg(feature = "vector-search")]
5691            diskann_source_digest: rabitq
5692                .as_ref()
5693                .and_then(|artifact| artifact.diskann_source_digest),
5694            #[cfg(not(feature = "vector-search"))]
5695            diskann_source_digest: None,
5696            objects,
5697            segment_id: 0,
5698            level: 0,
5699            generation,
5700            descriptor_file,
5701            descriptor_len: descriptor_bytes.len() as u64,
5702            descriptor_checksum: checksum_bytes(&descriptor_bytes),
5703            payload_file,
5704            payload_len: fs::metadata(root.join(format!(
5705                "search_projection_segment_payloads.{generation}.hawdb"
5706            )))?
5707            .len(),
5708            metadata_payload_file,
5709            metadata_payload_len,
5710            vector_payload_file,
5711            vector_payload_len,
5712            layout_file,
5713            layout_len: layout_bytes.len() as u64,
5714            layout_checksum: checksum_bytes(&layout_bytes),
5715            lexical_manifest_file,
5716            lexical_manifest_len: lexical_manifest_bytes.len() as u64,
5717            lexical_manifest_checksum: checksum_bytes(&lexical_manifest_bytes),
5718            #[cfg(feature = "vector-search")]
5719            rabitq_artifact_file: rabitq
5720                .as_ref()
5721                .map(|_| format!("search_rabitq.{generation}.hawdb")),
5722            #[cfg(not(feature = "vector-search"))]
5723            rabitq_artifact_file: None,
5724            #[cfg(feature = "vector-search")]
5725            rabitq_artifact_len: rabitq
5726                .as_ref()
5727                .map(|artifact| artifact.reference.byte_length),
5728            #[cfg(not(feature = "vector-search"))]
5729            rabitq_artifact_len: None,
5730            #[cfg(feature = "vector-search")]
5731            rabitq_artifact_checksum: rabitq.as_ref().map(|artifact| artifact.checksum),
5732            #[cfg(not(feature = "vector-search"))]
5733            rabitq_artifact_checksum: None,
5734            #[cfg(feature = "vector-search")]
5735            rabitq_source_digest: rabitq.as_ref().map(|artifact| artifact.source_digest),
5736            #[cfg(not(feature = "vector-search"))]
5737            rabitq_source_digest: None,
5738            #[cfg(feature = "vector-search")]
5739            rabitq_vector_document_count: rabitq
5740                .as_ref()
5741                .map(|artifact| artifact.vector_document_count),
5742            #[cfg(not(feature = "vector-search"))]
5743            rabitq_vector_document_count: None,
5744            #[cfg(feature = "vector-search")]
5745            rabitq_payload_checksum: rabitq.as_ref().map(|artifact| artifact.payload_checksum),
5746            #[cfg(not(feature = "vector-search"))]
5747            rabitq_payload_checksum: None,
5748            #[cfg(feature = "vector-search")]
5749            rabitq_peak_build_working_bytes: rabitq
5750                .as_ref()
5751                .map(|artifact| artifact.peak_build_working_bytes),
5752            #[cfg(not(feature = "vector-search"))]
5753            rabitq_peak_build_working_bytes: None,
5754            document_count: index.documents.len(),
5755            documents_digest: lexical_documents_digest(&index.documents),
5756            source_graph_commit_epoch: index.source_graph_commit_epoch,
5757            // The resident descriptor keeps complete value sets (V3).
5758            descriptor_version: None,
5759            // The resident snapshot writer frames segments as envelopes.
5760            content_encoding: content_blocks::ContentEncoding::Stream1,
5761        }],
5762        mutation_runs: Vec::new(),
5763        document_count: index.documents.len(),
5764        documents_digest: lexical_documents_digest(&index.documents),
5765        source_graph_commit_epoch: index.source_graph_commit_epoch,
5766        content_source_graph_commit_epoch: None,
5767        import_source_graph_commit_epoch: index.import_source_graph_commit_epoch,
5768        embedding_model: embedding.map(|manifest| manifest.model.clone()),
5769        embedding_version: embedding.and_then(|manifest| manifest.version.clone()),
5770        embedding_dimension: embedding
5771            .map(|manifest| manifest.dimension)
5772            .or(index.embedding_dimension),
5773        vector_scoring: index.vector_scoring,
5774        vector_index_binding: index
5775            .vector_index_descriptor
5776            .as_ref()
5777            .map(crate::vector_index::encode),
5778    };
5779    let manifest_path = root.join(OUT_OF_CORE_MANIFEST_FILE);
5780    let tmp_path = manifest_path.with_extension(format!("tmp.{generation}"));
5781    let manifest_bytes = manifest.encode()?;
5782    {
5783        let mut file = File::create(&tmp_path)?;
5784        file.write_all(&manifest_bytes)?;
5785        file.sync_all()?;
5786    }
5787    #[cfg(test)]
5788    resident_checkpoint_fault(ResidentCheckpointStep::BeforeSelector)?;
5789    durable_replace_file(&tmp_path, &manifest_path)?;
5790    // The selector rename above is the commit point. Aliases are derived
5791    // names; reopen re-derives them if this process stops before they land.
5792    if plan.deferred_aliases {
5793        #[cfg(test)]
5794        resident_checkpoint_fault(ResidentCheckpointStep::AfterSelector)?;
5795        for (current, generation_file) in resident_aliases(generation) {
5796            bytes_written = bytes_written
5797                .saturating_add(io.link(&root.join(generation_file), &root.join(current))?);
5798            #[cfg(test)]
5799            resident_checkpoint_fault(ResidentCheckpointStep::AfterAlias(current))?;
5800        }
5801    }
5802    Ok(PublishedOutOfCoreProjection {
5803        generation,
5804        bytes_written: bytes_written.saturating_add(manifest_bytes.len() as u64),
5805    })
5806}
5807
5808/// Current (unsuffixed) names and the generation names they alias, in the
5809/// order a resident checkpoint installs them after its selector.
5810fn resident_aliases(generation: u64) -> [(&'static str, String); 4] {
5811    [
5812        (
5813            crate::SEARCH_SNAPSHOT_FILE,
5814            crate::resident_snapshot_file(generation),
5815        ),
5816        // The payload precedes the descriptor that addresses its ranges.
5817        (
5818            SEARCH_SEGMENT_PAYLOAD_FILE,
5819            format!("search_projection_segment_payloads.{generation}.hawdb"),
5820        ),
5821        (
5822            SEARCH_SEGMENT_DESCRIPTOR_FILE,
5823            format!("search_projection_segments.{generation}.hawdb"),
5824        ),
5825        (
5826            MANIFEST_FILE,
5827            crate::lexical_projection::generation_manifest_file(generation),
5828        ),
5829    ]
5830}
5831
5832/// Steps of a resident checkpoint at which tests stop it as a process abort
5833/// would: every earlier file operation has completed and nothing later runs.
5834#[cfg(test)]
5835#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5836pub(crate) enum ResidentCheckpointStep {
5837    RaBitQ,
5838    Snapshot,
5839    SegmentArtifacts,
5840    Lexical,
5841    BeforeSelector,
5842    AfterSelector,
5843    AfterAlias(&'static str),
5844    Cleanup,
5845    EpochAdvanceBeforeSelector,
5846    EpochAdvanceAfterSelector,
5847}
5848
5849#[cfg(test)]
5850thread_local! {
5851    static RESIDENT_CHECKPOINT_FAULT: std::cell::Cell<Option<ResidentCheckpointStep>> =
5852        const { std::cell::Cell::new(None) };
5853}
5854
5855#[cfg(test)]
5856pub(crate) fn inject_resident_checkpoint_fault(step: Option<ResidentCheckpointStep>) {
5857    RESIDENT_CHECKPOINT_FAULT.with(|fault| fault.set(step));
5858}
5859
5860#[cfg(test)]
5861pub(crate) fn published_generation_for_test(root: &Path) -> u64 {
5862    SearchOutOfCoreManifestBody::decode(&fs::read(root.join(OUT_OF_CORE_MANIFEST_FILE)).unwrap())
5863        .unwrap()
5864        .generation
5865}
5866
5867#[cfg(test)]
5868pub(crate) fn resident_checkpoint_fault(step: ResidentCheckpointStep) -> Result<()> {
5869    if RESIDENT_CHECKPOINT_FAULT.with(|fault| fault.get()) == Some(step) {
5870        RESIDENT_CHECKPOINT_FAULT.with(|fault| fault.set(None));
5871        return Err(HawDBError::Storage(format!(
5872            "injected resident checkpoint abort at {step:?}"
5873        )));
5874    }
5875    Ok(())
5876}
5877
5878/// Reopen half of the resident checkpoint protocol.
5879///
5880/// A resident checkpoint writes every artifact, including its snapshot, under
5881/// generation names and then renames the out-of-core manifest: that rename is
5882/// the single commit point. Only afterwards are the unsuffixed current names
5883/// (`search_projection.hawdb` and the descriptor, payload and lexical
5884/// manifest) replaced by hard links to the selected generation. A process or
5885/// power loss before the selector leaves every current name and the manifest
5886/// at the previous checkpoint. A loss after it leaves some current names one
5887/// generation behind; this repair re-links them from the generation the
5888/// manifest selects, after verifying each source against its manifest object.
5889///
5890/// The repair applies only when the selected generation's own snapshot exists
5891/// and matches the manifest receipt. Older layouts (no generation snapshot)
5892/// and generations published by other writers keep their existing behavior.
5893pub(super) fn recover_resident_aliases(root: &Path) -> Result<()> {
5894    sweep_resident_scratch(root);
5895    let manifest_path = root.join(OUT_OF_CORE_MANIFEST_FILE);
5896    if !fs::try_exists(&manifest_path)? {
5897        return Ok(());
5898    }
5899    let Ok(manifest) = read_bounded_file(&manifest_path, MAX_OUT_OF_CORE_MANIFEST_BYTES)
5900        .and_then(|bytes| SearchOutOfCoreManifestBody::decode(&bytes))
5901    else {
5902        // Existing open validation reports an unreadable selector.
5903        return Ok(());
5904    };
5905    let Some(snapshot) = manifest
5906        .resident_snapshot
5907        .filter(|snapshot| !snapshot.metadata_only)
5908    else {
5909        return Ok(());
5910    };
5911    let [segment] = manifest.segments.as_slice() else {
5912        return Ok(());
5913    };
5914    // A metadata-only epoch advance (#1756) selects the same resident closure
5915    // under a newer selector generation; its aliases still name the content's.
5916    let generation = if manifest.content_source_graph_commit_epoch.is_some() {
5917        segment.generation
5918    } else {
5919        manifest.generation
5920    };
5921    let aliases = resident_aliases(generation);
5922    if !manifest.mutation_runs.is_empty()
5923        || segment.generation != generation
5924        || segment.payload_file != aliases[1].1
5925        || segment.descriptor_file != aliases[2].1
5926        || segment.lexical_manifest_file != aliases[3].1
5927    {
5928        return Ok(());
5929    }
5930    let objects = [
5931        snapshot.object,
5932        segment.objects.payload,
5933        segment.objects.descriptor,
5934        segment.objects.lexical_manifest,
5935    ];
5936    let task = hawdb_core::RuntimeTaskContext::default();
5937    let memory = crate::build_memory::BuildMemory::new(&task)?;
5938    let io = generation_writer::io::GenerationIo::new(&memory, &task);
5939    for (index, ((current, generation_file), object)) in aliases.iter().zip(objects).enumerate() {
5940        let source = root.join(generation_file);
5941        let target = root.join(current);
5942        if !fs::try_exists(&source)? {
5943            if index == 0 {
5944                // Not a deferred-alias publication: nothing to re-derive.
5945                return Ok(());
5946            }
5947            continue;
5948        }
5949        if same_file(&source, &target)?
5950            || (fs::try_exists(&target)? && file_matches_object(&target, object)?)
5951        {
5952            continue;
5953        }
5954        if !file_matches_object(&source, object)? {
5955            if index == 0 {
5956                return Ok(());
5957            }
5958            continue;
5959        }
5960        io.link(&source, &target)?;
5961    }
5962    Ok(())
5963}
5964
5965/// Families a resident checkpoint writes under generation names and then
5966/// aliases. Their scratch names are private to that checkpoint.
5967const RESIDENT_ALIAS_STEMS: [&str; 4] = [
5968    "search_projection",
5969    "search_projection_segment_payloads",
5970    "search_projection_segments",
5971    "search_lexical.manifest",
5972];
5973
5974/// Scratch a resident checkpoint can leave after a crash: an alias link
5975/// temporary (`<stem>.tmp.<pid>.<sequence>`) or a generation file's write
5976/// temporary (`<stem>.<generation>.hawdb.tmp` / `.hawdb.zstd.tmp`). Neither
5977/// is ever selected; a snapshot-sized one would otherwise persist forever.
5978fn is_resident_scratch(name: &str) -> bool {
5979    let digits = |value: &str| !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit());
5980    RESIDENT_ALIAS_STEMS.iter().any(|stem| {
5981        let Some(rest) = name.strip_prefix(stem) else {
5982            return false;
5983        };
5984        if let Some(sequence) = rest.strip_prefix(".tmp.") {
5985            return sequence
5986                .split_once('.')
5987                .is_some_and(|(pid, sequence)| digits(pid) && digits(sequence));
5988        }
5989        rest.strip_prefix('.')
5990            .and_then(|rest| {
5991                rest.strip_suffix(".hawdb.zstd.tmp")
5992                    .or_else(|| rest.strip_suffix(".hawdb.tmp"))
5993            })
5994            .is_some_and(digits)
5995    })
5996}
5997
5998/// Runs only while the caller holds the root's publication lease, so no live
5999/// checkpoint owns any of these names. Best effort, like generation cleanup:
6000/// a name that cannot be removed now is retried on the next open.
6001fn sweep_resident_scratch(root: &Path) {
6002    let Ok(entries) = fs::read_dir(root) else {
6003        return;
6004    };
6005    for entry in entries.flatten() {
6006        if let Some(name) = entry.file_name().to_str()
6007            && is_resident_scratch(name)
6008        {
6009            let _ = fs::remove_file(root.join(name));
6010        }
6011    }
6012}
6013
6014#[cfg(unix)]
6015pub(super) fn same_file(left: &Path, right: &Path) -> Result<bool> {
6016    use std::os::unix::fs::MetadataExt;
6017    let left = fs::metadata(left)?;
6018    let right = match fs::metadata(right) {
6019        Ok(metadata) => metadata,
6020        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
6021        Err(error) => return Err(error.into()),
6022    };
6023    Ok(left.dev() == right.dev() && left.ino() == right.ino())
6024}
6025
6026#[cfg(windows)]
6027pub(super) fn same_file(left: &Path, right: &Path) -> Result<bool> {
6028    let left = File::open(left)?;
6029    match left.matches_native_path(right) {
6030        Ok(same) => Ok(same),
6031        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
6032        Err(error) => Err(error.into()),
6033    }
6034}
6035
6036#[cfg(not(any(unix, windows)))]
6037pub(super) fn same_file(_left: &Path, _right: &Path) -> Result<bool> {
6038    // Keep content verification as the conservative fallback on targets
6039    // without a native file identity implementation.
6040    Ok(false)
6041}
6042
6043fn file_matches_object(path: &Path, object: ArtifactObject) -> Result<bool> {
6044    use hawdb_storage::immutable_object::ObjectReferenceWriter;
6045    let expected = object.reference();
6046    let mut file = File::open(path)?;
6047    if file.metadata()?.len() != expected.byte_length {
6048        return Ok(false);
6049    }
6050    let mut writer =
6051        ObjectReferenceWriter::new(expected.kind, expected.format_version, expected.byte_length)
6052            .map_err(|error| HawDBError::StorageIntegrity(error.to_string()))?;
6053    let mut buffer = vec![0u8; 64 * 1024];
6054    loop {
6055        let read = file.read(&mut buffer)?;
6056        if read == 0 {
6057            break;
6058        }
6059        writer.write_all(&buffer[..read])?;
6060    }
6061    Ok(writer.finish().ok() == Some(expected))
6062}
6063
6064#[cfg(test)]
6065thread_local! {
6066    static AFTER_RESIDENT_SIDECARS: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
6067}
6068
6069fn write_out_of_core_sidecars(
6070    index: &SearchIndex,
6071    descriptor: &SearchSegmentDescriptor,
6072    generation: u64,
6073    metadata_path: &Path,
6074    vector_path: &Path,
6075    io: &generation_writer::io::GenerationIo<'_>,
6076) -> Result<(SearchOutOfCoreLayoutBody, ArtifactObject, ArtifactObject)> {
6077    let metadata_tmp = temporary_artifact_path(metadata_path);
6078    let vector_tmp = temporary_artifact_path(vector_path);
6079    let mut metadata_guard = CandidateFileGuard::new(metadata_tmp.clone());
6080    let mut vector_guard = CandidateFileGuard::new(vector_tmp.clone());
6081    let mut metadata_offset = 0u64;
6082    let mut vector_offset = 0u64;
6083    let mut vector_ordinal = 0u64;
6084    let mut layouts = Vec::with_capacity(descriptor.segments.len());
6085    let metadata_object;
6086    let vector_object;
6087    {
6088        let mut metadata_file = fs::OpenOptions::new()
6089            .read(true)
6090            .write(true)
6091            .create_new(true)
6092            .open(&metadata_tmp)?;
6093        let mut vector_file = fs::OpenOptions::new()
6094            .read(true)
6095            .write(true)
6096            .create_new(true)
6097            .open(&vector_tmp)?;
6098
6099        for segment in &descriptor.segments {
6100            let documents = index
6101                .documents
6102                .range_documents(&segment.first_document_id, &segment.last_document_id)
6103                .map(|(_, document)| document)
6104                .collect::<Vec<_>>();
6105            if documents.len() != segment.document_count {
6106                return Err(HawDBError::Storage(format!(
6107                    "search sidecar segment {} has {} documents, expected {}",
6108                    segment.segment_id,
6109                    documents.len(),
6110                    segment.document_count
6111                )));
6112            }
6113
6114            let mut metadata_body = String::from("HAWDB_SEARCH_METADATA_SEGMENT_V1\n");
6115            let mut vectors = Vec::new();
6116            for &document in &documents {
6117                let document_vector_ordinal = document.embedding.as_ref().map(|_| vector_ordinal);
6118                metadata_body.push_str(&format!(
6119                    "meta\t{}\t{}\t{}\n",
6120                    encode_string(&document.id),
6121                    document_vector_ordinal
6122                        .map(|ordinal| ordinal.to_string())
6123                        .unwrap_or_else(|| "-".to_string()),
6124                    encode_metadata(&document.metadata)
6125                ));
6126                if let Some(embedding) = document.embedding.as_deref() {
6127                    if embedding.is_empty() {
6128                        return Err(HawDBError::Storage(format!(
6129                            "search document {} has an empty embedding",
6130                            document.id
6131                        )));
6132                    }
6133                    vectors.push((document.id.as_str(), embedding));
6134                    vector_ordinal = vector_ordinal.checked_add(1).ok_or_else(|| {
6135                        HawDBError::Storage("search vector ordinal overflow".to_string())
6136                    })?;
6137                }
6138            }
6139            let vector_count = vectors.len();
6140
6141            let metadata_payload = encode_search_snapshot_text(&metadata_body)?;
6142            let mut vector_payload = Vec::new();
6143            vector_segment::encode_into(&vectors, &mut vector_payload, || Ok(()))?;
6144            let metadata = append_sidecar_payload(
6145                &mut metadata_file,
6146                &mut metadata_offset,
6147                &metadata_payload,
6148                segment.document_count,
6149            )?;
6150            let postings = if postings::write_enabled() {
6151                let defaults = SearchOutOfCoreConfig::default();
6152                let limit = defaults
6153                    .max_uncompressed_segment_bytes
6154                    .get()
6155                    .min(defaults.max_compressed_segment_bytes.get());
6156                postings::encode(&documents, None, limit, || Ok(()))?
6157                    .map(|encoded| {
6158                        append_sidecar_payload(
6159                            &mut metadata_file,
6160                            &mut metadata_offset,
6161                            &encoded.payload,
6162                            segment.document_count,
6163                        )
6164                    })
6165                    .transpose()?
6166            } else {
6167                None
6168            };
6169            let vectors = append_sidecar_payload(
6170                &mut vector_file,
6171                &mut vector_offset,
6172                &vector_payload,
6173                vector_count,
6174            )?;
6175            layouts.push(SearchOutOfCoreSegmentLayout {
6176                segment_id: segment.segment_id,
6177                vector_ordinal_base: vector_ordinal.saturating_sub(vector_count as u64),
6178                metadata,
6179                vectors,
6180                postings,
6181            });
6182        }
6183
6184        metadata_file.sync_all()?;
6185        vector_file.sync_all()?;
6186        metadata_object =
6187            ArtifactObject::from_reference(io.seal_file(&mut metadata_file)?.reference)?;
6188        vector_object = ArtifactObject::from_reference(io.seal_file(&mut vector_file)?.reference)?;
6189    }
6190    durable_replace_file(&metadata_tmp, metadata_path)?;
6191    metadata_guard.disarm();
6192    durable_replace_file(&vector_tmp, vector_path)?;
6193    vector_guard.disarm();
6194    Ok((
6195        SearchOutOfCoreLayoutBody {
6196            format: postings::layout_format().to_string(),
6197            generation,
6198            document_count: descriptor.document_count,
6199            segments: layouts,
6200        },
6201        metadata_object,
6202        vector_object,
6203    ))
6204}
6205
6206fn append_sidecar_payload(
6207    file: &mut impl Write,
6208    offset: &mut u64,
6209    payload: &[u8],
6210    entry_count: usize,
6211) -> Result<SearchOutOfCoreRange> {
6212    append_sidecar_payload_with_context(file, offset, payload, entry_count, None)
6213}
6214
6215fn append_sidecar_payload_with_context(
6216    file: &mut impl Write,
6217    offset: &mut u64,
6218    payload: &[u8],
6219    entry_count: usize,
6220    task: Option<&hawdb_core::RuntimeTaskContext>,
6221) -> Result<SearchOutOfCoreRange> {
6222    let length = u64::try_from(payload.len()).map_err(|_| {
6223        HawDBError::Storage("search sidecar payload length exceeds u64".to_string())
6224    })?;
6225    let checksum = crate::build_control::write_checksummed(file, payload, task)?;
6226    let range = SearchOutOfCoreRange {
6227        offset: *offset,
6228        length,
6229        checksum,
6230        entry_count,
6231    };
6232    *offset = offset
6233        .checked_add(length)
6234        .ok_or_else(|| HawDBError::Storage("search sidecar payload offset overflow".to_string()))?;
6235    Ok(range)
6236}
6237
6238enum HydratedHits {
6239    Documents(hydration::query::Loaded),
6240    Sidecars(hydration::sidecar::Hits),
6241}
6242
6243enum HydratedHit {
6244    Document(hydration::query::Document),
6245    Sidecar(SearchDocument),
6246}
6247
6248impl std::ops::Deref for HydratedHit {
6249    type Target = SearchDocument;
6250    fn deref(&self) -> &SearchDocument {
6251        match self {
6252            Self::Document(document) => document,
6253            Self::Sidecar(document) => document,
6254        }
6255    }
6256}
6257
6258impl HydratedHits {
6259    fn remove(&mut self, id: &str) -> Option<HydratedHit> {
6260        match self {
6261            Self::Documents(loaded) => loaded.remove(id).map(HydratedHit::Document),
6262            Self::Sidecars(hits) => hits.values.remove(id).map(HydratedHit::Sidecar),
6263        }
6264    }
6265}
6266
6267struct HitHydrationContext<'a> {
6268    query_terms: &'a BTreeSet<String>,
6269    query_embedding: Option<&'a [f32]>,
6270    mode: SearchMode,
6271    fallback_reason_codes: &'a [SearchFallbackReasonCode],
6272    fallback_reasons: &'a [String],
6273    projection_freshness: &'a SearchProjectionFreshness,
6274    query: Option<crate::lexical_projection::QueryContext<'a>>,
6275    output_memory: query_output::Memory<'a>,
6276}
6277
6278struct CandidateFileGuard {
6279    path: PathBuf,
6280    armed: bool,
6281}
6282
6283impl CandidateFileGuard {
6284    fn new(path: PathBuf) -> Self {
6285        Self { path, armed: true }
6286    }
6287
6288    fn disarm(&mut self) {
6289        self.armed = false;
6290    }
6291}
6292
6293impl Drop for CandidateFileGuard {
6294    fn drop(&mut self) {
6295        if self.armed {
6296            let _ = fs::remove_file(&self.path);
6297        }
6298    }
6299}
6300
6301fn search_document_bytes(document: &SearchDocument) -> u64 {
6302    let scalar = document
6303        .id
6304        .len()
6305        .saturating_add(document.title.len())
6306        .saturating_add(document.content.len())
6307        .saturating_add(
6308            document
6309                .metadata
6310                .iter()
6311                .fold(0usize, |bytes, (key, value)| {
6312                    bytes.saturating_add(key.len()).saturating_add(value.len())
6313                }),
6314        );
6315    let vector = document
6316        .embedding
6317        .as_ref()
6318        .map(|embedding| embedding.len().saturating_mul(std::mem::size_of::<f32>()))
6319        .unwrap_or(0);
6320    scalar.saturating_add(vector) as u64
6321}
6322
6323fn validate_out_of_core_range(
6324    range: SearchOutOfCoreRange,
6325    expected_offset: u64,
6326    artifact_len: u64,
6327    max_compressed_segment_bytes: u64,
6328    segment_id: u64,
6329    kind: &str,
6330) -> Result<()> {
6331    if range.offset != expected_offset || range.length == 0 {
6332        return Err(HawDBError::Storage(format!(
6333            "search segment {segment_id} has an invalid {kind} sidecar range"
6334        )));
6335    }
6336    if range.length > max_compressed_segment_bytes {
6337        return Err(HawDBError::Storage(format!(
6338            "search segment {segment_id} {kind} sidecar requires {} compressed bytes, exceeding {max_compressed_segment_bytes}",
6339            range.length
6340        )));
6341    }
6342    let end = range.offset.checked_add(range.length).ok_or_else(|| {
6343        HawDBError::Storage(format!(
6344            "search segment {segment_id} {kind} sidecar range overflows"
6345        ))
6346    })?;
6347    if end > artifact_len {
6348        return Err(HawDBError::Storage(format!(
6349            "search segment {segment_id} {kind} sidecar exceeds its payload length"
6350        )));
6351    }
6352    Ok(())
6353}
6354
6355fn read_out_of_core_payload_range(
6356    file: &File,
6357    range: SearchOutOfCoreRange,
6358    segment_id: u64,
6359    kind: &str,
6360    metrics: &mut SearchOutOfCoreMetrics,
6361) -> Result<Vec<u8>> {
6362    let length = usize::try_from(range.length).map_err(|_| {
6363        HawDBError::Storage(format!(
6364            "search segment {segment_id} {kind} payload length exceeds the platform address space"
6365        ))
6366    })?;
6367    let mut payload = vec![0u8; length];
6368    read_search_range(file, range.offset, &mut payload)?;
6369    metrics.segment_range_reads = metrics.segment_range_reads.saturating_add(1);
6370    metrics.segment_bytes_read = metrics.segment_bytes_read.saturating_add(range.length);
6371    let actual_checksum = checksum_bytes(&payload);
6372    if actual_checksum != range.checksum {
6373        return Err(HawDBError::Storage(format!(
6374            "search segment {segment_id} {kind} payload checksum mismatch: expected {}, got {actual_checksum}",
6375            range.checksum
6376        )));
6377    }
6378    Ok(payload)
6379}
6380
6381fn decode_metadata_segment(
6382    text: &str,
6383    segment: &SearchSegmentDescriptorEntry,
6384    expected_count: usize,
6385    keys: Option<&crate::MetadataKeys>,
6386) -> Result<Vec<SearchMetadataDocument>> {
6387    let mut lines = text.lines();
6388    if lines.next() != Some("HAWDB_SEARCH_METADATA_SEGMENT_V1") {
6389        return Err(HawDBError::Storage(format!(
6390            "search segment {} metadata sidecar has an invalid header",
6391            segment.segment_id
6392        )));
6393    }
6394    let mut documents = Vec::with_capacity(expected_count);
6395    for line in lines {
6396        let fields = line.split('\t').collect::<Vec<_>>();
6397        match fields.as_slice() {
6398            ["meta", raw_id, raw_vector_ordinal, raw_metadata] => {
6399                documents.push(SearchMetadataDocument {
6400                    id: decode_string(raw_id)?,
6401                    vector_ordinal: decode_optional_vector_ordinal(raw_vector_ordinal)?,
6402                    metadata: crate::decode_metadata_keys(raw_metadata, keys)?,
6403                })
6404            }
6405            _ => {
6406                return Err(HawDBError::Storage(format!(
6407                    "search segment {} has an invalid metadata sidecar line",
6408                    segment.segment_id
6409                )));
6410            }
6411        }
6412    }
6413    if documents.len() != expected_count
6414        || documents.first().map(|document| document.id.as_str())
6415            != Some(segment.first_document_id.as_str())
6416        || documents.last().map(|document| document.id.as_str())
6417            != Some(segment.last_document_id.as_str())
6418        || documents.windows(2).any(|pair| pair[0].id >= pair[1].id)
6419    {
6420        return Err(HawDBError::Storage(format!(
6421            "search segment {} metadata sidecar count, bounds, or ordering mismatch",
6422            segment.segment_id
6423        )));
6424    }
6425    Ok(documents)
6426}
6427
6428fn decode_optional_vector_ordinal(raw: &str) -> Result<Option<u64>> {
6429    if raw == "-" {
6430        return Ok(None);
6431    }
6432    raw.parse::<u64>().map(Some).map_err(|_| {
6433        HawDBError::Storage("search metadata sidecar has an invalid vector ordinal".to_string())
6434    })
6435}
6436
6437fn matched_span_bytes_for(span: &super::SearchMatchedSpan) -> u64 {
6438    (span.field.len() as u64)
6439        .saturating_add(span.text.len() as u64)
6440        .saturating_add(span.term.len() as u64)
6441        .saturating_add(std::mem::size_of::<super::SearchMatchedSpan>() as u64)
6442}
6443
6444fn read_bound_artifact(
6445    path: &Path,
6446    expected_len: u64,
6447    expected_checksum: u64,
6448    max_bytes: u64,
6449    name: &str,
6450) -> Result<Vec<u8>> {
6451    if expected_len > max_bytes {
6452        return Err(HawDBError::Storage(format!(
6453            "{name} exceeds the manifest read budget"
6454        )));
6455    }
6456    let bytes = read_bound_file(path, expected_len, name)?;
6457    if bytes.len() as u64 != expected_len || checksum_bytes(&bytes) != expected_checksum {
6458        return Err(HawDBError::Storage(format!(
6459            "{name} length or checksum mismatch"
6460        )));
6461    }
6462    Ok(bytes)
6463}
6464
6465fn open_exact_length_artifact(path: &Path, expected_len: u64, name: &str) -> Result<File> {
6466    let file = File::open(path)?;
6467    let actual_len = file.metadata()?.len();
6468    if actual_len != expected_len {
6469        return Err(HawDBError::Storage(format!(
6470            "{name} length mismatch: expected {expected_len}, got {actual_len}"
6471        )));
6472    }
6473    Ok(file)
6474}
6475
6476fn read_marker_lines_bounded(path: &Path, max_bytes: u64) -> Result<Vec<String>> {
6477    // Only a missing entry means no marker. Do not hide lookup errors or
6478    // treat an existing but unreadable symlink as proof of freshness.
6479    match fs::symlink_metadata(path) {
6480        Ok(_) => {}
6481        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
6482        Err(error) => return Err(error.into()),
6483    }
6484    let bytes = read_bounded_file(path, max_bytes)?;
6485    let content = std::str::from_utf8(&bytes).map_err(|error| {
6486        HawDBError::or_stop(&error, || {
6487            HawDBError::Storage(format!("search marker is not UTF-8: {error}"))
6488        })
6489    })?;
6490    Ok(content
6491        .lines()
6492        .map(str::trim)
6493        .filter(|line| !line.is_empty())
6494        .map(str::to_string)
6495        .collect())
6496}
6497
6498pub(super) fn next_generation(root: &Path, max_lexical_manifest_bytes: u64) -> Result<u64> {
6499    let manifest_path = root.join(OUT_OF_CORE_MANIFEST_FILE);
6500    if !fs::try_exists(&manifest_path)? {
6501        return Ok(1);
6502    }
6503    let active_generation = match read_bounded_file(&manifest_path, MAX_OUT_OF_CORE_MANIFEST_BYTES)
6504        .and_then(|bytes| SearchOutOfCoreManifestBody::decode(&bytes))
6505        .map(|manifest| manifest.generation)
6506    {
6507        Ok(generation) => generation,
6508        // A selector for a newer reader is intact; never publish over it (#1763).
6509        Err(error @ (HawDBError::FileDescriptors(_) | HawDBError::UnsupportedStorageFormat(_))) => {
6510            return Err(error)
6511        }
6512        Err(_) => latest_recoverable_lexical_generation(root, max_lexical_manifest_bytes)?,
6513    };
6514    active_generation
6515        .checked_add(1)
6516        .ok_or_else(|| HawDBError::Storage("search out-of-core generation overflow".to_string()))
6517}
6518
6519fn latest_recoverable_lexical_generation(root: &Path, max_manifest_bytes: u64) -> Result<u64> {
6520    let mut latest = 0u64;
6521    for entry in fs::read_dir(root)? {
6522        let entry = entry?;
6523        let Some(name) = entry.file_name().to_str().map(str::to_string) else {
6524            continue;
6525        };
6526        let Some(generation) = name
6527            .strip_prefix("search_lexical.manifest.")
6528            .and_then(|value| value.strip_suffix(".hawdb"))
6529            .and_then(|value| value.parse::<u64>().ok())
6530        else {
6531            continue;
6532        };
6533        if lexical_manifest_generation(&entry.path(), max_manifest_bytes)? == Some(generation) {
6534            latest = latest.max(generation);
6535        }
6536    }
6537    Ok(latest)
6538}
6539
6540fn write_generation_artifact(target: &Path, bytes: &[u8]) -> Result<u64> {
6541    let tmp = temporary_artifact_path(target);
6542    let mut guard = CandidateFileGuard::new(tmp.clone());
6543    {
6544        let mut file = File::create(&tmp)?;
6545        file.write_all(bytes)?;
6546        file.sync_all()?;
6547    }
6548    durable_replace_file(&tmp, target)?;
6549    guard.disarm();
6550    Ok(bytes.len() as u64)
6551}
6552
6553fn temporary_artifact_path(target: &Path) -> PathBuf {
6554    target.with_extension(format!(
6555        "tmp.{}.{}",
6556        std::process::id(),
6557        CANDIDATE_SEQUENCE.fetch_add(1, Ordering::Relaxed)
6558    ))
6559}
6560
6561/// Unadmitted serving source for one vector segment payload.
6562struct PlainVectorSource<'a> {
6563    file: &'a File,
6564    offset: u64,
6565}
6566
6567impl vector_segment::Source for PlainVectorSource<'_> {
6568    fn read_exact_at(&mut self, offset: u64, output: &mut [u8]) -> Result<()> {
6569        let offset = self
6570            .offset
6571            .checked_add(offset)
6572            .ok_or_else(|| HawDBError::Storage("search vector range offset overflow".into()))?;
6573        read_search_range(self.file, offset, output)
6574    }
6575
6576    fn reserve(&mut self, _bytes: usize) -> Result<()> {
6577        Ok(())
6578    }
6579
6580    fn checkpoint(&mut self) -> Result<()> {
6581        Ok(())
6582    }
6583}
6584
6585fn read_search_range(file: &File, offset: u64, bytes: &mut [u8]) -> Result<()> {
6586    #[cfg(any(unix, windows))]
6587    {
6588        match hawdb_storage::io::read_exact_at(file, bytes, offset) {
6589            Ok(()) => Ok(()),
6590            #[cfg(windows)]
6591            Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => Err(
6592                HawDBError::Storage("search range read reached an unexpected EOF".to_string()),
6593            ),
6594            Err(error) => Err(error.into()),
6595        }
6596    }
6597    #[cfg(not(any(unix, windows)))]
6598    {
6599        let _ = (file, offset, bytes);
6600        Err(HawDBError::Storage(
6601            "search out-of-core range reads are unsupported on this platform".to_string(),
6602        ))
6603    }
6604}
6605
6606#[cfg(feature = "vector-search")]
6607pub(super) fn seal_resident_candidate(
6608    file: &mut File,
6609    task: &hawdb_core::RuntimeTaskContext,
6610) -> Result<(hawdb_storage::immutable_object::ObjectReference, u64)> {
6611    let memory = crate::build_memory::BuildMemory::new(task)?;
6612    let (seal, checksum) =
6613        generation_writer::io::GenerationIo::new(&memory, task).seal_file_with_checksum(file)?;
6614    Ok((seal.reference, checksum))
6615}
6616
6617#[cfg(test)]
6618mod tests {
6619    #[cfg(all(feature = "full-text-search", feature = "vector-search"))]
6620    mod admitted_working;
6621    #[cfg(feature = "full-text-search")]
6622    mod bm25_windows;
6623    #[cfg(feature = "full-text-search")]
6624    mod candidate_budget;
6625    #[cfg(feature = "full-text-search")]
6626    mod long_query;
6627    mod reader_admission;
6628    #[cfg(feature = "full-text-search")]
6629    mod span_budget;
6630    mod target_admission;
6631    #[cfg(feature = "full-text-search")]
6632    mod text_seed;
6633    mod value_summary_bounds;
6634    mod vector_segments;
6635
6636    use super::*;
6637    use crate::{
6638        SearchFusionWeights, SearchLexicalFeasibilityCoverage, SearchLexicalFeasibilityMetrics,
6639        SearchLexicalProductionQualificationReport, SearchProjectionCleanupOptions,
6640    };
6641    use std::io::{Seek, SeekFrom};
6642
6643    fn load_artifact_closure(
6644        root: &Path,
6645        config: &SearchOutOfCoreConfig,
6646        analyzer_lexicon: &SearchAnalyzerLexicon,
6647        lexical_term_policy: SearchLexicalTermPolicy,
6648        lexical_source_policy: SearchLexicalSourcePolicy,
6649    ) -> Result<(
6650        SearchOutOfCoreManifestBody,
6651        Vec<SearchOutOfCoreSegmentReader>,
6652        mutation_run::MutationVisibility,
6653    )> {
6654        let manifest_path = root.join(OUT_OF_CORE_MANIFEST_FILE);
6655        let manifest_bytes = read_bounded_file(&manifest_path, MAX_OUT_OF_CORE_MANIFEST_BYTES)?;
6656        let manifest = SearchOutOfCoreManifestBody::decode(&manifest_bytes)?;
6657        let closure = load_artifact_closure_for_manifest(
6658            root,
6659            config,
6660            analyzer_lexicon,
6661            lexical_term_policy,
6662            lexical_source_policy,
6663            manifest,
6664            None,
6665        )?;
6666        Ok((closure.manifest, closure.segments, closure.visibility))
6667    }
6668
6669    static TEST_SEQUENCE: AtomicU64 = AtomicU64::new(0);
6670
6671    thread_local! {
6672        // Each libtest thread owns its fresh fixture domains through cleanup.
6673        // Existing unknown roots on Windows require conservative alias probes;
6674        // fixtures must not borrow another concurrent test's exhausted domain.
6675        static TEST_PROJECTS: std::cell::RefCell<Vec<hawdb_storage::file_descriptors::ProjectFileDescriptors>> = const { std::cell::RefCell::new(Vec::new()) };
6676    }
6677
6678    pub(super) fn test_dir(name: &str) -> PathBuf {
6679        let sequence = TEST_SEQUENCE.fetch_add(1, Ordering::Relaxed);
6680        let path = crate::test_temp_dir().join(format!(
6681            "hawdb-search-out-of-core-{name}-{}-{sequence}",
6682            std::process::id()
6683        ));
6684        let files = hawdb_storage::file_descriptors::ProjectFileDescriptors::acquire(
6685            &path,
6686            hawdb_storage::file_descriptors::DEFAULT_MAX_OPEN_FILES,
6687        )
6688        .unwrap();
6689        TEST_PROJECTS.with_borrow_mut(|owners| owners.push(files));
6690        path
6691    }
6692
6693    pub(super) fn options(limit: usize, rank_window: Option<usize>) -> SearchQueryOptions {
6694        SearchQueryOptions {
6695            limit,
6696            offset: 0,
6697            rank_window,
6698            fusion_weights: SearchFusionWeights::default(),
6699            metadata_filters: BTreeMap::new(),
6700            policy_epoch: None,
6701        }
6702    }
6703
6704    #[test]
6705    fn resident_sidecar_producer_references_reject_installed_same_length_changes() {
6706        check_resident_producer_changes(0..3);
6707    }
6708
6709    #[test]
6710    fn resident_segment_and_lexical_producer_references_reject_installed_same_length_changes() {
6711        check_resident_producer_changes(3..7);
6712    }
6713
6714    #[test]
6715    fn resident_generation_snapshot_reference_rejects_installed_same_length_changes() {
6716        check_resident_producer_changes(7..8);
6717    }
6718
6719    fn check_resident_producer_changes(artifacts: std::ops::Range<usize>) {
6720        for artifact in artifacts {
6721            let path = test_dir("resident-sidecar-producer-reference");
6722            let mut index = SearchIndex::open(&path).unwrap();
6723            index.upsert(document(0, "team")).unwrap();
6724            index.checkpoint().unwrap();
6725            let selected = fs::read(path.join(OUT_OF_CORE_MANIFEST_FILE)).unwrap();
6726            AFTER_RESIDENT_SIDECARS.with(|hook| hook.set(Some(artifact)));
6727            let error = index.checkpoint().unwrap_err();
6728            assert!(
6729                error
6730                    .to_string()
6731                    .contains("differs from its producer reference"),
6732                "artifact {artifact}: {error}"
6733            );
6734            assert_eq!(
6735                fs::read(path.join(OUT_OF_CORE_MANIFEST_FILE)).unwrap(),
6736                selected
6737            );
6738            assert_eq!(
6739                SearchOutOfCoreReader::open(&path).unwrap().document_count(),
6740                1
6741            );
6742            index.checkpoint().unwrap();
6743            let bytes = fs::read(path.join(OUT_OF_CORE_MANIFEST_FILE)).unwrap();
6744            let manifest = SearchOutOfCoreManifestBody::decode(&bytes).unwrap();
6745            let segment = &manifest.segments[0];
6746            let lexical_payload =
6747                crate::lexical_projection::artifact_file(segment.objects.lexical_generation);
6748            for (name, object) in [
6749                (&segment.descriptor_file, segment.objects.descriptor),
6750                (&segment.payload_file, segment.objects.payload),
6751                (
6752                    &segment.lexical_manifest_file,
6753                    segment.objects.lexical_manifest,
6754                ),
6755                (&lexical_payload, segment.objects.lexical_payload),
6756                (&segment.metadata_payload_file, segment.objects.metadata),
6757                (&segment.vector_payload_file, segment.objects.vector),
6758                (&segment.layout_file, segment.objects.layout),
6759            ] {
6760                assert_eq!(
6761                    object,
6762                    ArtifactObject::for_bytes(&fs::read(path.join(name)).unwrap())
6763                );
6764            }
6765            assert_eq!(
6766                SearchOutOfCoreReader::open(&path).unwrap().document_count(),
6767                1
6768            );
6769            drop(index);
6770            fs::remove_dir_all(path).unwrap();
6771        }
6772    }
6773
6774    #[test]
6775    fn bound_artifact_read_retains_one_encoded_buffer() {
6776        let _serial = crate::test_allocation::serial();
6777        let root = test_dir("bound-artifact-allocation");
6778        let path = root.join("artifact");
6779        // Cross the final geometric growth boundary of a large descriptor.
6780        let data = vec![b'x'; 17 * 1024 * 1024 + 4096];
6781        fs::write(&path, &data).unwrap();
6782        let checksum = checksum_bytes(&data);
6783        // Shared descriptor state and droppable test hooks are fixture owners,
6784        // so initialize them before tracking this read's encoded buffer.
6785        drop(
6786            read_bound_artifact(
6787                &path,
6788                data.len() as u64,
6789                checksum,
6790                64 * 1024 * 1024,
6791                "allocation fixture",
6792            )
6793            .unwrap(),
6794        );
6795        let baseline = crate::test_allocation::live();
6796        let (bytes, peak) = crate::test_allocation::measure(|| {
6797            read_bound_artifact(
6798                &path,
6799                data.len() as u64,
6800                checksum,
6801                64 * 1024 * 1024,
6802                "allocation fixture",
6803            )
6804            .unwrap()
6805        });
6806        assert_eq!(bytes, data);
6807        let peak = peak.saturating_sub(baseline);
6808        assert!(
6809            peak <= data.len() + 64 * 1024,
6810            "bound artifact retained {peak} allocated bytes for {} encoded bytes",
6811            data.len()
6812        );
6813        drop(bytes);
6814        assert_eq!(crate::test_allocation::live(), baseline);
6815        fs::remove_dir_all(root).unwrap();
6816    }
6817
6818    #[test]
6819    #[cfg(any(unix, windows))]
6820    fn search_range_adapter_preserves_exact_reads_and_eof_errors() {
6821        let directory = test_dir("positioned-read-adapter");
6822        let path = directory.join("range.hawdb");
6823        let mut file = OpenOptions::new()
6824            .read(true)
6825            .write(true)
6826            .create_new(true)
6827            .open(&path)
6828            .unwrap();
6829        file.write_all(b"abcdefgh").unwrap();
6830        let mut bytes = [0; 4];
6831        read_search_range(&file, 2, &mut bytes).unwrap();
6832        assert_eq!(&bytes, b"cdef");
6833        let error = read_search_range(&file, 6, &mut bytes).unwrap_err();
6834        #[cfg(unix)]
6835        assert_eq!(
6836            error,
6837            HawDBError::Storage("failed to fill whole buffer".to_string())
6838        );
6839        #[cfg(windows)]
6840        assert_eq!(
6841            error,
6842            HawDBError::Storage("search range read reached an unexpected EOF".to_string())
6843        );
6844        assert_eq!(
6845            read_search_range(&file, u64::MAX, &mut bytes).unwrap_err(),
6846            HawDBError::Storage("read range end overflows u64".to_string())
6847        );
6848        drop(file);
6849        fs::remove_file(path).unwrap();
6850        fs::remove_dir(directory).unwrap();
6851    }
6852
6853    fn document(number: usize, space: &str) -> SearchDocument {
6854        SearchDocument {
6855            id: format!("memory:{number:03}"),
6856            title: std::iter::repeat_n("graph", number % 3 + 1)
6857                .collect::<Vec<_>>()
6858                .join(" "),
6859            content: format!("storage memory document {number}"),
6860            embedding: Some(vec![number as f32 + 1.0, (16 - number) as f32]),
6861            metadata: BTreeMap::from([
6862                ("kind".to_string(), "memory".to_string()),
6863                ("external_id".to_string(), number.to_string()),
6864                ("space_id".to_string(), space.to_string()),
6865            ]),
6866        }
6867    }
6868
6869    fn production_identity() -> crate::ProductionQualificationIdentity {
6870        crate::ProductionQualificationIdentity {
6871            source_revision: "test-revision".to_string(),
6872            rust_toolchain: "test-toolchain".to_string(),
6873            target_os: "linux".to_string(),
6874            target_arch: "x86_64".to_string(),
6875            enabled_features: vec!["full-text-search".to_string(), "vector-search".to_string()],
6876            durable_format_version: 1,
6877            schema_version: 1,
6878            configuration_digest: "test-config".to_string(),
6879            deployment_profile: "production-replica".to_string(),
6880            dataset_fingerprint: "test-dataset".to_string(),
6881            canonical_graph_commit_epoch: 42,
6882            policy_version: crate::PRODUCTION_QUALIFICATION_POLICY_VERSION,
6883        }
6884    }
6885
6886    fn assert_search_parity(expected: &SearchResultSet, actual: &SearchResultSet) {
6887        assert_eq!(actual.total_hits, expected.total_hits);
6888        assert_eq!(
6889            actual.filtered_document_count,
6890            expected.filtered_document_count
6891        );
6892        assert_eq!(actual.hits.len(), expected.hits.len());
6893        for (actual, expected) in actual.hits.iter().zip(&expected.hits) {
6894            assert_eq!(actual.id, expected.id);
6895            assert_eq!(actual.vector_rank, expected.vector_rank);
6896            assert_eq!(actual.text_rank, expected.text_rank);
6897            assert!((actual.score - expected.score).abs() < 1e-12);
6898            assert!((actual.vector_score - expected.vector_score).abs() < 1e-12);
6899            assert!((actual.text_score - expected.text_score).abs() < 1e-12);
6900            assert_eq!(actual.matched_terms, expected.matched_terms);
6901            assert_eq!(actual.matched_spans, expected.matched_spans);
6902        }
6903    }
6904
6905    #[test]
6906    fn out_of_core_text_vector_and_hybrid_match_resident_search() {
6907        let path = test_dir("parity");
6908        let mut index = SearchIndex::open(&path).unwrap();
6909        for number in 0..12 {
6910            index.upsert(document(number, "team")).unwrap();
6911        }
6912        index.checkpoint().unwrap();
6913        let resident = SearchIndex::open(&path).unwrap();
6914        let reader = SearchOutOfCoreReader::open(&path).unwrap();
6915        assert_eq!(reader.document_count(), 12);
6916        assert_eq!(reader.resident_document_count(), 0);
6917        let hydrated = reader
6918            .hydrate_documents(&["memory:003".to_string(), "memory:001".to_string()])
6919            .unwrap();
6920        assert_eq!(
6921            hydrated
6922                .documents
6923                .iter()
6924                .map(|document| document.id.as_str())
6925                .collect::<Vec<_>>(),
6926            vec!["memory:003", "memory:001"]
6927        );
6928        assert_eq!(hydrated.metrics.hydrated_documents, 2);
6929
6930        let query_embedding = [1.0, 0.5];
6931        let modes: &[(SearchMode, Option<usize>)] = &[
6932            #[cfg(feature = "full-text-search")]
6933            (SearchMode::Text, None),
6934            #[cfg(feature = "vector-search")]
6935            (SearchMode::Vector, None),
6936            #[cfg(all(feature = "full-text-search", feature = "vector-search"))]
6937            (SearchMode::Hybrid, Some(6)),
6938        ];
6939        for &(mode, rank_window) in modes {
6940            let options = options(5, rank_window);
6941            let expected = resident
6942                .try_search_with_options(
6943                    "graph storage",
6944                    Some(&query_embedding),
6945                    mode,
6946                    options.clone(),
6947                )
6948                .unwrap();
6949            let actual = reader
6950                .search_with_options("graph storage", Some(&query_embedding), mode, options)
6951                .unwrap();
6952            assert_search_parity(&expected, &actual.result);
6953            assert!(actual.metrics.hydrated_documents <= 5);
6954        }
6955        fs::remove_dir_all(path).unwrap();
6956    }
6957
6958    #[test]
6959    #[cfg(feature = "full-text-search")]
6960    fn out_of_core_text_search_uses_chinese_word_segmentation() {
6961        let path = test_dir("chinese-tokenization");
6962        let term = "\u{5206}\u{5e03}\u{5f0f}\u{7cfb}\u{7edf}";
6963        let mut index = SearchIndex::open(&path).unwrap();
6964        index
6965            .upsert(SearchDocument {
6966                id: "memory:cn".to_string(),
6967                title: "\u{73b0}\u{4ee3}\u{5206}\u{5e03}\u{5f0f}\u{7cfb}\u{7edf}\u{6570}\u{636e}\u{5e93}\u{8bbe}\u{8ba1}".to_string(),
6968                content: String::new(),
6969                embedding: None,
6970                metadata: BTreeMap::new(),
6971            })
6972            .unwrap();
6973        index.checkpoint().unwrap();
6974        let reader = SearchOutOfCoreReader::open(&path).unwrap();
6975
6976        let output = reader
6977            .search_with_options(term, None, SearchMode::Text, options(10, None))
6978            .unwrap();
6979
6980        assert_eq!(output.result.hits[0].id, "memory:cn");
6981        assert!(output.result.hits[0]
6982            .matched_terms
6983            .iter()
6984            .any(|token| token == term));
6985        fs::remove_dir_all(path).unwrap();
6986    }
6987
6988    #[test]
6989    #[cfg(feature = "full-text-search")]
6990    fn out_of_core_candidate_spill_applies_metadata_before_ranking() {
6991        let path = test_dir("metadata");
6992        let spill = path.join("spill");
6993        let mut index = SearchIndex::open(&path).unwrap();
6994        for number in 0..10 {
6995            let space = if number < 4 { "team" } else { "private" };
6996            index.upsert(document(number, space)).unwrap();
6997        }
6998        index.checkpoint().unwrap();
6999        let config = SearchOutOfCoreConfig {
7000            spill_directory: spill.clone(),
7001            ..SearchOutOfCoreConfig::default()
7002        };
7003        let reader = SearchOutOfCoreReader::open_with_config(&path, config).unwrap();
7004        let mut options = options(10, None);
7005        options
7006            .metadata_filters
7007            .insert("space_id".to_string(), "team".to_string());
7008        let output = reader
7009            .search_with_options("graph", None, SearchMode::Text, options)
7010            .unwrap();
7011        assert_eq!(output.result.filtered_document_count, 4);
7012        assert_eq!(output.result.total_hits, 4);
7013        assert_eq!(
7014            output.result.candidate_set.representation,
7015            "spilled_sorted_document_ids"
7016        );
7017        assert!(output.metrics.candidate_spill_bytes > 0);
7018        assert!(fs::read_dir(spill).unwrap().next().is_none());
7019        fs::remove_dir_all(path).unwrap();
7020    }
7021
7022    #[test]
7023    #[cfg(all(feature = "full-text-search", feature = "vector-search"))]
7024    fn out_of_core_filter_and_vector_scoring_do_not_hydrate_full_documents() {
7025        let path = test_dir("sidecar-read-paths");
7026        let mut index = SearchIndex::open(&path).unwrap();
7027        for number in 0..4 {
7028            index.upsert(document(number, "team")).unwrap();
7029        }
7030        index.checkpoint().unwrap();
7031        let reader = SearchOutOfCoreReader::open(&path).unwrap();
7032
7033        let mut filtered = options(0, None);
7034        filtered
7035            .metadata_filters
7036            .insert("space_id".to_string(), "team".to_string());
7037        let text = reader
7038            .search_with_options("graph", None, SearchMode::Text, filtered)
7039            .unwrap();
7040        assert_eq!(text.result.total_hits, 4);
7041        assert!(text.metrics.metadata_segment_bytes_read > 0);
7042        assert_eq!(text.metrics.vector_segment_bytes_read, 0);
7043        assert_eq!(text.metrics.hydration_segment_bytes_read, 0);
7044        assert_eq!(text.metrics.peak_segment_document_bytes, 0);
7045
7046        let vector = reader
7047            .search_with_options("", Some(&[1.0, 0.5]), SearchMode::Vector, options(0, None))
7048            .unwrap();
7049        assert_eq!(vector.result.total_hits, 4);
7050        assert_eq!(vector.metrics.metadata_segment_bytes_read, 0);
7051        assert!(vector.metrics.vector_segment_bytes_read > 0);
7052        assert_eq!(vector.metrics.hydration_segment_bytes_read, 0);
7053        assert_eq!(vector.metrics.peak_segment_document_bytes, 0);
7054        fs::remove_dir_all(path).unwrap();
7055    }
7056
7057    /// Exact vector-only reads larger than a reader cap or their admitted
7058    /// score entries are typed budget refusals, never storage faults (#1748).
7059    #[test]
7060    #[cfg(feature = "vector-search")]
7061    fn out_of_core_exact_vector_window_and_hydration_caps_are_typed_budget_errors() {
7062        let path = test_dir("exact-vector-caps");
7063        let mut index = SearchIndex::open(&path).unwrap();
7064        for number in 0..4 {
7065            index.upsert(document(number, "team")).unwrap();
7066        }
7067        index.checkpoint().unwrap();
7068        let reader = SearchOutOfCoreReader::open_with_config(
7069            &path,
7070            SearchOutOfCoreConfig {
7071                max_score_entries: NonZeroUsize::new(8).unwrap(),
7072                max_hydrated_documents: NonZeroUsize::new(2).unwrap(),
7073                ..SearchOutOfCoreConfig::default()
7074            },
7075        )
7076        .unwrap();
7077        let exact = |limit: usize, rank_window: Option<usize>, working_bytes: usize| {
7078            reader
7079                .search_with_options_compressed_vector_projection_execution_options(
7080                    "",
7081                    Some(&[1.0, 0.5]),
7082                    SearchMode::Vector,
7083                    options(limit, rank_window),
7084                    CompressedVectorSearchMode::Disabled,
7085                    VectorSearchExecutionOptions::bounded(NonZeroUsize::MIN, working_bytes, None)
7086                        .with_exact_search(),
7087                )
7088                .unwrap_err()
7089        };
7090        let assert_entries = |error: HawDBError, budget: u64, option: &str, text: &str| {
7091            assert!(error.to_string().contains(text), "{error}");
7092            match error {
7093                HawDBError::ResourceBudgetExceeded(details) => {
7094                    assert_eq!(details.resource, ResourceBudgetKind::MetadataEntries);
7095                    assert_eq!(details.budget, budget, "{details:?}");
7096                    assert_eq!(details.budget_option, option, "{details:?}");
7097                }
7098                other => panic!("{other:?}"),
7099            }
7100        };
7101        assert_entries(
7102            exact(3, None, 1 << 20),
7103            2,
7104            "SearchOutOfCoreConfig.max_hydrated_documents",
7105            "search hydration requested 3 documents, exceeding 2",
7106        );
7107        assert_entries(
7108            exact(1, Some(9), 1 << 20),
7109            8,
7110            MAX_SCORE_ENTRIES_OPTION,
7111            "search rank window exceeds the admitted 8 score entries",
7112        );
7113        // 512 working bytes admit 512 / 128 / 2 = 2 scored documents.
7114        assert_entries(
7115            exact(2, None, 512),
7116            2,
7117            "VectorSearchExecutionOptions.max_working_bytes",
7118            "search vector uniqueness check requires more than 2 document ids",
7119        );
7120        let unhydrated = SearchOutOfCoreReader::open_with_config(
7121            &path,
7122            SearchOutOfCoreConfig {
7123                max_score_entries: NonZeroUsize::new(2).unwrap(),
7124                ..SearchOutOfCoreConfig::default()
7125            },
7126        )
7127        .unwrap();
7128        assert_entries(
7129            unhydrated
7130                .search_with_options("", Some(&[1.0, 0.5]), SearchMode::Vector, options(3, None))
7131                .unwrap_err(),
7132            2,
7133            MAX_SCORE_ENTRIES_OPTION,
7134            "search page window requires 3 score entries, exceeding 2",
7135        );
7136        // An admission below one score entry pair refuses the window itself.
7137        assert_entries(
7138            exact(1, None, 256),
7139            1,
7140            "VectorSearchExecutionOptions.max_working_bytes",
7141            "search vector uniqueness check requires more than 1 document ids",
7142        );
7143        assert_entries(
7144            exact(2, None, 256),
7145            1,
7146            "VectorSearchExecutionOptions.max_working_bytes",
7147            "search rank window exceeds the admitted 1 score entries",
7148        );
7149        fs::remove_dir_all(path).unwrap();
7150    }
7151
7152    /// An offset and limit whose sum overflows is a caller mistake, not a
7153    /// storage fault (#1754).
7154    #[test]
7155    #[cfg(feature = "full-text-search")]
7156    fn out_of_core_offset_and_limit_overflow_is_a_semantic_error() {
7157        let path = test_dir("offset-limit-overflow");
7158        let mut index = SearchIndex::open(&path).unwrap();
7159        index.upsert(document(0, "team")).unwrap();
7160        index.checkpoint().unwrap();
7161        let reader = SearchOutOfCoreReader::open(&path).unwrap();
7162        let overflowing = SearchQueryOptions {
7163            offset: usize::MAX,
7164            ..options(1, None)
7165        };
7166        let error = reader
7167            .search_with_options("storage", None, SearchMode::Text, overflowing.clone())
7168            .unwrap_err();
7169        assert!(matches!(error, HawDBError::Semantic(_)), "{error:?}");
7170        let error = reader
7171            .search_candidates_with_options("storage", None, SearchMode::Text, overflowing)
7172            .unwrap_err();
7173        assert!(matches!(error, HawDBError::Semantic(_)), "{error:?}");
7174        drop(reader);
7175        fs::remove_dir_all(path).unwrap();
7176    }
7177
7178    #[test]
7179    #[cfg(feature = "vector-search")]
7180    fn out_of_core_vector_execution_options_enforce_memory_and_cancellation() {
7181        for diskann in [false, true] {
7182            check_vector_execution_options(diskann);
7183        }
7184    }
7185
7186    #[cfg(feature = "vector-search")]
7187    fn check_vector_execution_options(diskann: bool) {
7188        let path = test_dir("vector-execution-options");
7189        let mut index = SearchIndex::open(&path).unwrap();
7190        if !diskann {
7191            index.set_rabitq_projection_build_options(Default::default());
7192        }
7193        index.upsert(document(0, "team")).unwrap();
7194        index.checkpoint().unwrap();
7195        let reader = SearchOutOfCoreReader::open(&path).unwrap();
7196
7197        let memory_error = reader
7198            .search_with_options_compressed_vector_projection_execution_options(
7199                "",
7200                Some(&[1.0, 0.5]),
7201                SearchMode::Vector,
7202                options(1, None),
7203                CompressedVectorSearchMode::Disabled,
7204                VectorSearchExecutionOptions::bounded(NonZeroUsize::MIN, 64, None),
7205            )
7206            .unwrap_err();
7207        if diskann {
7208            assert!(
7209                matches!(&memory_error, HawDBError::ResourceBudgetExceeded(details)
7210                    if details.resource == hawdb_core::ResourceBudgetKind::MemoryBytes),
7211                "{memory_error:?}"
7212            );
7213        } else {
7214            assert!(
7215                matches!(&memory_error, HawDBError::ResourceBudgetExceeded(details)
7216                    if details.resource == hawdb_core::ResourceBudgetKind::MetadataEntries
7217                        && details.budget == 0
7218                        && details.budget_option
7219                            == "VectorSearchExecutionOptions.max_working_bytes"),
7220                "{memory_error:?}"
7221            );
7222            assert!(memory_error
7223                .to_string()
7224                .contains("uniqueness check exceeds the admitted working memory"));
7225        }
7226
7227        let cancellation = crate::RuntimeCancellationToken::new();
7228        let task_context = crate::RuntimeTaskContext::without_deadline(cancellation.clone());
7229        assert!(cancellation.cancel());
7230        let cancellation_error = reader
7231            .search_with_options_compressed_vector_projection_execution_options(
7232                "",
7233                Some(&[1.0, 0.5]),
7234                SearchMode::Vector,
7235                options(1, None),
7236                CompressedVectorSearchMode::Disabled,
7237                VectorSearchExecutionOptions::bounded(NonZeroUsize::MIN, 1024, Some(&task_context)),
7238            )
7239            .unwrap_err();
7240        assert!(cancellation_error.to_string().contains("cancelled"));
7241        fs::remove_dir_all(path).unwrap();
7242    }
7243
7244    #[cfg(all(feature = "acl", feature = "full-text-search"))]
7245    #[test]
7246    fn out_of_core_acl_excludes_hidden_documents_from_bm25_candidates() {
7247        let path = test_dir("acl");
7248        let mut reference = SearchIndex::in_memory();
7249        let mut index = SearchIndex::open(&path).unwrap();
7250        for number in 0..2 {
7251            let allowed = document(number, "team");
7252            reference.upsert(allowed.clone()).unwrap();
7253            index.upsert(allowed).unwrap();
7254        }
7255        let mut hidden = document(9, "private");
7256        hidden.title = "graph graph graph graph graph graph".to_string();
7257        index.upsert(hidden).unwrap();
7258        index.checkpoint().unwrap();
7259        let expected = reference
7260            .try_search_with_options("graph", None, SearchMode::Text, options(10, None))
7261            .unwrap();
7262        let mut reader = SearchOutOfCoreReader::open(&path).unwrap();
7263        reader.set_runtime_capabilities(
7264            RuntimeCapabilities::default().with(RuntimeCapability::AccessControl, true),
7265        );
7266        let actual = reader
7267            .search_with_options_access_control(
7268                "graph",
7269                None,
7270                SearchMode::Text,
7271                options(10, None),
7272                SearchAccessControlContext::visibility_scopes(7, "space_id", ["team"]),
7273            )
7274            .unwrap();
7275        assert_eq!(actual.result.total_hits, expected.total_hits);
7276        assert_eq!(actual.result.hits.len(), expected.hits.len());
7277        for (actual, expected) in actual.result.hits.iter().zip(&expected.hits) {
7278            assert_eq!(actual.id, expected.id);
7279            assert_eq!(actual.text_rank, expected.text_rank);
7280            assert_eq!(actual.matched_terms, expected.matched_terms);
7281            assert_eq!(actual.matched_spans, expected.matched_spans);
7282        }
7283        assert_eq!(actual.result.candidate_set.filtered_out_count, 1);
7284        fs::remove_dir_all(path).unwrap();
7285    }
7286
7287    #[cfg(all(feature = "acl", feature = "full-text-search"))]
7288    #[test]
7289    fn out_of_core_access_control_caller_mistakes_are_semantic_errors() {
7290        let path = test_dir("acl-caller-mistakes");
7291        let mut index = SearchIndex::open(&path).unwrap();
7292        index.upsert(document(0, "team")).unwrap();
7293        index.checkpoint().unwrap();
7294        let mut reader = SearchOutOfCoreReader::open(&path).unwrap();
7295        reader.set_runtime_capabilities(
7296            RuntimeCapabilities::default().with(RuntimeCapability::AccessControl, true),
7297        );
7298        let search = |policy_epoch, access_control| {
7299            reader.search_with_options_access_control(
7300                "graph",
7301                None,
7302                SearchMode::Text,
7303                SearchQueryOptions {
7304                    policy_epoch,
7305                    ..options(10, None)
7306                },
7307                access_control,
7308            )
7309        };
7310        // A matching epoch and a valid context still search.
7311        search(
7312            Some(7),
7313            SearchAccessControlContext::visibility_scopes(7, "space_id", ["team"]),
7314        )
7315        .unwrap();
7316        // A mismatched epoch or a malformed context is the caller's mistake,
7317        // not a storage fault (#1767).
7318        for (policy_epoch, access_control) in
7319            SearchAccessControlContext::invalid_requests_for_test()
7320        {
7321            let error = search(policy_epoch, access_control.clone()).unwrap_err();
7322            assert!(
7323                matches!(error, HawDBError::Semantic(_)),
7324                "{access_control:?}: {error:?}"
7325            );
7326        }
7327        drop(reader);
7328        fs::remove_dir_all(path).unwrap();
7329    }
7330
7331    #[test]
7332    #[cfg(feature = "full-text-search")]
7333    fn out_of_core_hydration_and_candidate_budgets_fail_closed() {
7334        let path = test_dir("budgets");
7335        let mut index = SearchIndex::open(&path).unwrap();
7336        let mut large = document(0, "team");
7337        large.content = "graph ".repeat(256);
7338        index.upsert(large).unwrap();
7339        index.checkpoint().unwrap();
7340
7341        let hydration_config = SearchOutOfCoreConfig {
7342            max_hydrated_bytes: NonZeroU64::new(32).unwrap(),
7343            ..SearchOutOfCoreConfig::default()
7344        };
7345        let hydration_reader =
7346            SearchOutOfCoreReader::open_with_config(&path, hydration_config).unwrap();
7347        let error = hydration_reader
7348            .search_with_options("graph", None, SearchMode::Text, options(1, None))
7349            .unwrap_err();
7350        assert!(error.to_string().contains("search hydration requires"));
7351        assert!(matches!(
7352            error,
7353            HawDBError::ResourceBudgetExceeded(details)
7354                if details.budget_option == "SearchOutOfCoreConfig.max_hydrated_bytes"
7355        ));
7356
7357        let span_config = SearchOutOfCoreConfig {
7358            max_matched_spans: NonZeroUsize::new(1).unwrap(),
7359            ..SearchOutOfCoreConfig::default()
7360        };
7361        let span_reader = SearchOutOfCoreReader::open_with_config(&path, span_config).unwrap();
7362        let error = span_reader
7363            .search_with_options("graph", None, SearchMode::Text, options(1, None))
7364            .unwrap_err();
7365        assert!(error
7366            .to_string()
7367            .contains("matched-span hydration exceeded"));
7368
7369        let spill_config = SearchOutOfCoreConfig {
7370            spill_directory: path.join("spill-budget"),
7371            max_candidate_spill_bytes: NonZeroU64::new(1).unwrap(),
7372            ..SearchOutOfCoreConfig::default()
7373        };
7374        let spill_reader = SearchOutOfCoreReader::open_with_config(&path, spill_config).unwrap();
7375        let mut filtered = options(1, None);
7376        filtered
7377            .metadata_filters
7378            .insert("space_id".to_string(), "team".to_string());
7379        let error = spill_reader
7380            .search_with_options("graph", None, SearchMode::Text, filtered)
7381            .unwrap_err();
7382        assert!(error.to_string().contains("candidate spill requires"));
7383        fs::remove_dir_all(path).unwrap();
7384    }
7385
7386    #[test]
7387    fn out_of_core_segment_corruption_fails_during_late_hydration() {
7388        let path = test_dir("corruption");
7389        let mut index = SearchIndex::open(&path).unwrap();
7390        index.upsert(document(0, "team")).unwrap();
7391        index.checkpoint().unwrap();
7392        let reader = SearchOutOfCoreReader::open(&path).unwrap();
7393        let payload_path = path.join(
7394            &reader
7395                .manifest
7396                .segments
7397                .first()
7398                .expect("manifest has a segment")
7399                .payload_file,
7400        );
7401        let mut file = OpenOptions::new()
7402            .read(true)
7403            .write(true)
7404            .open(payload_path)
7405            .unwrap();
7406        file.seek(SeekFrom::Start(0)).unwrap();
7407        file.write_all(b"X").unwrap();
7408        file.sync_all().unwrap();
7409        #[cfg(feature = "full-text-search")]
7410        {
7411            let unhydrated = reader
7412                .search_with_options("graph", None, SearchMode::Text, options(0, None))
7413                .unwrap();
7414            assert_eq!(unhydrated.result.total_hits, 1);
7415            assert_eq!(unhydrated.metrics.hydration_segment_bytes_read, 0);
7416            let error = reader
7417                .search_with_options("graph", None, SearchMode::Text, options(1, None))
7418                .unwrap_err();
7419            assert!(error.to_string().contains("payload checksum mismatch"));
7420        }
7421        let error = reader
7422            .hydrate_documents(&[document(0, "team").id])
7423            .unwrap_err();
7424        assert!(error.to_string().contains("payload checksum mismatch"));
7425        drop(file);
7426        drop(reader);
7427        fs::remove_dir_all(path).unwrap();
7428    }
7429
7430    #[test]
7431    fn out_of_core_reader_rejects_duplicate_manifest_segment_ids() {
7432        let path = test_dir("multiple-manifest-segments");
7433        let mut index = SearchIndex::open(&path).unwrap();
7434        index.upsert(document(0, "team")).unwrap();
7435        index.checkpoint().unwrap();
7436
7437        let manifest_path = path.join(OUT_OF_CORE_MANIFEST_FILE);
7438        let envelope: SearchOutOfCoreManifestEnvelope =
7439            serde_json::from_slice(&fs::read(&manifest_path).unwrap()).unwrap();
7440        let mut body = envelope.body;
7441        let duplicate = body.segments[0].clone();
7442        body.segments.push(duplicate);
7443        let body_bytes = serde_json::to_vec(&body).unwrap();
7444        let bytes = serde_json::to_vec(&SearchOutOfCoreManifestEnvelope {
7445            body,
7446            checksum: checksum_bytes(&body_bytes),
7447        })
7448        .unwrap();
7449        fs::write(&manifest_path, bytes).unwrap();
7450
7451        let error = SearchOutOfCoreReader::open(&path).unwrap_err();
7452        assert!(error.to_string().contains("duplicate segment ids"));
7453        fs::remove_dir_all(path).unwrap();
7454    }
7455
7456    #[test]
7457    #[cfg(feature = "full-text-search")]
7458    fn out_of_core_reader_and_generation_update_reject_duplicate_manifest_documents() {
7459        let path = test_dir("duplicate-segment-documents");
7460        let mut index = SearchIndex::open(&path).unwrap();
7461        index.upsert(document(0, "team")).unwrap();
7462        index.checkpoint().unwrap();
7463
7464        let manifest_path = path.join(OUT_OF_CORE_MANIFEST_FILE);
7465        let envelope: SearchOutOfCoreManifestEnvelope =
7466            serde_json::from_slice(&fs::read(&manifest_path).unwrap()).unwrap();
7467        let mut body = envelope.body;
7468        let mut duplicate = body.segments[0].clone();
7469        duplicate.segment_id = 1;
7470        body.segments.push(duplicate);
7471        body.document_count = 2;
7472        let body_bytes = serde_json::to_vec(&body).unwrap();
7473        let bytes = serde_json::to_vec(&SearchOutOfCoreManifestEnvelope {
7474            body,
7475            checksum: checksum_bytes(&body_bytes),
7476        })
7477        .unwrap();
7478        fs::write(&manifest_path, &bytes).unwrap();
7479
7480        let reader = SearchOutOfCoreReader::open(&path).unwrap();
7481        let error = reader
7482            .search_with_options("graph", None, SearchMode::Text, options(1, None))
7483            .unwrap_err();
7484        assert!(error.to_string().contains("duplicate document"));
7485        let error = reader
7486            .hydrate_documents(&[document(0, "team").id])
7487            .unwrap_err();
7488        assert!(error.to_string().contains("duplicate document"));
7489        #[cfg(feature = "vector-search")]
7490        {
7491            let error = reader
7492                .search_with_options("", Some(&[1.0, 16.0]), SearchMode::Vector, options(1, None))
7493                .unwrap_err();
7494            assert!(error.to_string().contains("duplicate document"));
7495        }
7496        let error = SearchOutOfCoreGenerationWriter::prepare_delta(
7497            &reader,
7498            crate::SearchProjectionDelta::default(),
7499            Default::default(),
7500        )
7501        .unwrap_err();
7502        assert!(error
7503            .to_string()
7504            .contains("duplicate document content artifacts"));
7505        assert_eq!(fs::read(&manifest_path).unwrap(), bytes);
7506        fs::remove_dir_all(path).unwrap();
7507    }
7508
7509    #[cfg(feature = "full-text-search")]
7510    fn publish_two_artifact_manifest(
7511        path: &Path,
7512        initial_document: SearchDocument,
7513        next_document: SearchDocument,
7514    ) {
7515        publish_two_artifact_manifest_with_options(
7516            path,
7517            initial_document,
7518            Default::default(),
7519            next_document,
7520            Default::default(),
7521        );
7522    }
7523
7524    #[cfg(feature = "full-text-search")]
7525    fn publish_two_artifact_manifest_with_options(
7526        path: &Path,
7527        initial_document: SearchDocument,
7528        initial_options: SearchOutOfCoreGenerationBuildOptions,
7529        next_document: SearchDocument,
7530        next_options: SearchOutOfCoreGenerationBuildOptions,
7531    ) {
7532        publish_two_artifact_manifest_with_initial_documents(
7533            path,
7534            vec![initial_document],
7535            initial_options,
7536            next_document,
7537            next_options,
7538        );
7539    }
7540
7541    #[cfg(feature = "full-text-search")]
7542    fn publish_two_artifact_manifest_with_initial_documents(
7543        path: &Path,
7544        initial_documents: Vec<SearchDocument>,
7545        mut initial_options: SearchOutOfCoreGenerationBuildOptions,
7546        next_document: SearchDocument,
7547        mut next_options: SearchOutOfCoreGenerationBuildOptions,
7548    ) {
7549        // This family qualifies legacy layered RaBitQ, including mixed
7550        // quantization and budget fallback. Default graphs have their own CRUD
7551        // and pin/reopen family in generation_writer::tests::diskann.
7552        initial_options.vector_backend = None;
7553        next_options.vector_backend = None;
7554        let mut initial = SearchOutOfCoreGenerationWriter::create(path, initial_options).unwrap();
7555        for document in initial_documents {
7556            initial.push(document).unwrap();
7557        }
7558        initial.finish().unwrap();
7559
7560        // Ordinary readers do not register GC pins. Retain an admitted private
7561        // capture until the combined manifest selects the first closure again.
7562        let initial_capture = {
7563            use crate::build_memory::read::{ReadAdmission, ReadPermit};
7564            let reader = SearchOutOfCoreReader::open(path).unwrap();
7565            let governor = crate::build_memory::read::tests::governor();
7566            let permit = governor
7567                .try_admit(
7568                    hawdb_qos::RuntimeWorkRequest::background_maintenance(8 << 20)
7569                        .with_io_wave_slots(1),
7570                )
7571                .unwrap();
7572            let task = permit.bind_task_context(Default::default());
7573            let memory = crate::build_memory::BuildMemory::new(&task).unwrap();
7574            let admission = ReadAdmission {
7575                memory: &memory,
7576                task: &task,
7577                permit: ReadPermit::Governed(&permit),
7578            };
7579            admitted_root::open(admitted_root::OpenContext {
7580                root: path,
7581                config: reader.config.clone(),
7582                analyzer_lexicon: reader.analyzer_lexicon.clone(),
7583                lexical_term_policy: reader.lexical_term_policy,
7584                lexical_source_policy: reader.lexical_source_policy,
7585                admission: Some(&admission),
7586                project: Some(&reader._project_files),
7587                max_artifact_read_bytes: 32 << 20,
7588                publication: None,
7589                stationary: None,
7590                expected_stationary_manifest: None,
7591            })
7592            .unwrap()
7593        };
7594        let manifest_path = path.join(OUT_OF_CORE_MANIFEST_FILE);
7595        let initial_manifest: SearchOutOfCoreManifestEnvelope =
7596            serde_json::from_slice(&fs::read(&manifest_path).unwrap()).unwrap();
7597        let initial_segment = initial_manifest
7598            .body
7599            .segments
7600            .into_iter()
7601            .next()
7602            .expect("initial manifest has one segment");
7603
7604        let mut next = SearchOutOfCoreGenerationWriter::create(path, next_options).unwrap();
7605        next.push(next_document).unwrap();
7606        next.finish().unwrap();
7607        if let Some(name) = &initial_segment.rabitq_artifact_file {
7608            assert!(
7609                path.join(name).is_file(),
7610                "the captured first segment must survive replacement cleanup"
7611            );
7612        }
7613
7614        let next_manifest: SearchOutOfCoreManifestEnvelope =
7615            serde_json::from_slice(&fs::read(&manifest_path).unwrap()).unwrap();
7616        let mut body = next_manifest.body;
7617        let mut next_segment = body.segments.pop().expect("next manifest has one segment");
7618        next_segment.segment_id = 1;
7619        body.segments = vec![initial_segment, next_segment];
7620        body.document_count = body
7621            .segments
7622            .iter()
7623            .map(|segment| segment.document_count)
7624            .sum();
7625        body.documents_digest = body.segments.iter().fold(0, |digest, segment| {
7626            crate::lexical_projection::DocumentsDigest::combine(digest, segment.documents_digest)
7627        });
7628        let body_bytes = serde_json::to_vec(&body).unwrap();
7629        fs::write(
7630            &manifest_path,
7631            serde_json::to_vec(&SearchOutOfCoreManifestEnvelope {
7632                body,
7633                checksum: checksum_bytes(&body_bytes),
7634            })
7635            .unwrap(),
7636        )
7637        .unwrap();
7638        drop(initial_capture);
7639    }
7640
7641    fn install_delete_mutation_run(
7642        path: &Path,
7643        document: &SearchDocument,
7644        target_segment_id: u64,
7645        run_generation: u64,
7646    ) {
7647        install_edited_mutation_run(path, document, target_segment_id, run_generation, |_| {});
7648    }
7649
7650    #[cfg(feature = "full-text-search")]
7651    fn install_delete_mutation_runs(
7652        path: &Path,
7653        targets: &[(&SearchDocument, u64)],
7654        run_generation: u64,
7655    ) {
7656        let reader = SearchOutOfCoreReader::open(path).unwrap();
7657        let entries = targets
7658            .iter()
7659            .map(|(document, target_segment_id)| {
7660                Ok(mutation_run::SearchMutationRunEntry {
7661                    document_id: document.id.clone(),
7662                    target_segment_id: *target_segment_id,
7663                    operation: mutation_run::SearchMutationOperation::Delete,
7664                    retraction: mutation_run::SearchMutationRetraction::from_document(
7665                        document,
7666                        &reader.segments[0].lexical_projection,
7667                        &SearchAnalyzerLexicon::default(),
7668                    )?,
7669                })
7670            })
7671            .collect::<Result<Vec<_>>>()
7672            .unwrap();
7673        let manifest_path = path.join(OUT_OF_CORE_MANIFEST_FILE);
7674        let envelope: SearchOutOfCoreManifestEnvelope =
7675            serde_json::from_slice(&fs::read(&manifest_path).unwrap()).unwrap();
7676        let mut manifest = envelope.body;
7677        let mut documents_digest = manifest.segments.iter().fold(0, |digest, segment| {
7678            crate::lexical_projection::DocumentsDigest::combine(digest, segment.documents_digest)
7679        });
7680        for entry in &entries {
7681            documents_digest = crate::lexical_projection::DocumentsDigest::replace(
7682                documents_digest,
7683                entry.retraction.documents_digest,
7684                0,
7685            );
7686        }
7687        let analyzer_digest = lexical_analyzer_digest(&SearchAnalyzerLexicon::default());
7688        let run_body =
7689            mutation_run::SearchMutationRunBody::new(manifest.generation, analyzer_digest, entries)
7690                .unwrap();
7691        let run_bytes = run_body.encode().unwrap();
7692        let run_file = mutation_run::artifact_file(run_generation);
7693        fs::write(path.join(&run_file), &run_bytes).unwrap();
7694        manifest.mutation_runs = vec![SearchOutOfCoreMutationRunManifest {
7695            object: ArtifactObject::for_bytes(&run_bytes),
7696            generation: manifest.generation,
7697            file: run_file,
7698            len: run_bytes.len() as u64,
7699            checksum: checksum_bytes(&run_bytes),
7700            entry_count: targets.len(),
7701            analyzer_digest,
7702        }];
7703        manifest.document_count = manifest.document_count.checked_sub(targets.len()).unwrap();
7704        manifest.documents_digest = documents_digest;
7705        let body_bytes = serde_json::to_vec(&manifest).unwrap();
7706        fs::write(
7707            manifest_path,
7708            serde_json::to_vec(&SearchOutOfCoreManifestEnvelope {
7709                body: manifest,
7710                checksum: checksum_bytes(&body_bytes),
7711            })
7712            .unwrap(),
7713        )
7714        .unwrap();
7715    }
7716
7717    fn install_edited_mutation_run(
7718        path: &Path,
7719        document: &SearchDocument,
7720        target_segment_id: u64,
7721        run_generation: u64,
7722        edit: impl FnOnce(&mut mutation_run::SearchMutationRunEntry),
7723    ) {
7724        let reader = SearchOutOfCoreReader::open(path).unwrap();
7725        let mut entry = mutation_run::SearchMutationRunEntry {
7726            document_id: document.id.clone(),
7727            target_segment_id,
7728            operation: mutation_run::SearchMutationOperation::Delete,
7729            retraction: mutation_run::SearchMutationRetraction::from_document(
7730                document,
7731                &reader.segments[0].lexical_projection,
7732                &SearchAnalyzerLexicon::default(),
7733            )
7734            .unwrap(),
7735        };
7736        edit(&mut entry);
7737        // Recompute both envelope checksums and the manifest aggregate identity.
7738        // Invalid fixtures must reach target verification, not fail a checksum.
7739        let document_digest = entry.retraction.documents_digest;
7740        let manifest_path = path.join(OUT_OF_CORE_MANIFEST_FILE);
7741        let envelope: SearchOutOfCoreManifestEnvelope =
7742            serde_json::from_slice(&fs::read(&manifest_path).unwrap()).unwrap();
7743        let mut manifest = envelope.body;
7744        manifest.generation = run_generation;
7745        let analyzer_digest = lexical_analyzer_digest(&SearchAnalyzerLexicon::default());
7746        let run_body = mutation_run::SearchMutationRunBody::new(
7747            manifest.generation,
7748            analyzer_digest,
7749            vec![entry],
7750        )
7751        .unwrap();
7752        let run_bytes = run_body.encode().unwrap();
7753        let run_file = mutation_run::artifact_file(manifest.generation);
7754        fs::write(path.join(&run_file), &run_bytes).unwrap();
7755        manifest.mutation_runs = vec![SearchOutOfCoreMutationRunManifest {
7756            object: ArtifactObject::for_bytes(&run_bytes),
7757            generation: manifest.generation,
7758            file: run_file,
7759            len: run_bytes.len() as u64,
7760            checksum: checksum_bytes(&run_bytes),
7761            entry_count: 1,
7762            analyzer_digest,
7763        }];
7764        manifest.document_count = manifest.document_count.checked_sub(1).unwrap();
7765        manifest.documents_digest = crate::lexical_projection::DocumentsDigest::replace(
7766            manifest.segments.iter().fold(0, |digest, segment| {
7767                crate::lexical_projection::DocumentsDigest::combine(
7768                    digest,
7769                    segment.documents_digest,
7770                )
7771            }),
7772            document_digest,
7773            0,
7774        );
7775        let body_bytes = serde_json::to_vec(&manifest).unwrap();
7776        fs::write(
7777            manifest_path,
7778            serde_json::to_vec(&SearchOutOfCoreManifestEnvelope {
7779                body: manifest,
7780                checksum: checksum_bytes(&body_bytes),
7781            })
7782            .unwrap(),
7783        )
7784        .unwrap();
7785    }
7786
7787    #[test]
7788    fn out_of_core_reader_validates_mutation_run_artifact_closure() {
7789        let path = test_dir("mutation-run-artifact-closure");
7790        let document = document(0, "team");
7791        let mut index = SearchIndex::open(&path).unwrap();
7792        index.upsert(document.clone()).unwrap();
7793        index.checkpoint().unwrap();
7794        let old_reader = SearchOutOfCoreReader::open(&path).unwrap();
7795        install_delete_mutation_run(&path, &document, 0, 2);
7796
7797        // Integrity/cleanup and the public reader must agree on the complete
7798        // closure: the deleted physical version is retained for target-bound
7799        // validation but is not visible through hydration or search.
7800        let manifest: SearchOutOfCoreManifestEnvelope =
7801            serde_json::from_slice(&fs::read(path.join(OUT_OF_CORE_MANIFEST_FILE)).unwrap())
7802                .unwrap();
7803        let limited = SearchOutOfCoreReader::open_with_config(
7804            &path,
7805            SearchOutOfCoreConfig {
7806                max_mutation_run_bytes: NonZeroU64::new(manifest.body.mutation_runs[0].len - 1)
7807                    .unwrap(),
7808                ..SearchOutOfCoreConfig::default()
7809            },
7810        )
7811        .unwrap_err();
7812        assert!(limited
7813            .to_string()
7814            .contains("mutation-run artifact exceeds the configured read budget"));
7815        let reopened = SearchOutOfCoreReader::open(&path).unwrap();
7816        assert_eq!(reopened.document_count(), 0);
7817        assert!(reopened
7818            .hydrate_documents(std::slice::from_ref(&document.id))
7819            .is_err());
7820        let (validated, _, _) = load_artifact_closure(
7821            &path,
7822            &SearchOutOfCoreConfig::default(),
7823            &SearchAnalyzerLexicon::default(),
7824            SearchLexicalTermPolicy::default(),
7825            SearchLexicalSourcePolicy::default(),
7826        )
7827        .unwrap();
7828        assert_eq!(validated.document_count, 0);
7829        let generations = published_artifact_generations(&path, &SearchAnalyzerLexicon::default())
7830            .unwrap()
7831            .unwrap();
7832        assert_eq!(generations.active_generation, 2);
7833        assert_eq!(generations.lexical_generations, BTreeSet::from([1]));
7834        assert_eq!(generations.out_of_core_generations, BTreeSet::from([1, 2]));
7835
7836        let cleanup = index.retry_projection_cleanup(SearchProjectionCleanupOptions::default());
7837        assert_eq!(cleanup.generation_discovery_failures, 0);
7838        assert!(!cleanup.retry_required, "{cleanup:?}");
7839        assert!(path.join(&manifest.body.mutation_runs[0].file).is_file());
7840        assert_eq!(
7841            old_reader
7842                .hydrate_documents(std::slice::from_ref(&document.id))
7843                .unwrap()
7844                .documents,
7845            vec![document.clone()]
7846        );
7847
7848        fs::write(
7849            path.join(&manifest.body.mutation_runs[0].file),
7850            b"corrupt mutation run",
7851        )
7852        .unwrap();
7853        let error = SearchOutOfCoreReader::open(&path).unwrap_err();
7854        assert!(error
7855            .to_string()
7856            .contains("mutation-run artifact length or checksum mismatch"));
7857        fs::remove_dir_all(path).unwrap();
7858    }
7859
7860    #[test]
7861    fn mutation_publication_recovery_ignores_orphaned_run_after_manifest_failure() {
7862        let path = test_dir("mutation-publication-recovery");
7863        let document = document(0, "team");
7864        let mut index = SearchIndex::open(&path).unwrap();
7865        index.upsert(document.clone()).unwrap();
7866        index.checkpoint().unwrap();
7867
7868        install_delete_mutation_run(&path, &document, 0, 2);
7869        let active_manifest = path.join(OUT_OF_CORE_MANIFEST_FILE);
7870        let published = fs::read(&active_manifest).unwrap();
7871        let envelope: SearchOutOfCoreManifestEnvelope = serde_json::from_slice(&published).unwrap();
7872        let mutation_run = envelope.body.mutation_runs[0].file.clone();
7873        fs::copy(
7874            path.join(&mutation_run),
7875            path.join(mutation_run::artifact_file(3)),
7876        )
7877        .unwrap();
7878
7879        // A process crash after the run file is durable but before the
7880        // manifest publish must leave the previous committed generation
7881        // selectable. Recovery must not infer a mutation closure from the
7882        // orphaned artifact alone.
7883        fs::write(&active_manifest, b"torn manifest tail").unwrap();
7884        drop(index);
7885        let mut retry = SearchOutOfCoreGenerationWriter::create(&path, Default::default()).unwrap();
7886        retry.push(document.clone()).unwrap();
7887        let report = retry.finish().unwrap();
7888        assert_eq!(report.generation, 2);
7889        let recovered = SearchOutOfCoreReader::open(&path).unwrap();
7890        assert_eq!(recovered.generation(), 2);
7891        assert_eq!(recovered.document_count(), 1);
7892        assert_eq!(
7893            recovered
7894                .hydrate_documents(std::slice::from_ref(&document.id))
7895                .unwrap()
7896                .documents,
7897            vec![document]
7898        );
7899        drop(recovered);
7900
7901        assert!(path.join(mutation_run::artifact_file(3)).exists());
7902        let active: SearchOutOfCoreManifestEnvelope =
7903            serde_json::from_slice(&fs::read(&active_manifest).unwrap()).unwrap();
7904        assert!(active
7905            .body
7906            .mutation_runs
7907            .iter()
7908            .all(|run| run.generation != 3));
7909        fs::remove_dir_all(path).unwrap();
7910    }
7911
7912    // Test the shared read implementation through the public constructor. The
7913    // mutation writer and compaction lifecycle remain covered separately.
7914    #[cfg(feature = "full-text-search")]
7915    fn mutation_reader_for_test(path: &Path) -> SearchOutOfCoreReader {
7916        SearchOutOfCoreReader::open(path).unwrap()
7917    }
7918
7919    #[test]
7920    #[cfg(feature = "full-text-search")]
7921    fn reader_refresh_validates_only_new_retractions_without_compaction() {
7922        let path = test_dir("refresh-uncompacted-history");
7923        let mut writer =
7924            SearchOutOfCoreGenerationWriter::create(&path, Default::default()).unwrap();
7925        writer.push(document(0, "team")).unwrap();
7926        writer.push(document(1, "team")).unwrap();
7927        writer.finish().unwrap();
7928        let mut reader = SearchOutOfCoreReader::open(&path).unwrap();
7929        let original = reader.primary_segment().clone();
7930        for round in 0..24 {
7931            let row = crate::SearchProjectionRow {
7932                kind: crate::SearchProjectionKind::Memory,
7933                external_id: "000".into(),
7934                title: format!("graph revision {round}"),
7935                body: "graph refresh history ".repeat(32),
7936                embedding: Some(vec![1.0, round as f32]),
7937                source_id: None,
7938                metadata: BTreeMap::new(),
7939            };
7940            SearchOutOfCoreGenerationWriter::prepare_delta(
7941                &reader,
7942                crate::SearchProjectionDelta {
7943                    upserts: vec![row.clone()],
7944                    ..Default::default()
7945                },
7946                Default::default(),
7947            )
7948            .unwrap()
7949            .finish()
7950            .unwrap();
7951            let report = reader.refresh().unwrap();
7952            assert!(report.generation_changed);
7953            assert_eq!(report.validated_retractions, 1);
7954            assert_eq!(report.reused_retractions, round);
7955            assert_eq!(report.opened_content_segments, 1);
7956            assert_eq!(report.reused_content_segments, round + 1);
7957            assert!(std::ptr::eq(
7958                &original.payload,
7959                &reader.primary_segment().payload
7960            ));
7961            assert!(std::ptr::eq(
7962                &original.descriptor,
7963                &reader.primary_segment().descriptor
7964            ));
7965            assert!(std::ptr::eq(
7966                &original.layout,
7967                &reader.primary_segment().layout
7968            ));
7969            assert_eq!(reader.manifest.mutation_runs.len(), round + 1);
7970            assert_eq!(reader.document_count(), 2);
7971            assert_eq!(
7972                reader
7973                    .hydrate_documents(&["memory:000".into()])
7974                    .unwrap()
7975                    .documents,
7976                vec![row.into_document()]
7977            );
7978            let fresh = SearchOutOfCoreReader::open(&path).unwrap();
7979            assert_search_parity(
7980                &fresh
7981                    .search_with_options("graph", None, SearchMode::Text, options(10, None))
7982                    .unwrap()
7983                    .result,
7984                &reader
7985                    .search_with_options("graph", None, SearchMode::Text, options(10, None))
7986                    .unwrap()
7987                    .result,
7988            );
7989            let unchanged = reader.refresh().unwrap();
7990            assert!(!unchanged.generation_changed);
7991            assert_eq!(unchanged.validated_retractions, 0);
7992            assert_eq!(unchanged.reused_retractions, round + 1);
7993            assert_eq!(unchanged.opened_content_segments, 0);
7994            assert_eq!(unchanged.reused_content_segments, round + 2);
7995        }
7996        drop(reader);
7997        fs::remove_dir_all(path).unwrap();
7998    }
7999
8000    #[test]
8001    #[cfg(feature = "full-text-search")]
8002    fn reader_refresh_rejects_fabricated_new_retractions_and_retains_its_pin() {
8003        let path = test_dir("refresh-fabricated-target");
8004        let old = document(0, "team");
8005        publish_two_artifact_manifest(&path, old.clone(), document(1, "team"));
8006        let mut reader = SearchOutOfCoreReader::open(&path).unwrap();
8007        let generation = reader.generation();
8008        let expected = reader
8009            .search_with_options("graph", None, SearchMode::Text, options(10, None))
8010            .unwrap()
8011            .result;
8012        install_edited_mutation_run(&path, &old, 0, generation + 1, |entry| {
8013            entry.document_id = "memory:missing".into();
8014        });
8015        let error = reader.refresh().unwrap_err();
8016        assert!(
8017            error.to_string().contains("target document is absent"),
8018            "{error}"
8019        );
8020        assert_eq!(reader.generation(), generation);
8021        assert_search_parity(
8022            &expected,
8023            &reader
8024                .search_with_options("graph", None, SearchMode::Text, options(10, None))
8025                .unwrap()
8026                .result,
8027        );
8028        assert!(SearchOutOfCoreReader::open(&path).is_err());
8029        drop(reader);
8030        fs::remove_dir_all(path).unwrap();
8031    }
8032
8033    #[test]
8034    #[cfg(feature = "full-text-search")]
8035    fn reader_refresh_revalidates_a_changed_run_at_a_known_run_generation() {
8036        let path = test_dir("refresh-changed-run-identity");
8037        let old = document(0, "team");
8038        publish_two_artifact_manifest(&path, old.clone(), document(1, "team"));
8039        install_delete_mutation_run(&path, &old, 0, 3);
8040        let mut reader = SearchOutOfCoreReader::open(&path).unwrap();
8041        let generation = reader.generation();
8042        let mut manifest = reader.manifest.clone();
8043        let reference = &mut manifest.mutation_runs[0];
8044        let mut entry = reader.visibility.retractions().next().unwrap().clone();
8045        entry.retraction.lexical_document_len += 1;
8046        let bytes = mutation_run::SearchMutationRunBody::new(
8047            reference.generation,
8048            reference.analyzer_digest,
8049            vec![entry],
8050        )
8051        .unwrap()
8052        .encode()
8053        .unwrap();
8054        // Keep the run generation, target and aggregate document identity. Only
8055        // the immutable run fingerprint changes in this corruption fixture.
8056        fs::write(path.join(&reference.file), &bytes).unwrap();
8057        reference.len = bytes.len() as u64;
8058        reference.object = ArtifactObject::for_bytes(&bytes);
8059        reference.checksum = checksum_bytes(&bytes);
8060        manifest.generation += 1;
8061        fs::write(
8062            path.join(OUT_OF_CORE_MANIFEST_FILE),
8063            manifest.encode().unwrap(),
8064        )
8065        .unwrap();
8066        let error = reader.refresh().unwrap_err();
8067        assert!(
8068            error
8069                .to_string()
8070                .contains("does not match its target document"),
8071            "{error}"
8072        );
8073        assert_eq!(reader.generation(), generation);
8074        assert_eq!(reader.document_count(), 1);
8075        assert!(SearchOutOfCoreReader::open(&path).is_err());
8076        drop(reader);
8077        fs::remove_dir_all(path).unwrap();
8078    }
8079
8080    #[test]
8081    fn reader_refresh_revalidates_changed_content_references() {
8082        let path = test_dir("refresh-changed-content-reference");
8083        let mut writer =
8084            SearchOutOfCoreGenerationWriter::create(&path, Default::default()).unwrap();
8085        writer.push(document(0, "team")).unwrap();
8086        writer.finish().unwrap();
8087        let mut reader = SearchOutOfCoreReader::open(&path).unwrap();
8088        let generation = reader.generation();
8089        let mut manifest = reader.manifest.clone();
8090        manifest.generation += 1;
8091        manifest.segments[0].payload_len += 1;
8092        manifest.segments[0].objects.payload.byte_length += 1;
8093        fs::write(
8094            path.join(OUT_OF_CORE_MANIFEST_FILE),
8095            manifest.encode().unwrap(),
8096        )
8097        .unwrap();
8098        assert!(reader.refresh().is_err());
8099        assert_eq!(reader.generation(), generation);
8100        assert!(SearchOutOfCoreReader::open(&path).is_err());
8101        drop(reader);
8102        fs::remove_dir_all(path).unwrap();
8103    }
8104
8105    #[test]
8106    fn reader_refresh_rejects_missing_pinned_payload_and_lexical_paths() {
8107        let path = test_dir("refresh-missing-pinned-paths");
8108        let mut writer =
8109            SearchOutOfCoreGenerationWriter::create(&path, Default::default()).unwrap();
8110        writer.push(document(0, "team")).unwrap();
8111        writer.finish().unwrap();
8112        let mut reader = SearchOutOfCoreReader::open(&path).unwrap();
8113        let generation = reader.generation();
8114        let files = [
8115            reader.manifest.segments[0].payload_file.clone(),
8116            crate::lexical_projection::artifact_file(
8117                reader.primary_segment().lexical_projection.generation(),
8118            ),
8119        ];
8120        for file in files {
8121            let original = path.join(file);
8122            let retained = path.join("retained-missing-artifact");
8123            fs::rename(&original, &retained).unwrap();
8124            assert!(reader.refresh().is_err());
8125            let mut manifest = reader.manifest.clone();
8126            manifest.generation += 1;
8127            fs::write(
8128                path.join(OUT_OF_CORE_MANIFEST_FILE),
8129                manifest.encode().unwrap(),
8130            )
8131            .unwrap();
8132            assert!(reader.refresh().is_err());
8133            assert_eq!(reader.generation(), generation);
8134            fs::rename(retained, original).unwrap();
8135            fs::write(
8136                path.join(OUT_OF_CORE_MANIFEST_FILE),
8137                reader.manifest.encode().unwrap(),
8138            )
8139            .unwrap();
8140        }
8141        drop(reader);
8142        fs::remove_dir_all(path).unwrap();
8143    }
8144
8145    #[test]
8146    #[cfg(feature = "vector-search")]
8147    fn reader_refresh_revalidates_changed_global_embedding_identity() {
8148        let path = test_dir("refresh-embedding-identity");
8149        let mut writer =
8150            SearchOutOfCoreGenerationWriter::create(&path, Default::default()).unwrap();
8151        writer.push(document(0, "team")).unwrap();
8152        let report = writer.finish().unwrap();
8153        assert!(report.rabitq_artifact_bytes > 0);
8154        let mut reader = SearchOutOfCoreReader::open(&path).unwrap();
8155        let generation = reader.generation();
8156        for field in 0..3 {
8157            let mut manifest = reader.manifest.clone();
8158            manifest.generation += 1;
8159            match field {
8160                0 => manifest.embedding_model = Some("changed-model".into()),
8161                1 => manifest.embedding_version = Some("changed-version".into()),
8162                2 => manifest.embedding_dimension = Some(3),
8163                _ => unreachable!(),
8164            }
8165            fs::write(
8166                path.join(OUT_OF_CORE_MANIFEST_FILE),
8167                manifest.encode().unwrap(),
8168            )
8169            .unwrap();
8170            let error = reader.refresh().unwrap_err();
8171            assert!(error.to_string().contains("identity"), "{error}");
8172            assert_eq!(reader.generation(), generation);
8173            assert!(SearchOutOfCoreReader::open(&path).is_err());
8174        }
8175        drop(reader);
8176        fs::remove_dir_all(path).unwrap();
8177    }
8178
8179    #[test]
8180    fn reader_refresh_rejects_regressed_and_reused_head_generations() {
8181        let path = test_dir("refresh-head-identity");
8182        let mut writer =
8183            SearchOutOfCoreGenerationWriter::create(&path, Default::default()).unwrap();
8184        writer.push(document(0, "team")).unwrap();
8185        writer.finish().unwrap();
8186        let manifest_path = path.join(OUT_OF_CORE_MANIFEST_FILE);
8187        let old_bytes = fs::read(&manifest_path).unwrap();
8188        let mut reader = SearchOutOfCoreReader::open(&path).unwrap();
8189        SearchOutOfCoreGenerationWriter::prepare_delta(
8190            &reader,
8191            crate::SearchProjectionDelta {
8192                deletes: vec![document(0, "team").id],
8193                ..Default::default()
8194            },
8195            Default::default(),
8196        )
8197        .unwrap()
8198        .finish()
8199        .unwrap();
8200        reader.refresh().unwrap();
8201        let generation = reader.generation();
8202        let current_bytes = fs::read(&manifest_path).unwrap();
8203        fs::write(&manifest_path, old_bytes).unwrap();
8204        let error = reader.refresh().unwrap_err();
8205        assert!(
8206            error.to_string().contains("durable head regressed"),
8207            "{error}"
8208        );
8209        assert_eq!(reader.generation(), generation);
8210        let mut changed = SearchOutOfCoreManifestBody::decode(&current_bytes).unwrap();
8211        changed.source_graph_commit_epoch = Some(123);
8212        fs::write(&manifest_path, changed.encode().unwrap()).unwrap();
8213        let error = reader.refresh().unwrap_err();
8214        assert!(
8215            error.to_string().contains("changed an existing generation"),
8216            "{error}"
8217        );
8218        assert_eq!(reader.generation(), generation);
8219        fs::write(&manifest_path, current_bytes).unwrap();
8220        drop(reader);
8221        fs::remove_dir_all(path).unwrap();
8222    }
8223
8224    #[test]
8225    #[cfg(feature = "full-text-search")]
8226    fn mutation_publication_replacements_match_rebuild_and_can_delete_to_empty() {
8227        let path = test_dir("mutation-replace-publication");
8228        let merged_path = test_dir("mutation-replace-publication-merged");
8229        let old = document(0, "team");
8230        publish_two_artifact_manifest_with_initial_documents(
8231            &path,
8232            vec![old.clone(), document(1, "team")],
8233            Default::default(),
8234            document(2, "team"),
8235            Default::default(),
8236        );
8237        install_delete_mutation_run(&path, &old, 0, 3);
8238        let reader = mutation_reader_for_test(&path);
8239        let row = |id: &str, body: &str| crate::SearchProjectionRow {
8240            kind: crate::SearchProjectionKind::Memory,
8241            external_id: id.into(),
8242            title: "graph replacement".into(),
8243            body: body.into(),
8244            embedding: Some(vec![1.0, 0.0]),
8245            source_id: None,
8246            metadata: BTreeMap::new(),
8247        };
8248        let revived = row("000", "new graph version");
8249        let replacement = row("001", "updated graph memory");
8250        let (delta, _, _) = SearchOutOfCoreGenerationWriter::prepare_delta(
8251            &reader,
8252            crate::SearchProjectionDelta {
8253                upserts: vec![replacement.clone(), revived.clone()],
8254                deletes: vec!["memory:002".into()],
8255                ..Default::default()
8256            },
8257            Default::default(),
8258        )
8259        .unwrap()
8260        .finish()
8261        .unwrap();
8262        assert_eq!(delta.before_document_count, 2);
8263        assert_eq!(delta.after_document_count, 2);
8264        assert_eq!(delta.deleted_documents, 1);
8265        let current = mutation_reader_for_test(&path);
8266        let mut merged =
8267            SearchOutOfCoreGenerationWriter::create(&merged_path, Default::default()).unwrap();
8268        merged.push(revived.clone().into_document()).unwrap();
8269        merged.push(replacement.into_document()).unwrap();
8270        merged.finish().unwrap();
8271        let merged = SearchOutOfCoreReader::open(&merged_path).unwrap();
8272        let expected = merged
8273            .search_with_options("graph", None, SearchMode::Text, options(10, None))
8274            .unwrap();
8275        let actual = current
8276            .search_with_options("graph", None, SearchMode::Text, options(10, None))
8277            .unwrap();
8278        assert_search_parity(&expected.result, &actual.result);
8279        let latest = row("001", "latest graph revision");
8280        SearchOutOfCoreGenerationWriter::prepare_delta(
8281            &current,
8282            crate::SearchProjectionDelta {
8283                upserts: vec![latest.clone()],
8284                ..Default::default()
8285            },
8286            Default::default(),
8287        )
8288        .unwrap()
8289        .finish()
8290        .unwrap();
8291        let replaced = mutation_reader_for_test(&path);
8292        assert_eq!(
8293            replaced
8294                .hydrate_documents(&["memory:001".into()])
8295                .unwrap()
8296                .documents,
8297            vec![latest.into_document()]
8298        );
8299        assert_eq!(replaced.manifest.mutation_runs.len(), 3);
8300        SearchOutOfCoreGenerationWriter::prepare_delta(
8301            &replaced,
8302            crate::SearchProjectionDelta {
8303                deletes: vec!["memory:000".into(), "memory:001".into()],
8304                ..Default::default()
8305            },
8306            Default::default(),
8307        )
8308        .unwrap()
8309        .finish()
8310        .unwrap();
8311        let empty = mutation_reader_for_test(&path);
8312        assert_eq!(empty.document_count(), 0);
8313        assert_eq!(empty.manifest.documents_digest, 0);
8314        assert!(empty
8315            .search_with_options("graph", None, SearchMode::Text, options(10, None))
8316            .unwrap()
8317            .result
8318            .hits
8319            .is_empty());
8320        drop(empty);
8321        drop(replaced);
8322        drop(current);
8323        drop(reader);
8324        drop(merged);
8325        fs::remove_dir_all(path).unwrap();
8326        fs::remove_dir_all(merged_path).unwrap();
8327    }
8328
8329    #[test]
8330    #[cfg(feature = "full-text-search")]
8331    fn mutation_publication_budget_and_cancel_leave_active_manifest_unchanged() {
8332        let path = test_dir("mutation-publication-rejection");
8333        let old = document(0, "team");
8334        publish_two_artifact_manifest(&path, old.clone(), document(1, "team"));
8335        install_delete_mutation_run(&path, &old, 0, 3);
8336        let before = fs::read(path.join(OUT_OF_CORE_MANIFEST_FILE)).unwrap();
8337        let delta = || crate::SearchProjectionDelta {
8338            deletes: vec!["memory:001".into()],
8339            ..Default::default()
8340        };
8341        let mut reader = mutation_reader_for_test(&path);
8342        reader.config.max_mutation_run_bytes = NonZeroU64::MIN;
8343        assert!(SearchOutOfCoreGenerationWriter::prepare_delta(
8344            &reader,
8345            delta(),
8346            Default::default()
8347        )
8348        .unwrap_err()
8349        .to_string()
8350        .contains("mutation term spill exceeds byte admission"));
8351        assert_eq!(
8352            fs::read(path.join(OUT_OF_CORE_MANIFEST_FILE)).unwrap(),
8353            before
8354        );
8355        reader.config.max_mutation_run_bytes =
8356            SearchOutOfCoreConfig::default().max_mutation_run_bytes;
8357        reader.config.max_mutation_working_bytes = NonZeroU64::MIN;
8358        assert!(SearchOutOfCoreGenerationWriter::prepare_delta(
8359            &reader,
8360            delta(),
8361            Default::default()
8362        )
8363        .unwrap_err()
8364        .to_string()
8365        .contains("mutation-run working set"));
8366        assert_eq!(
8367            fs::read(path.join(OUT_OF_CORE_MANIFEST_FILE)).unwrap(),
8368            before
8369        );
8370        reader.config.max_mutation_working_bytes =
8371            SearchOutOfCoreConfig::default().max_mutation_working_bytes;
8372        let token = crate::RuntimeCancellationToken::new();
8373        let task = crate::RuntimeTaskContext::without_deadline(token.clone());
8374        let update = SearchOutOfCoreGenerationWriter::prepare_delta_with_context(
8375            &reader,
8376            delta(),
8377            Default::default(),
8378            task,
8379        )
8380        .unwrap();
8381        assert!(token.cancel());
8382        assert!(update
8383            .finish()
8384            .unwrap_err()
8385            .to_string()
8386            .contains("cancelled"));
8387        assert_eq!(
8388            fs::read(path.join(OUT_OF_CORE_MANIFEST_FILE)).unwrap(),
8389            before
8390        );
8391        drop(reader);
8392        let reopened = mutation_reader_for_test(&path);
8393        assert_eq!(reopened.document_count(), 1);
8394        drop(reopened);
8395        fs::remove_dir_all(path).unwrap();
8396    }
8397
8398    #[test]
8399    #[cfg(feature = "full-text-search")]
8400    fn mutation_delete_publication_reuses_content_and_repeated_delete_is_a_noop() {
8401        let path = test_dir("mutation-delete-publication");
8402        let old = document(0, "team");
8403        let deleted = document(1, "team");
8404        let live = document(2, "team");
8405        publish_two_artifact_manifest_with_initial_documents(
8406            &path,
8407            vec![old.clone(), deleted.clone()],
8408            Default::default(),
8409            live.clone(),
8410            Default::default(),
8411        );
8412        install_delete_mutation_run(&path, &old, 0, 3);
8413        let reader = mutation_reader_for_test(&path);
8414        let physical = serde_json::to_vec(&reader.manifest.segments).unwrap();
8415        let corpus_artifact_bytes: u64 = reader
8416            .manifest
8417            .segments
8418            .iter()
8419            .map(|segment| {
8420                segment
8421                    .descriptor_len
8422                    .saturating_add(segment.payload_len)
8423                    .saturating_add(segment.metadata_payload_len)
8424                    .saturating_add(segment.vector_payload_len)
8425                    .saturating_add(segment.layout_len)
8426                    .saturating_add(segment.lexical_manifest_len)
8427                    .saturating_add(segment.rabitq_artifact_len.unwrap_or_default())
8428            })
8429            .sum();
8430        let before_payloads: Vec<_> = reader
8431            .manifest
8432            .segments
8433            .iter()
8434            .map(|segment| {
8435                (
8436                    segment.payload_file.clone(),
8437                    fs::read(path.join(&segment.payload_file)).unwrap(),
8438                )
8439            })
8440            .collect();
8441        let prepare = |reader: &SearchOutOfCoreReader| {
8442            SearchOutOfCoreGenerationWriter::prepare_delta(
8443                reader,
8444                crate::SearchProjectionDelta {
8445                    deletes: vec![deleted.id.clone(), "memory:missing".into()],
8446                    ..Default::default()
8447                },
8448                Default::default(),
8449            )
8450            .unwrap()
8451        };
8452        let update = prepare(&reader);
8453        let stale = prepare(&reader);
8454        assert_eq!(update.delta_report().deleted_documents, 1);
8455        assert_eq!(update.source_read_metrics().hydrated_documents, 0);
8456        assert_eq!(update.source_read_metrics().streamed_documents, 1);
8457        let (_, build, _) = update.finish().unwrap();
8458        assert_eq!(build.document_count, 1);
8459        assert_eq!(build.document_payload_bytes, 0);
8460        assert_eq!(build.lexical_artifact_bytes, 0);
8461        // The tiny fixture's binary vector sidecars make the corpus about as
8462        // small as one manifest, so compare the rewritten content bytes instead.
8463        let rewritten = build.descriptor_bytes
8464            + build.metadata_payload_bytes
8465            + build.vector_payload_bytes
8466            + build.rabitq_artifact_bytes;
8467        assert!(
8468            rewritten == 0,
8469            "delete-only checkpoint rewrote the corpus: {rewritten} of {corpus_artifact_bytes}"
8470        );
8471        assert!(stale
8472            .finish()
8473            .unwrap_err()
8474            .to_string()
8475            .contains("base changed"));
8476        let reopened = mutation_reader_for_test(&path);
8477        assert_eq!(
8478            serde_json::to_vec(&reopened.manifest.segments).unwrap(),
8479            physical
8480        );
8481        assert_eq!(reopened.manifest.mutation_runs.len(), 2);
8482        assert_eq!(
8483            build.generation_bytes,
8484            build.manifest_bytes + reopened.manifest.mutation_runs[1].len
8485        );
8486        assert_eq!(
8487            reopened
8488                .hydrate_documents(std::slice::from_ref(&live.id))
8489                .unwrap()
8490                .documents,
8491            vec![live.clone()]
8492        );
8493        assert!(reopened
8494            .hydrate_documents(std::slice::from_ref(&deleted.id))
8495            .is_err());
8496        for (name, bytes) in before_payloads {
8497            assert_eq!(fs::read(path.join(name)).unwrap(), bytes);
8498        }
8499        let repeated = prepare(&reopened);
8500        assert_eq!(repeated.delta_report().deleted_documents, 0);
8501        assert_eq!(repeated.source_read_metrics().hydrated_documents, 0);
8502        let (_, repeated_build, _) = repeated.finish().unwrap();
8503        let final_reader = mutation_reader_for_test(&path);
8504        assert_eq!(final_reader.manifest.mutation_runs.len(), 2);
8505        assert_eq!(
8506            repeated_build.generation_bytes,
8507            repeated_build.manifest_bytes
8508        );
8509        assert_eq!(final_reader.document_count(), 1);
8510        assert_eq!(
8511            serde_json::to_vec(&final_reader.manifest.segments).unwrap(),
8512            physical
8513        );
8514        drop(final_reader);
8515        drop(reopened);
8516        drop(reader);
8517        fs::remove_dir_all(path).unwrap();
8518    }
8519
8520    #[test]
8521    #[cfg(feature = "full-text-search")]
8522    fn mutation_append_preserves_retractions_and_logical_identity() {
8523        let path = test_dir("mutation-append-preservation");
8524        let old = document(0, "team");
8525        let live = document(1, "team");
8526        publish_two_artifact_manifest(&path, old.clone(), live.clone());
8527        install_delete_mutation_run(&path, &old, 0, 3);
8528        let reader = mutation_reader_for_test(&path);
8529        let run = reader.manifest.mutation_runs[0].clone();
8530        let run_bytes = fs::read(path.join(&run.file)).unwrap();
8531        let appended = crate::SearchProjectionRow {
8532            kind: crate::SearchProjectionKind::Memory,
8533            external_id: "999".into(),
8534            title: "appended".into(),
8535            body: "graph memory".into(),
8536            embedding: None,
8537            source_id: None,
8538            metadata: BTreeMap::new(),
8539        };
8540        let update = SearchOutOfCoreGenerationWriter::prepare_delta(
8541            &reader,
8542            crate::SearchProjectionDelta {
8543                upserts: vec![appended.clone()],
8544                ..Default::default()
8545            },
8546            Default::default(),
8547        )
8548        .unwrap();
8549        assert_eq!(update.source_read_metrics().hydrated_documents, 0);
8550        let (_, build, _) = update.finish().unwrap();
8551        assert_eq!(build.document_count, 2);
8552        let reopened = mutation_reader_for_test(&path);
8553        assert_eq!(reopened.manifest.mutation_runs.len(), 1);
8554        assert_eq!(reopened.manifest.mutation_runs[0].file, run.file);
8555        assert_eq!(fs::read(path.join(&run.file)).unwrap(), run_bytes);
8556        assert_eq!(reopened.manifest.embedding_dimension, Some(2));
8557        assert!(reopened
8558            .hydrate_documents(std::slice::from_ref(&old.id))
8559            .is_err());
8560        let ids = [live.id.clone(), "memory:999".into()];
8561        let output = reopened.hydrate_documents(&ids).unwrap();
8562        assert_eq!(output.documents, vec![live, appended.into_document()]);
8563        assert_eq!(reopened.document_count(), 2);
8564        assert!(!reopened.visibility.is_visible(0, &old.id));
8565        drop(reopened);
8566        drop(reader);
8567        fs::remove_dir_all(path).unwrap();
8568    }
8569
8570    #[test]
8571    #[cfg(all(feature = "full-text-search", feature = "vector-search"))]
8572    fn mutation_rabitq_budget_fallback_is_exact_observable_and_failure_specific() {
8573        let path = test_dir("mutation-rabitq-budget-fallback");
8574        let old = document(0, "team");
8575        let unchanged = document(1, "team");
8576        let mut replacement = old.clone();
8577        replacement.content = "updated graph memory".into();
8578        replacement.embedding = Some(vec![16.0, 1.0]);
8579        publish_two_artifact_manifest_with_initial_documents(
8580            &path,
8581            vec![old.clone(), unchanged],
8582            Default::default(),
8583            replacement,
8584            Default::default(),
8585        );
8586        install_edited_mutation_run(&path, &old, 0, 3, |entry| {
8587            entry.operation = mutation_run::SearchMutationOperation::Replace
8588        });
8589        let mut reader = mutation_reader_for_test(&path);
8590        reader.config.max_vector_candidates = NonZeroUsize::new(4).unwrap();
8591        // Enough for the retained headers and scalar scoring of two live IDs,
8592        // but only one byte remains for the ordinal allowlist plus its block.
8593        let budget = vector_serving::candidate_working_bytes(4).unwrap() + 1;
8594        reader.config.max_vector_search_working_bytes = NonZeroUsize::new(budget).unwrap();
8595        let search = |reader: &SearchOutOfCoreReader, mode| {
8596            reader.search_with_options_compressed_vector_projection_mode(
8597                "",
8598                Some(&[1.0, 16.0]),
8599                SearchMode::Vector,
8600                options(1, None),
8601                mode,
8602            )
8603        };
8604        let expected = search(&reader, CompressedVectorSearchMode::Disabled).unwrap();
8605        // The allowlist working set is a resource refusal naming the option
8606        // that bound it, not a storage fault (#1767).
8607        let assert_allowlist_refusal = |error: HawDBError, budget_option: &str| match error {
8608            HawDBError::ResourceBudgetExceeded(details) => {
8609                assert_eq!(details.resource, ResourceBudgetKind::MemoryBytes);
8610                assert_eq!(details.budget_option, budget_option, "{details:?}");
8611                assert!(details.requested > details.budget, "{details:?}");
8612            }
8613            other => panic!("{other:?}"),
8614        };
8615        assert_allowlist_refusal(
8616            search(&reader, CompressedVectorSearchMode::Required).unwrap_err(),
8617            "SearchOutOfCoreConfig.max_vector_search_working_bytes",
8618        );
8619        // With a roomy reader cap, the per-query admission binds instead.
8620        let mut roomy = mutation_reader_for_test(&path);
8621        roomy.config.max_vector_candidates = NonZeroUsize::new(4).unwrap();
8622        assert_allowlist_refusal(
8623            roomy
8624                .search_with_options_compressed_vector_projection_execution_options(
8625                    "",
8626                    Some(&[1.0, 16.0]),
8627                    SearchMode::Vector,
8628                    options(1, None),
8629                    CompressedVectorSearchMode::Required,
8630                    VectorSearchExecutionOptions::bounded(NonZeroUsize::MIN, budget, None),
8631                )
8632                .unwrap_err(),
8633            "VectorSearchExecutionOptions.max_working_bytes",
8634        );
8635        drop(roomy);
8636        let actual = search(&reader, CompressedVectorSearchMode::Preferred).unwrap();
8637        assert_search_parity(&expected.result, &actual.result);
8638        assert!(actual
8639            .result
8640            .fallback_reason_codes
8641            .contains(&SearchFallbackReasonCode::CompressedVectorBudgetExceeded));
8642
8643        let cancellation = crate::RuntimeCancellationToken::new();
8644        let task = crate::RuntimeTaskContext::without_deadline(cancellation.clone());
8645        assert!(cancellation.cancel());
8646        let error = reader
8647            .search_with_options_compressed_vector_projection_execution_options(
8648                "",
8649                Some(&[1.0, 16.0]),
8650                SearchMode::Vector,
8651                options(1, None),
8652                CompressedVectorSearchMode::Preferred,
8653                VectorSearchExecutionOptions::bounded(NonZeroUsize::MIN, budget, Some(&task)),
8654            )
8655            .unwrap_err();
8656        assert!(error.to_string().contains("cancelled"), "{error}");
8657
8658        reader.config.max_vector_search_working_bytes =
8659            SearchOutOfCoreConfig::default().max_vector_search_working_bytes;
8660        let mismatch = reader
8661            .search_with_options_compressed_vector_projection_mode(
8662                "",
8663                Some(&[1.0]),
8664                SearchMode::Vector,
8665                options(1, None),
8666                CompressedVectorSearchMode::Preferred,
8667            )
8668            .unwrap();
8669        assert!(mismatch
8670            .result
8671            .fallback_reason_codes
8672            .contains(&SearchFallbackReasonCode::VectorDimensionMismatch));
8673        assert!(!mismatch
8674            .result
8675            .fallback_reason_codes
8676            .contains(&SearchFallbackReasonCode::CompressedVectorBudgetExceeded));
8677
8678        // Mapped artifacts are immutable for the reader's lifetime. Drop the
8679        // mapping before corrupting files, then verify open rejects corruption.
8680        let segments = reader.manifest.segments.clone();
8681        drop(reader);
8682        for segment in &segments {
8683            let artifact = segment.rabitq_artifact_file.as_ref().unwrap();
8684            fs::write(path.join(artifact), b"truncated projection").unwrap();
8685        }
8686        let error = SearchOutOfCoreReader::open(&path).unwrap_err();
8687        assert!(error.to_string().contains("RaBitQ artifact"), "{error}");
8688        fs::remove_dir_all(path).unwrap();
8689    }
8690
8691    #[test]
8692    #[cfg(all(feature = "full-text-search", feature = "vector-search"))]
8693    fn mutation_rabitq_equal_scores_match_merged_logical_id_order() {
8694        let path = test_dir("mutation-rabitq-ties");
8695        let merged_path = test_dir("mutation-rabitq-ties-merged");
8696        let mut old = document(0, "team");
8697        old.embedding = Some(vec![1.0, 1.0]);
8698        let mut replacement = old.clone();
8699        replacement.content = "updated graph memory".into();
8700        let mut unchanged = document(1, "team");
8701        unchanged.embedding = replacement.embedding.clone();
8702        publish_two_artifact_manifest_with_initial_documents(
8703            &path,
8704            vec![old.clone(), unchanged.clone()],
8705            Default::default(),
8706            replacement.clone(),
8707            Default::default(),
8708        );
8709        install_edited_mutation_run(&path, &old, 0, 3, |entry| {
8710            entry.operation = mutation_run::SearchMutationOperation::Replace
8711        });
8712        let mut reader = mutation_reader_for_test(&path);
8713        reader.config.max_vector_candidates = NonZeroUsize::new(1).unwrap();
8714        let mut writer = SearchOutOfCoreGenerationWriter::create(
8715            &merged_path,
8716            SearchOutOfCoreGenerationBuildOptions {
8717                vector_backend: None,
8718                ..Default::default()
8719            },
8720        )
8721        .unwrap();
8722        writer.push(replacement).unwrap();
8723        writer.push(unchanged).unwrap();
8724        writer.finish().unwrap();
8725        let mut merged = SearchOutOfCoreReader::open(&merged_path).unwrap();
8726        merged.config.max_vector_candidates = NonZeroUsize::new(1).unwrap();
8727        let search = |reader: &SearchOutOfCoreReader| {
8728            reader
8729                .search_with_options_compressed_vector_projection_mode(
8730                    "",
8731                    Some(&[1.0, 1.0]),
8732                    SearchMode::Vector,
8733                    options(1, None),
8734                    CompressedVectorSearchMode::Required,
8735                )
8736                .unwrap()
8737        };
8738        let expected = search(&merged);
8739        let actual = search(&reader);
8740        assert_eq!(expected.result.hits[0].id, "memory:000");
8741        assert_search_parity(&expected.result, &actual.result);
8742        fs::remove_dir_all(path).unwrap();
8743        fs::remove_dir_all(merged_path).unwrap();
8744    }
8745
8746    #[test]
8747    #[cfg(feature = "full-text-search")]
8748    fn mutation_visibility_matches_merged_reads_for_delete_and_replace() {
8749        for replace in [false, true] {
8750            let path = test_dir(&format!("mutation-visible-{replace}"));
8751            let merged_path = test_dir(&format!("mutation-merged-{replace}"));
8752            let old = document(0, "old-space");
8753            let mut live = if replace {
8754                old.clone()
8755            } else {
8756                document(1, "live-space")
8757            };
8758            live.title = "graph replacement".into();
8759            live.content = "memory current version".into();
8760            live.metadata.insert("space_id".into(), "live-space".into());
8761            live.embedding = Some(vec![16.0, 1.0]);
8762            publish_two_artifact_manifest(&path, old.clone(), live.clone());
8763            install_edited_mutation_run(&path, &old, 0, 3, |entry| {
8764                if replace {
8765                    entry.operation = mutation_run::SearchMutationOperation::Replace;
8766                }
8767            });
8768            let reader = SearchOutOfCoreReader::open(&path).unwrap();
8769            let mut merged = SearchOutOfCoreGenerationWriter::create(
8770                &merged_path,
8771                SearchOutOfCoreGenerationBuildOptions {
8772                    vector_backend: None,
8773                    ..Default::default()
8774                },
8775            )
8776            .unwrap();
8777            merged.push(live.clone()).unwrap();
8778            merged.finish().unwrap();
8779            let merged = SearchOutOfCoreReader::open(&merged_path).unwrap();
8780
8781            assert_eq!(reader.document_count(), 1);
8782            assert_eq!(
8783                reader
8784                    .hydrate_documents(std::slice::from_ref(&live.id))
8785                    .unwrap()
8786                    .documents,
8787                vec![live.clone()]
8788            );
8789            // The deleted id is hidden by the mutation run's visibility, not
8790            // removed from its content segment.
8791            // A replacement keeps the id, so it is requested once.
8792            let mut ids = vec![live.id.clone()];
8793            if !replace {
8794                ids.push(old.id.clone());
8795            }
8796            ids.push("memory:never".to_string());
8797            let lookup = reader.lookup_documents(&ids).unwrap();
8798            assert_eq!(lookup.documents, vec![live.clone()]);
8799            if replace {
8800                assert_eq!(lookup.missing_document_ids, vec!["memory:never"]);
8801            } else {
8802                // Hydration by id refuses a deleted id as a caller mistake
8803                // (#1767); lookup reports it missing (#1786).
8804                let deleted = reader
8805                    .hydrate_documents(std::slice::from_ref(&old.id))
8806                    .unwrap_err();
8807                assert!(matches!(deleted, HawDBError::Semantic(_)), "{deleted:?}");
8808                assert_eq!(
8809                    lookup.missing_document_ids,
8810                    vec![old.id.clone(), "memory:never".to_string()]
8811                );
8812            }
8813            let mut modes = vec![SearchMode::Text];
8814            #[cfg(feature = "vector-search")]
8815            modes.extend([SearchMode::Vector, SearchMode::Hybrid]);
8816            for mode in modes.drain(..) {
8817                for filter in [None, Some("old-space"), Some("live-space")] {
8818                    let mut options = options(10, None);
8819                    if let Some(space) = filter {
8820                        options
8821                            .metadata_filters
8822                            .insert("space_id".into(), space.into());
8823                    }
8824                    let expected = merged
8825                        .search_with_options("graph", Some(&[1.0, 16.0]), mode, options.clone())
8826                        .unwrap();
8827                    let actual = reader
8828                        .search_with_options("graph", Some(&[1.0, 16.0]), mode, options)
8829                        .unwrap();
8830                    assert_search_parity(&expected.result, &actual.result);
8831                }
8832            }
8833            assert_eq!(
8834                reader
8835                    .search_with_options("storage", None, SearchMode::Text, options(10, None))
8836                    .unwrap()
8837                    .result
8838                    .total_hits,
8839                0
8840            );
8841            #[cfg(feature = "vector-search")]
8842            {
8843                let actual = reader
8844                    .search_with_options_compressed_vector_projection_mode(
8845                        "",
8846                        Some(&[1.0, 16.0]),
8847                        SearchMode::Vector,
8848                        options(10, None),
8849                        CompressedVectorSearchMode::Required,
8850                    )
8851                    .unwrap();
8852                let expected = merged
8853                    .search_with_options_compressed_vector_projection_mode(
8854                        "",
8855                        Some(&[1.0, 16.0]),
8856                        SearchMode::Vector,
8857                        options(10, None),
8858                        CompressedVectorSearchMode::Required,
8859                    )
8860                    .unwrap();
8861                assert_search_parity(&expected.result, &actual.result);
8862            }
8863            fs::remove_dir_all(path).unwrap();
8864            fs::remove_dir_all(merged_path).unwrap();
8865        }
8866    }
8867
8868    #[test]
8869    #[cfg(feature = "full-text-search")]
8870    fn mutation_compaction_absorbs_a_complete_target_closure() {
8871        let path = test_dir("mutation-compaction-guard");
8872        let old = document(0, "old-space");
8873        let live = document(1, "live-space");
8874        publish_two_artifact_manifest(&path, old.clone(), live.clone());
8875        install_delete_mutation_run(&path, &old, 0, 3);
8876        let reader = SearchOutOfCoreReader::open(&path).unwrap();
8877        let policy =
8878            crate::out_of_core::generation_writer::SearchOutOfCoreSegmentCompactionPolicy::default(
8879            );
8880        assert!(
8881            SearchOutOfCoreGenerationWriter::segment_compaction_work_plan(
8882                &reader,
8883                policy,
8884                hawdb_qos::BackgroundWorkHint::default(),
8885            )
8886            .unwrap()
8887            .is_some()
8888        );
8889        let report =
8890            SearchOutOfCoreGenerationWriter::compact_segments(&reader, policy, Default::default())
8891                .unwrap()
8892                .unwrap();
8893        assert_eq!(report.build().document_count, 1);
8894        drop(reader);
8895        let reopened = SearchOutOfCoreReader::open(&path).unwrap();
8896        assert!(reopened.manifest.mutation_runs.is_empty());
8897        assert_eq!(reopened.manifest.segments.len(), 1);
8898        assert_eq!(
8899            reopened
8900                .hydrate_documents(std::slice::from_ref(&live.id))
8901                .unwrap()
8902                .documents,
8903            vec![live]
8904        );
8905        fs::remove_dir_all(path).unwrap();
8906    }
8907
8908    #[test]
8909    #[cfg(feature = "full-text-search")]
8910    fn mutation_compaction_rewrites_entries_outside_the_selected_range() {
8911        let path = test_dir("mutation-compaction-partial-closure");
8912        let first = document(0, "first-space");
8913        let live = document(1, "live-space");
8914        let outside = document(2, "outside-space");
8915        publish_two_artifact_manifest(&path, first.clone(), live.clone());
8916
8917        let reader = SearchOutOfCoreReader::open(&path).unwrap();
8918        let outside_row = crate::SearchProjectionRow {
8919            kind: crate::SearchProjectionKind::Memory,
8920            external_id: "002".into(),
8921            title: outside.title.clone(),
8922            body: outside.content.clone(),
8923            embedding: outside.embedding.clone(),
8924            source_id: None,
8925            metadata: outside.metadata.clone(),
8926        };
8927        let outside = outside_row.clone().into_document();
8928        SearchOutOfCoreGenerationWriter::prepare_delta(
8929            &reader,
8930            crate::SearchProjectionDelta {
8931                upserts: vec![outside_row],
8932                ..Default::default()
8933            },
8934            Default::default(),
8935        )
8936        .unwrap()
8937        .finish()
8938        .unwrap();
8939        drop(reader);
8940
8941        install_delete_mutation_runs(&path, &[(&first, 0), (&outside, 2)], 3);
8942        let reader = SearchOutOfCoreReader::open(&path).unwrap();
8943        let policy =
8944            crate::out_of_core::generation_writer::SearchOutOfCoreSegmentCompactionPolicy::default(
8945            );
8946        let report =
8947            SearchOutOfCoreGenerationWriter::compact_segments(&reader, policy, Default::default())
8948                .unwrap()
8949                .unwrap();
8950        assert_eq!(report.build().document_count, 1);
8951        drop(reader);
8952
8953        let reopened = SearchOutOfCoreReader::open(&path).unwrap();
8954        assert_eq!(reopened.document_count(), 1);
8955        assert_eq!(reopened.manifest.mutation_runs.len(), 1);
8956        assert_eq!(reopened.manifest.mutation_runs[0].entry_count, 1);
8957        assert!(reopened
8958            .hydrate_documents(std::slice::from_ref(&live.id))
8959            .unwrap()
8960            .documents
8961            .contains(&live));
8962        assert!(reopened
8963            .hydrate_documents(std::slice::from_ref(&outside.id))
8964            .is_err());
8965        fs::remove_dir_all(path).unwrap();
8966    }
8967
8968    #[test]
8969    #[cfg(feature = "full-text-search")]
8970    fn mutation_compaction_publication_failure_preserves_the_active_closure() {
8971        let path = test_dir("mutation-compaction-publication-failure");
8972        let old = document(0, "old-space");
8973        let live = document(1, "live-space");
8974        publish_two_artifact_manifest(&path, old.clone(), live.clone());
8975        install_delete_mutation_run(&path, &old, 0, 3);
8976        let before = fs::read(path.join(OUT_OF_CORE_MANIFEST_FILE)).unwrap();
8977        let reader = SearchOutOfCoreReader::open(&path).unwrap();
8978        let error = SearchOutOfCoreGenerationWriter::compact_segments(
8979            &reader,
8980            SearchOutOfCoreSegmentCompactionPolicy::default(),
8981            SearchOutOfCoreGenerationBuildOptions {
8982                max_generation_bytes: NonZeroU64::MIN,
8983                ..Default::default()
8984            },
8985        )
8986        .unwrap_err();
8987        assert!(error.to_string().contains("published bytes"), "{error}");
8988        assert_eq!(
8989            fs::read(path.join(OUT_OF_CORE_MANIFEST_FILE)).unwrap(),
8990            before
8991        );
8992        drop(reader);
8993        let reopened = SearchOutOfCoreReader::open(&path).unwrap();
8994        assert_eq!(reopened.document_count(), 1);
8995        assert!(reopened.manifest.mutation_runs.len() == 1);
8996        assert!(fs::read_dir(&path)
8997            .unwrap()
8998            .filter_map(|entry| entry.ok())
8999            .all(|entry| !entry
9000                .file_name()
9001                .to_string_lossy()
9002                .starts_with(".search-generation.")));
9003        fs::remove_dir_all(path).unwrap();
9004    }
9005
9006    #[test]
9007    #[cfg(feature = "full-text-search")]
9008    fn mutation_sustained_replacements_append_and_compaction_reopen_each_round() {
9009        let path = test_dir("mutation-sustained-rounds");
9010        let mut initial = SearchOutOfCoreGenerationWriter::create(
9011            &path,
9012            SearchOutOfCoreGenerationBuildOptions {
9013                ..Default::default()
9014            },
9015        )
9016        .unwrap();
9017        initial.push(document(0, "team")).unwrap();
9018        initial.finish().unwrap();
9019        for number in 1..32 {
9020            let reader = SearchOutOfCoreReader::open(&path).unwrap();
9021            let mut appended = document(number % 16, "team");
9022            appended.id = format!("memory:{number:03}");
9023            appended
9024                .metadata
9025                .insert("external_id".to_string(), number.to_string());
9026            let row = crate::SearchProjectionRow {
9027                kind: crate::SearchProjectionKind::Memory,
9028                external_id: format!("{number:03}"),
9029                title: appended.title.clone(),
9030                body: appended.content.clone(),
9031                embedding: appended.embedding.clone(),
9032                source_id: None,
9033                metadata: appended.metadata.clone(),
9034            };
9035            SearchOutOfCoreGenerationWriter::prepare_delta(
9036                &reader,
9037                crate::SearchProjectionDelta {
9038                    upserts: vec![row],
9039                    ..Default::default()
9040                },
9041                Default::default(),
9042            )
9043            .unwrap()
9044            .finish()
9045            .unwrap();
9046        }
9047        let initial_reader = SearchOutOfCoreReader::open(&path).unwrap();
9048        assert!(
9049            initial_reader.manifest.segments.len() >= 2,
9050            "the sustained fixture must contain multiple immutable segments"
9051        );
9052        drop(initial_reader);
9053
9054        let policy = SearchOutOfCoreSegmentCompactionPolicy::default()
9055            .with_level_zero_target_bytes(NonZeroU64::new(8 * 1024).unwrap())
9056            .unwrap();
9057        let mut compaction_count = 0;
9058        for round in 0..4 {
9059            let reader = SearchOutOfCoreReader::open(&path).unwrap();
9060            let mut replaced = document(round, "replacement-space");
9061            replaced
9062                .metadata
9063                .insert("external_id".to_string(), format!("{round:03}"));
9064            let mut appended = document(0, "append-space");
9065            appended.id = format!("memory:{:03}", 100 + round);
9066            appended
9067                .metadata
9068                .insert("external_id".to_string(), (100 + round).to_string());
9069            let replacement_row = crate::SearchProjectionRow {
9070                kind: crate::SearchProjectionKind::Memory,
9071                external_id: format!("{round:03}"),
9072                title: replaced.title.clone(),
9073                body: replaced.content.clone(),
9074                embedding: replaced.embedding.clone(),
9075                source_id: None,
9076                metadata: replaced.metadata.clone(),
9077            };
9078            let appended_row = crate::SearchProjectionRow {
9079                kind: crate::SearchProjectionKind::Memory,
9080                external_id: format!("{:03}", 100 + round),
9081                title: appended.title.clone(),
9082                body: appended.content.clone(),
9083                embedding: appended.embedding.clone(),
9084                source_id: None,
9085                metadata: appended.metadata.clone(),
9086            };
9087            SearchOutOfCoreGenerationWriter::prepare_delta(
9088                &reader,
9089                crate::SearchProjectionDelta {
9090                    upserts: vec![replacement_row, appended_row],
9091                    ..Default::default()
9092                },
9093                Default::default(),
9094            )
9095            .unwrap()
9096            .finish()
9097            .unwrap();
9098            drop(reader);
9099
9100            let reader = SearchOutOfCoreReader::open(&path).unwrap();
9101            let compaction = SearchOutOfCoreGenerationWriter::compact_segments(
9102                &reader,
9103                policy,
9104                Default::default(),
9105            )
9106            .unwrap();
9107            if let Some(report) = &compaction {
9108                compaction_count += 1;
9109                assert!(report.source_segment_count() >= 2);
9110                assert!(report.source_bytes() > 0);
9111                assert!(report.build().document_count > 0);
9112            }
9113            drop(reader);
9114
9115            let reopened = SearchOutOfCoreReader::open(&path).unwrap();
9116            assert_eq!(reopened.document_count(), 33 + round);
9117            assert_eq!(
9118                reopened
9119                    .hydrate_documents(&[replaced.id.clone()])
9120                    .unwrap()
9121                    .documents,
9122                vec![replaced]
9123            );
9124            assert_eq!(
9125                reopened
9126                    .hydrate_documents(&[appended.id.clone()])
9127                    .unwrap()
9128                    .documents,
9129                vec![appended]
9130            );
9131            drop(reopened);
9132        }
9133        assert!(
9134            compaction_count > 0,
9135            "sustained fixture must compact at least once"
9136        );
9137        fs::remove_dir_all(path).unwrap();
9138    }
9139
9140    #[test]
9141    fn out_of_core_mutation_retractions_must_match_physical_targets() {
9142        for corruption in [
9143            "missing_id",
9144            "id_gap",
9145            "other_id",
9146            "digest",
9147            "length",
9148            "missing_term",
9149            "extra_term",
9150        ] {
9151            let path = test_dir(&format!("mutation-retraction-{corruption}"));
9152            let previous = document(0, "team");
9153            let mut index = SearchIndex::open(&path).unwrap();
9154            index.upsert(previous.clone()).unwrap();
9155            index.upsert(document(2, "team")).unwrap();
9156            index.checkpoint().unwrap();
9157            install_edited_mutation_run(&path, &previous, 0, 2, |entry| match corruption {
9158                "missing_id" => entry.document_id = "memory:missing".into(),
9159                "id_gap" => entry.document_id = "memory:001".into(),
9160                "other_id" => entry.document_id = "memory:002".into(),
9161                "digest" => entry.retraction.documents_digest ^= 1,
9162                "length" => entry.retraction.lexical_document_len += 1,
9163                "missing_term" => {
9164                    entry.retraction.unique_terms.owned_mut().pop().unwrap();
9165                }
9166                "extra_term" => {
9167                    entry
9168                        .retraction
9169                        .unique_terms
9170                        .owned_mut()
9171                        .push("zzzzzz".into());
9172                }
9173                _ => unreachable!(),
9174            });
9175            let error = load_artifact_closure(
9176                &path,
9177                &SearchOutOfCoreConfig::default(),
9178                &SearchAnalyzerLexicon::default(),
9179                SearchLexicalTermPolicy::default(),
9180                SearchLexicalSourcePolicy::default(),
9181            )
9182            .unwrap_err();
9183            let expected = if matches!(corruption, "missing_id" | "id_gap") {
9184                "target document is absent"
9185            } else {
9186                "retraction does not match its target document"
9187            };
9188            assert!(
9189                error.to_string().contains(expected),
9190                "{corruption}: {error}"
9191            );
9192            let cleanup = index.retry_projection_cleanup(SearchProjectionCleanupOptions::default());
9193            assert!(cleanup.retry_required, "{corruption}");
9194            assert!(cleanup.generation_discovery_failures > 0, "{corruption}");
9195            assert!(path.join(mutation_run::artifact_file(2)).is_file());
9196            fs::remove_dir_all(path).unwrap();
9197        }
9198    }
9199
9200    #[test]
9201    #[cfg(feature = "full-text-search")]
9202    fn out_of_core_mutation_retraction_binds_same_id_to_exact_content_version() {
9203        for target in [0, 1] {
9204            let path = test_dir(&format!("mutation-target-version-{target}"));
9205            let old = document(0, "team");
9206            let mut replacement = old.clone();
9207            replacement.content = "a different replacement version".into();
9208            publish_two_artifact_manifest(&path, old.clone(), replacement);
9209            install_delete_mutation_run(&path, &old, target, 3);
9210            let result = load_artifact_closure(
9211                &path,
9212                &SearchOutOfCoreConfig::default(),
9213                &SearchAnalyzerLexicon::default(),
9214                SearchLexicalTermPolicy::default(),
9215                SearchLexicalSourcePolicy::default(),
9216            );
9217            if target == 0 {
9218                assert_eq!(result.unwrap().0.document_count, 1);
9219            } else {
9220                let error = result.unwrap_err();
9221                assert!(
9222                    error
9223                        .to_string()
9224                        .contains("retraction does not match its target document"),
9225                    "{error}"
9226                );
9227            }
9228            fs::remove_dir_all(path).unwrap();
9229        }
9230    }
9231
9232    #[test]
9233    fn out_of_core_mutation_retraction_uses_weighted_analyzer_contributions() {
9234        for stopwords in [false, true] {
9235            let path = test_dir(&format!("mutation-analyzer-contribution-{stopwords}"));
9236            let analyzer = if stopwords {
9237                SearchAnalyzerLexicon::empty().with_stopwords(["memory"])
9238            } else {
9239                SearchAnalyzerLexicon::empty()
9240            };
9241            let document = SearchDocument {
9242                id: "memory:contribution".into(),
9243                title: "graph graph".into(),
9244                content: "memory graph".into(),
9245                embedding: None,
9246                metadata: BTreeMap::new(),
9247            };
9248            let mut writer = SearchOutOfCoreGenerationWriter::create(
9249                &path,
9250                SearchOutOfCoreGenerationBuildOptions {
9251                    analyzer_lexicon: analyzer.clone(),
9252                    ..Default::default()
9253                },
9254            )
9255            .unwrap();
9256            writer.push(document.clone()).unwrap();
9257            writer.finish().unwrap();
9258            let (_, segments, _) = load_artifact_closure(
9259                &path,
9260                &SearchOutOfCoreConfig::default(),
9261                &analyzer,
9262                SearchLexicalTermPolicy::default(),
9263                SearchLexicalSourcePolicy::default(),
9264            )
9265            .unwrap();
9266            let retraction = mutation_run::SearchMutationRetraction::from_document(
9267                &document,
9268                &segments[0].lexical_projection,
9269                &analyzer,
9270            )
9271            .unwrap();
9272            // Title: graph twice plus graph_graph, each weighted by two.
9273            // Body: memory, graph and memory_graph, each weighted by one.
9274            // Removing memory leaves the distinct memory_graph phrase intact.
9275            assert_eq!(
9276                retraction.lexical_document_len,
9277                if stopwords { 8 } else { 9 }
9278            );
9279            assert_eq!(
9280                retraction.unique_terms.to_vec(),
9281                if stopwords {
9282                    vec!["graph", "graph_graph", "memory_graph"]
9283                } else {
9284                    vec!["graph", "graph_graph", "memory", "memory_graph"]
9285                }
9286            );
9287            assert_eq!(
9288                retraction.documents_digest,
9289                lexical_documents_digest(&BTreeMap::from([(document.id.clone(), document)]))
9290            );
9291            fs::remove_dir_all(path).unwrap();
9292        }
9293    }
9294
9295    #[test]
9296    fn out_of_core_mutation_working_budget_is_enforced_only_for_mutation_closures() {
9297        let path = test_dir("mutation-working-budget");
9298        let document = document(0, "team");
9299        let mut index = SearchIndex::open(&path).unwrap();
9300        index.upsert(document.clone()).unwrap();
9301        index.checkpoint().unwrap();
9302        let config = SearchOutOfCoreConfig {
9303            max_mutation_working_bytes: NonZeroU64::MIN,
9304            ..Default::default()
9305        };
9306        SearchOutOfCoreReader::open_with_config(&path, config.clone()).unwrap();
9307        install_delete_mutation_run(&path, &document, 0, 2);
9308        let error = SearchOutOfCoreReader::open_with_config(&path, config).unwrap_err();
9309        assert!(
9310            matches!(&error, HawDBError::ResourceBudgetExceeded(cause)
9311                if cause.resource == hawdb_core::ResourceBudgetKind::MemoryBytes
9312                    && cause.scope == hawdb_core::ResourceBudgetScope::Operator
9313                    && cause.owner == "search mutation-run reader"
9314                    && cause.budget == 1
9315                    && cause.budget_option == "SearchOutOfCoreConfig.max_mutation_working_bytes"),
9316            "{error}"
9317        );
9318        fs::remove_dir_all(path).unwrap();
9319    }
9320
9321    #[test]
9322    fn out_of_core_mutation_target_validation_uses_reanalysis_budget() {
9323        let path = test_dir("mutation-target-hydration-budget");
9324        let document = document(0, "team");
9325        let mut index = SearchIndex::open(&path).unwrap();
9326        index.upsert(document.clone()).unwrap();
9327        index.checkpoint().unwrap();
9328        install_delete_mutation_run(&path, &document, 0, 2);
9329        SearchOutOfCoreReader::open_with_config(
9330            &path,
9331            SearchOutOfCoreConfig {
9332                max_hydrated_bytes: NonZeroU64::MIN,
9333                ..Default::default()
9334            },
9335        )
9336        .unwrap();
9337        let error = load_artifact_closure(
9338            &path,
9339            &SearchOutOfCoreConfig {
9340                max_reanalysis_working_bytes: NonZeroU64::MIN,
9341                ..SearchOutOfCoreConfig::default()
9342            },
9343            &SearchAnalyzerLexicon::default(),
9344            SearchLexicalTermPolicy::default(),
9345            SearchLexicalSourcePolicy::default(),
9346        )
9347        .unwrap_err();
9348        assert!(error.to_string().contains("memory"), "{error}");
9349        fs::remove_dir_all(path).unwrap();
9350    }
9351
9352    #[test]
9353    fn out_of_core_reader_rejects_mutation_runs_targeting_inactive_segments() {
9354        let path = test_dir("mutation-run-inactive-target");
9355        let document = document(0, "team");
9356        let mut index = SearchIndex::open(&path).unwrap();
9357        index.upsert(document.clone()).unwrap();
9358        index.checkpoint().unwrap();
9359        install_delete_mutation_run(&path, &document, 99, 2);
9360
9361        let error = SearchOutOfCoreReader::open(&path).unwrap_err();
9362        assert!(error
9363            .to_string()
9364            .contains("targets a segment outside the active manifest"));
9365        fs::remove_dir_all(path).unwrap();
9366    }
9367
9368    #[test]
9369    #[cfg(feature = "full-text-search")]
9370    fn published_artifact_generations_track_every_manifest_artifact() {
9371        let path = test_dir("published-artifact-generations");
9372        publish_two_artifact_manifest(&path, document(0, "team"), document(1, "team"));
9373
9374        let generations = published_artifact_generations(&path, &SearchAnalyzerLexicon::default())
9375            .unwrap()
9376            .unwrap();
9377        assert_eq!(generations.active_generation, 2);
9378        assert_eq!(generations.lexical_generations, BTreeSet::from([1, 2]));
9379        assert_eq!(generations.out_of_core_generations, BTreeSet::from([1, 2]));
9380        #[cfg(feature = "vector-search")]
9381        assert_eq!(generations.rabitq_generations, BTreeSet::from([1, 2]));
9382        #[cfg(not(feature = "vector-search"))]
9383        assert!(generations.rabitq_generations.is_empty());
9384
9385        fs::remove_dir_all(path).unwrap();
9386    }
9387
9388    #[test]
9389    #[cfg(feature = "full-text-search")]
9390    fn out_of_core_generation_update_retains_every_ordered_manifest_artifact() {
9391        let path = test_dir("multi-segment-generation-update");
9392        publish_two_artifact_manifest(&path, document(0, "team"), document(1, "team"));
9393        let reader = SearchOutOfCoreReader::open(&path).unwrap();
9394        let appended = crate::SearchProjectionRow {
9395            kind: crate::SearchProjectionKind::Memory,
9396            external_id: "002".to_string(),
9397            title: "added graph document".to_string(),
9398            body: "storage memory document 2".to_string(),
9399            embedding: Some(vec![3.0, 14.0]),
9400            source_id: None,
9401            metadata: BTreeMap::from([("space_id".to_string(), "team".to_string())]),
9402        };
9403        let expected_appended = appended.clone().into_document();
9404        let update = SearchOutOfCoreGenerationWriter::prepare_delta(
9405            &reader,
9406            crate::SearchProjectionDelta {
9407                upserts: vec![appended],
9408                ..Default::default()
9409            },
9410            Default::default(),
9411        )
9412        .unwrap();
9413        assert_eq!(update.delta_report().before_document_count, 2);
9414        assert_eq!(update.delta_report().action, "incremental_segment_append");
9415        assert_eq!(update.source_read_metrics().hydrated_documents, 0);
9416        assert_eq!(update.source_read_metrics().segment_range_reads, 0);
9417        let (_, build, _) = update.finish().unwrap();
9418        assert_eq!(build.document_count, 3);
9419
9420        let reader = SearchOutOfCoreReader::open(&path).unwrap();
9421        assert_eq!(reader.manifest.segments.len(), 3);
9422        assert_eq!(
9423            reader
9424                .hydrate_documents(&[
9425                    "memory:000".to_string(),
9426                    "memory:001".to_string(),
9427                    "memory:002".to_string(),
9428                ])
9429                .unwrap()
9430                .documents,
9431            vec![document(0, "team"), document(1, "team"), expected_appended],
9432        );
9433        fs::remove_dir_all(path).unwrap();
9434    }
9435
9436    #[test]
9437    #[cfg(feature = "full-text-search")]
9438    fn out_of_core_multi_segment_metadata_filter_reads_each_artifact() {
9439        let path = test_dir("multi-segment-metadata-filter");
9440        publish_two_artifact_manifest(&path, document(0, "team"), document(1, "team"));
9441
9442        let reader = SearchOutOfCoreReader::open(&path).unwrap();
9443        let mut filtered = options(10, None);
9444        filtered
9445            .metadata_filters
9446            .insert("space_id".to_string(), "team".to_string());
9447        let output = reader
9448            .search_with_options("graph", None, SearchMode::Text, filtered)
9449            .unwrap();
9450        assert_eq!(output.result.filtered_document_count, 2);
9451        assert_eq!(output.result.total_hits, 2);
9452        assert_eq!(
9453            output
9454                .result
9455                .hits
9456                .iter()
9457                .map(|hit| hit.id.as_str())
9458                .collect::<BTreeSet<_>>(),
9459            BTreeSet::from(["memory:000", "memory:001"]),
9460        );
9461        assert_eq!(
9462            output
9463                .result
9464                .candidate_set
9465                .metadata_predicate_pushdown
9466                .segment_count,
9467            2
9468        );
9469        assert_eq!(output.metrics.candidate_block_reads, 2);
9470        fs::remove_dir_all(path).unwrap();
9471    }
9472
9473    #[test]
9474    #[cfg(all(feature = "full-text-search", feature = "vector-search"))]
9475    fn out_of_core_multi_segment_vector_and_hybrid_query_all_artifacts() {
9476        let path = test_dir("multi-segment-vector");
9477        publish_two_artifact_manifest(&path, document(0, "team"), document(1, "team"));
9478        let reader = SearchOutOfCoreReader::open(&path).unwrap();
9479        let query_embedding = [1.0, 16.0];
9480        let mut filtered = options(10, None);
9481        filtered
9482            .metadata_filters
9483            .insert("space_id".to_string(), "team".to_string());
9484
9485        let vector = reader
9486            .search_with_options(
9487                "",
9488                Some(&query_embedding),
9489                SearchMode::Vector,
9490                filtered.clone(),
9491            )
9492            .unwrap();
9493        assert_eq!(vector.result.filtered_document_count, 2);
9494        assert_eq!(vector.result.total_hits, 2);
9495        assert_eq!(
9496            vector
9497                .result
9498                .hits
9499                .iter()
9500                .map(|hit| hit.id.as_str())
9501                .collect::<BTreeSet<_>>(),
9502            BTreeSet::from(["memory:000", "memory:001"]),
9503        );
9504        assert_eq!(vector.metrics.candidate_block_reads, 2);
9505        assert!(vector.metrics.vector_segment_bytes_read > 0);
9506
9507        let limited = reader
9508            .search_with_options("", Some(&[16.0, 1.0]), SearchMode::Vector, options(1, None))
9509            .unwrap();
9510        assert_eq!(limited.result.total_hits, 2);
9511        assert_eq!(limited.result.hits.len(), 1);
9512        assert_eq!(limited.result.hits[0].id, "memory:001");
9513
9514        let hybrid = reader
9515            .search_with_options(
9516                "graph",
9517                Some(&query_embedding),
9518                SearchMode::Hybrid,
9519                filtered.clone(),
9520            )
9521            .unwrap();
9522        assert_eq!(hybrid.result.filtered_document_count, 2);
9523        assert_eq!(hybrid.result.total_hits, 2);
9524        assert!(hybrid.metrics.vector_segment_bytes_read > 0);
9525
9526        let preferred = reader
9527            .search_with_options_compressed_vector_projection_mode(
9528                "",
9529                Some(&query_embedding),
9530                SearchMode::Vector,
9531                filtered.clone(),
9532                CompressedVectorSearchMode::Preferred,
9533            )
9534            .unwrap();
9535        assert_eq!(preferred.result.total_hits, 2);
9536        assert_eq!(
9537            preferred.result.retrievers[0].backend,
9538            "hawdb_rabitq_out_of_core_candidate_projection"
9539        );
9540        assert!(!preferred
9541            .result
9542            .fallback_reason_codes
9543            .contains(&SearchFallbackReasonCode::CompressedVectorProjectionUnavailable));
9544        assert_eq!(preferred.metrics.candidate_block_reads, 2);
9545        assert!(preferred.metrics.rabitq_payload_bytes_read > 0);
9546        let required = reader
9547            .search_with_options_compressed_vector_projection_mode(
9548                "",
9549                Some(&query_embedding),
9550                SearchMode::Vector,
9551                filtered,
9552                CompressedVectorSearchMode::Required,
9553            )
9554            .unwrap();
9555        assert_eq!(required.result.total_hits, 2);
9556        assert_eq!(
9557            required
9558                .result
9559                .hits
9560                .iter()
9561                .map(|hit| hit.id.as_str())
9562                .collect::<BTreeSet<_>>(),
9563            BTreeSet::from(["memory:000", "memory:001"]),
9564        );
9565        assert_eq!(required.metrics.candidate_block_reads, 2);
9566        assert!(required.metrics.rabitq_payload_bytes_read > 0);
9567
9568        let limited_config = SearchOutOfCoreConfig {
9569            max_vector_candidates: std::num::NonZeroUsize::new(1).unwrap(),
9570            ..SearchOutOfCoreConfig::default()
9571        };
9572        let limited_reader =
9573            SearchOutOfCoreReader::open_with_config(&path, limited_config).unwrap();
9574        let limited = limited_reader
9575            .search_with_options_compressed_vector_projection_mode(
9576                "",
9577                Some(&[16.0, 1.0]),
9578                SearchMode::Vector,
9579                options(1, None),
9580                CompressedVectorSearchMode::Required,
9581            )
9582            .unwrap();
9583        assert_eq!(limited.result.total_hits, 1);
9584        assert_eq!(limited.result.hits.len(), 1);
9585        fs::remove_dir_all(path).unwrap();
9586    }
9587
9588    #[test]
9589    #[cfg(all(feature = "full-text-search", feature = "vector-search"))]
9590    fn out_of_core_multi_segment_rabitq_rejects_mixed_quantization() {
9591        let path = test_dir("multi-segment-rabitq-mixed-quantization");
9592        publish_two_artifact_manifest_with_options(
9593            &path,
9594            document(0, "team"),
9595            SearchOutOfCoreGenerationBuildOptions {
9596                rabitq_transform_seed: 1,
9597                ..Default::default()
9598            },
9599            document(1, "team"),
9600            SearchOutOfCoreGenerationBuildOptions {
9601                rabitq_transform_seed: 2,
9602                ..Default::default()
9603            },
9604        );
9605        let reader = SearchOutOfCoreReader::open(&path).unwrap();
9606        let error = reader
9607            .search_with_options_compressed_vector_projection_mode(
9608                "",
9609                Some(&[1.0, 16.0]),
9610                SearchMode::Vector,
9611                options(1, None),
9612                CompressedVectorSearchMode::Required,
9613            )
9614            .unwrap_err();
9615        assert!(error.to_string().contains("matching backend parameters"));
9616        fs::remove_dir_all(path).unwrap();
9617    }
9618
9619    #[test]
9620    #[cfg(all(feature = "full-text-search", feature = "vector-search"))]
9621    fn out_of_core_sidecar_corruption_fails_closed_in_the_consuming_stage() {
9622        let metadata_path = test_dir("metadata-corruption");
9623        let mut metadata_index = SearchIndex::open(&metadata_path).unwrap();
9624        metadata_index.upsert(document(0, "team")).unwrap();
9625        metadata_index.checkpoint().unwrap();
9626        let metadata_reader = SearchOutOfCoreReader::open(&metadata_path).unwrap();
9627        corrupt_first_byte(
9628            &metadata_path.join(
9629                &metadata_reader
9630                    .manifest
9631                    .segments
9632                    .first()
9633                    .expect("manifest has a segment")
9634                    .metadata_payload_file,
9635            ),
9636        );
9637        let mut filtered = options(0, None);
9638        filtered
9639            .metadata_filters
9640            .insert("document_id".to_string(), "memory:000".to_string());
9641        let error = metadata_reader
9642            .search_with_options("graph", None, SearchMode::Text, filtered)
9643            .unwrap_err();
9644        assert!(error
9645            .to_string()
9646            .contains("metadata payload checksum mismatch"));
9647        fs::remove_dir_all(metadata_path).unwrap();
9648
9649        let vector_path = test_dir("vector-corruption");
9650        let mut vector_index = SearchIndex::open(&vector_path).unwrap();
9651        vector_index.upsert(document(0, "team")).unwrap();
9652        vector_index.checkpoint().unwrap();
9653        let vector_reader = SearchOutOfCoreReader::open(&vector_path).unwrap();
9654        corrupt_first_byte(
9655            &vector_path.join(
9656                &vector_reader
9657                    .manifest
9658                    .segments
9659                    .first()
9660                    .expect("manifest has a segment")
9661                    .vector_payload_file,
9662            ),
9663        );
9664        let error = vector_reader
9665            .search_with_options("", Some(&[1.0, 0.5]), SearchMode::Vector, options(0, None))
9666            .unwrap_err();
9667        // Binary sidecars verify the head checksum-covered bytes they read.
9668        assert!(error
9669            .to_string()
9670            .contains("vector sidecar has an invalid header"));
9671        fs::remove_dir_all(vector_path).unwrap();
9672    }
9673
9674    #[test]
9675    fn out_of_core_reader_pins_immutable_generation_across_checkpoint() {
9676        let path = test_dir("generation");
9677        let mut index = SearchIndex::open(&path).unwrap();
9678        index.upsert(document(0, "team")).unwrap();
9679        index.checkpoint().unwrap();
9680        let old_reader = SearchOutOfCoreReader::open(&path).unwrap();
9681
9682        index.upsert(document(1, "team")).unwrap();
9683        index.checkpoint().unwrap();
9684        let new_reader = SearchOutOfCoreReader::open(&path).unwrap();
9685        assert_eq!(old_reader.document_count(), 1);
9686        assert_eq!(new_reader.document_count(), 2);
9687        assert_eq!(
9688            old_reader
9689                .hydrate_documents(&[document(0, "team").id])
9690                .unwrap()
9691                .documents,
9692            vec![document(0, "team")]
9693        );
9694        assert!(old_reader
9695            .hydrate_documents(&[document(1, "team").id])
9696            .is_err());
9697        assert_eq!(
9698            new_reader
9699                .hydrate_documents(&[document(1, "team").id])
9700                .unwrap()
9701                .documents,
9702            vec![document(1, "team")]
9703        );
9704        #[cfg(feature = "full-text-search")]
9705        {
9706            let old = old_reader
9707                .search_with_options("graph", None, SearchMode::Text, options(10, None))
9708                .unwrap();
9709            let new = new_reader
9710                .search_with_options("graph", None, SearchMode::Text, options(10, None))
9711                .unwrap();
9712            assert_eq!(old.result.total_hits, 1);
9713            assert_eq!(new.result.total_hits, 2);
9714        }
9715        drop(old_reader);
9716        drop(new_reader);
9717        fs::remove_dir_all(path).unwrap();
9718    }
9719
9720    #[test]
9721    fn out_of_core_reader_survives_generation_retention_cleanup() {
9722        let path = test_dir("generation-retention");
9723        let mut index = SearchIndex::open(&path).unwrap();
9724        index.upsert(document(0, "team")).unwrap();
9725        index.checkpoint().unwrap();
9726        let oldest_reader = SearchOutOfCoreReader::open(&path).unwrap();
9727
9728        index.upsert(document(1, "team")).unwrap();
9729        index.checkpoint().unwrap();
9730        index.upsert(document(2, "team")).unwrap();
9731        index.checkpoint().unwrap();
9732
9733        assert_eq!(oldest_reader.document_count(), 1);
9734        assert_eq!(
9735            oldest_reader
9736                .hydrate_documents(&[document(0, "team").id])
9737                .unwrap()
9738                .documents,
9739            vec![document(0, "team")]
9740        );
9741        assert!(oldest_reader
9742            .hydrate_documents(&[document(2, "team").id])
9743            .is_err());
9744        let newest_reader = SearchOutOfCoreReader::open(&path).unwrap();
9745        assert_eq!(newest_reader.document_count(), 3);
9746        assert_eq!(
9747            newest_reader
9748                .hydrate_documents(&[document(2, "team").id])
9749                .unwrap()
9750                .documents,
9751            vec![document(2, "team")]
9752        );
9753        drop(newest_reader);
9754        #[cfg(feature = "full-text-search")]
9755        {
9756            let oldest = oldest_reader
9757                .search_with_options("graph", None, SearchMode::Text, options(10, None))
9758                .unwrap();
9759            let newest = SearchOutOfCoreReader::open(&path)
9760                .unwrap()
9761                .search_with_options("graph", None, SearchMode::Text, options(10, None))
9762                .unwrap();
9763            assert_eq!(oldest.result.total_hits, 1);
9764            assert_eq!(newest.result.total_hits, 3);
9765        }
9766        drop(oldest_reader);
9767        let cleanup = index.retry_projection_cleanup(SearchProjectionCleanupOptions::default());
9768        assert!(!cleanup.retry_required, "{cleanup:?}");
9769        fs::remove_dir_all(path).unwrap();
9770    }
9771
9772    #[test]
9773    #[cfg(feature = "full-text-search")]
9774    fn out_of_core_large_payload_only_retains_one_segment_and_final_page() {
9775        let path = test_dir("large-payload");
9776        let mut index = SearchIndex::open(&path).unwrap();
9777        let content = format!("graph {}", "x ".repeat(64 * 1024));
9778        for number in 0..8 {
9779            let mut document = document(number, "team");
9780            document.content = content.clone();
9781            index.upsert(document).unwrap();
9782        }
9783        index.checkpoint().unwrap();
9784        let reader = SearchOutOfCoreReader::open(&path).unwrap();
9785        let output = reader
9786            .search_with_options("graph", None, SearchMode::Text, options(1, None))
9787            .unwrap();
9788        assert_eq!(reader.resident_document_count(), 0);
9789        assert_eq!(output.metrics.hydrated_documents, 1);
9790        assert!(output.metrics.hydrated_bytes < 256 * 1024);
9791        assert!(output.metrics.peak_segment_document_bytes < 512 * 1024);
9792        fs::remove_dir_all(path).unwrap();
9793    }
9794
9795    #[test]
9796    #[cfg(feature = "full-text-search")]
9797    fn nowledge_out_of_core_facade_uses_the_bounded_reader() {
9798        let path = test_dir("nowledge-facade");
9799        let mut index = SearchIndex::open(&path).unwrap();
9800        index.upsert(document(0, "team")).unwrap();
9801        index.checkpoint().unwrap();
9802        let projection = SearchOutOfCoreReader::open(&path).unwrap();
9803        let output = projection
9804            .search_with_options("graph", None, SearchMode::Text, options(1, None))
9805            .unwrap();
9806        assert_eq!(output.result.hits[0].id, "memory:000");
9807        assert_eq!(output.metrics.hydrated_documents, 1);
9808        assert_eq!(projection.resident_document_count(), 0);
9809        fs::remove_dir_all(path).unwrap();
9810    }
9811
9812    #[test]
9813    fn production_facade_rejects_unqualified_or_stale_lexical_evidence() {
9814        let path = test_dir("nowledge-production-qualification");
9815        let mut index = SearchIndex::open(&path).unwrap();
9816        index.upsert(document(0, "team")).unwrap();
9817        index.checkpoint().unwrap();
9818        let qualification = SearchLexicalProductionQualificationReport::evaluate(
9819            999,
9820            Some(999),
9821            100_000,
9822            true,
9823            SearchLexicalFeasibilityCoverage::default(),
9824            SearchLexicalFeasibilityMetrics::default(),
9825        );
9826
9827        let projection = SearchOutOfCoreReader::open(&path).unwrap();
9828        let error = qualification
9829            .validate_for_projection_and_release(
9830                &projection.production_qualification_identity(),
9831                &production_identity(),
9832            )
9833            .unwrap_err();
9834        assert!(error.to_string().contains("projection_identity_mismatch"));
9835        assert!(error.to_string().contains("workload_coverage_incomplete"));
9836        // Not storage damage: the reader opened and verified its files (#1932).
9837        assert!(matches!(
9838            error,
9839            HawDBError::SearchProductionQualificationRefused { .. }
9840        ));
9841        fs::remove_dir_all(path).unwrap();
9842    }
9843
9844    #[cfg(all(feature = "full-text-search", feature = "vector-search"))]
9845    fn corrupt_first_byte(path: &Path) {
9846        let mut file = OpenOptions::new()
9847            .read(true)
9848            .write(true)
9849            .open(path)
9850            .unwrap();
9851        file.seek(SeekFrom::Start(0)).unwrap();
9852        file.write_all(b"X").unwrap();
9853        file.sync_all().unwrap();
9854    }
9855}