Skip to main content

hermes_core/segment/builder/
mod.rs

1//! Streaming segment builder with optimized memory usage
2//!
3//! Key optimizations:
4//! - **String interning**: Terms are interned using `lasso` to avoid repeated allocations
5//! - **hashbrown HashMap**: O(1) average insertion instead of BTreeMap's O(log n)
6//! - **Streaming document store**: Documents written to disk immediately
7//! - **Zero-copy store build**: Pre-serialized doc bytes passed directly to compressor
8//! - **Parallel posting serialization**: Rayon parallel sort + serialize
9//! - **Inline posting fast path**: Small terms skip PostingList/BlockPostingList entirely
10
11#[cfg_attr(not(feature = "native"), allow(dead_code))]
12pub(crate) mod bmp;
13mod config;
14mod dense;
15#[cfg(feature = "diagnostics")]
16mod diagnostics;
17#[cfg_attr(not(feature = "native"), allow(dead_code))]
18pub(crate) mod graph_bisection;
19pub use graph_bisection::BpBudget;
20mod postings;
21mod sparse;
22mod store;
23
24pub use config::{MemoryBreakdown, SegmentBuilderConfig, SegmentBuilderStats};
25
26#[cfg(feature = "native")]
27use std::fs::{File, OpenOptions};
28#[cfg(feature = "native")]
29use std::io::BufWriter;
30use std::io::Write;
31use std::mem::size_of;
32#[cfg(feature = "native")]
33use std::path::PathBuf;
34
35use hashbrown::HashMap;
36use rustc_hash::FxHashMap;
37
38// String interning: lasso on native (fast arena), HashMap on WASM (no C deps)
39#[cfg(feature = "native")]
40use lasso::{Rodeo, Spur};
41
42#[cfg(not(feature = "native"))]
43pub(crate) mod simple_interner {
44    use hashbrown::HashMap;
45
46    #[derive(Clone, Copy, PartialEq, Eq, Hash)]
47    pub struct Spur(u32);
48
49    /// Simple string interner for WASM (replaces lasso::Rodeo).
50    /// Stores each string once in a Vec; HashMap maps &str → index.
51    pub struct Rodeo {
52        /// Canonical storage — each string lives here exactly once.
53        strings: Vec<Box<str>>,
54        /// Maps borrowed string slices (pointing into `strings`) to their index.
55        /// Safety: entries are never removed and Box<str> has a stable address.
56        map: HashMap<&'static str, u32>,
57    }
58
59    impl Rodeo {
60        pub fn new() -> Self {
61            Self {
62                strings: Vec::new(),
63                map: HashMap::new(),
64            }
65        }
66
67        pub fn get(&self, key: &str) -> Option<Spur> {
68            self.map.get(key).map(|&id| Spur(id))
69        }
70
71        pub fn get_or_intern(&mut self, key: &str) -> Spur {
72            if let Some(&id) = self.map.get(key) {
73                return Spur(id);
74            }
75            let id = self.strings.len() as u32;
76            let boxed: Box<str> = key.into();
77            // Safety: the Box<str> is stored in self.strings (append-only Vec)
78            // and never moved or freed while the Rodeo is alive.
79            let static_ref: &'static str = unsafe { &*(boxed.as_ref() as *const str) };
80            self.strings.push(boxed);
81            self.map.insert(static_ref, id);
82            Spur(id)
83        }
84
85        pub fn resolve(&self, spur: &Spur) -> &str {
86            &self.strings[spur.0 as usize]
87        }
88
89        pub fn len(&self) -> usize {
90            self.strings.len()
91        }
92    }
93}
94
95#[cfg(not(feature = "native"))]
96use simple_interner::{Rodeo, Spur};
97
98use super::types::{FieldStats, SegmentFiles, SegmentId, SegmentMeta};
99use std::sync::Arc;
100
101use crate::directories::{Directory, DirectoryWriter};
102use crate::dsl::{Document, Field, FieldType, FieldValue, Schema};
103use crate::tokenizer::BoxedTokenizer;
104use crate::{DocId, Result};
105
106use dense::{BinaryDenseVectorBuilder, DenseVectorBuilder};
107use postings::{CompactPosting, PositionPostingListBuilder, PostingListBuilder, TermKey};
108use sparse::SparseVectorBuilder;
109
110/// Size of the document store buffer before writing to disk
111const STORE_BUFFER_SIZE: usize = 16 * 1024 * 1024; // 16MB
112
113/// Memory overhead per new term in the inverted index:
114/// HashMap entry control byte + padding + TermKey + PostingListBuilder + Vec header
115const NEW_TERM_OVERHEAD: usize = size_of::<TermKey>() + size_of::<PostingListBuilder>() + 24;
116
117/// Memory overhead per newly interned string: Spur + arena pointers (2 × usize)
118const INTERN_OVERHEAD: usize = size_of::<Spur>() + 2 * size_of::<usize>();
119
120/// Memory overhead per new term in the position index
121const NEW_POS_TERM_OVERHEAD: usize =
122    size_of::<TermKey>() + size_of::<PositionPostingListBuilder>() + 24;
123
124/// Packed position encoding is `(element_ordinal << 20) | token_position`:
125/// 12 bits of element ordinal, 20 bits of token position. Values beyond these
126/// maxima must saturate — a plain shift/or silently corrupts the neighboring
127/// bit field (ordinal 4096 wraps to 0 and aliases element 0; token positions
128/// >= 2^20 bleed into the ordinal bits).
129const MAX_POSITION_ELEMENT_ORDINAL: u32 = (1 << 12) - 1;
130const MAX_TOKEN_POSITION: u32 = (1 << 20) - 1;
131
132/// Default BMP vocabulary size when `dims` is unset in the sparse vector
133/// config (SPLADE unigram vocabulary). Must match the build-time defaults in
134/// `builder/sparse.rs` and `merger/sparse.rs`.
135const DEFAULT_BMP_SPARSE_DIMS: u32 = 105879;
136
137/// Human-readable name of a schema field type (matches the SDL/serde names).
138fn field_type_name(field_type: &FieldType) -> &'static str {
139    match field_type {
140        FieldType::Text => "text",
141        FieldType::U64 => "u64",
142        FieldType::I64 => "i64",
143        FieldType::F64 => "f64",
144        FieldType::Bytes => "bytes",
145        FieldType::SparseVector => "sparse_vector",
146        FieldType::DenseVector => "dense_vector",
147        FieldType::Json => "json",
148        FieldType::BinaryDenseVector => "binary_dense_vector",
149    }
150}
151
152/// Human-readable name of a document field value's type (matches SDL names).
153fn field_value_type_name(value: &FieldValue) -> &'static str {
154    match value {
155        FieldValue::Text(_) => "text",
156        FieldValue::U64(_) => "u64",
157        FieldValue::I64(_) => "i64",
158        FieldValue::F64(_) => "f64",
159        FieldValue::Bytes(_) => "bytes",
160        FieldValue::SparseVector(_) => "sparse_vector",
161        FieldValue::DenseVector(_) => "dense_vector",
162        FieldValue::Json(_) => "json",
163        FieldValue::BinaryDenseVector(_) => "binary_dense_vector",
164    }
165}
166
167/// Segment builder with optimized memory usage
168///
169/// Features:
170/// - Streams documents to disk immediately (no in-memory document storage)
171/// - Uses string interning for terms (reduced allocations)
172/// - Uses hashbrown HashMap (faster than BTreeMap)
173pub struct SegmentBuilder {
174    schema: Arc<Schema>,
175    config: SegmentBuilderConfig,
176    tokenizers: FxHashMap<Field, BoxedTokenizer>,
177
178    /// String interner for terms - O(1) lookup and deduplication
179    term_interner: Rodeo,
180
181    /// Inverted index: term key -> posting list
182    inverted_index: HashMap<TermKey, PostingListBuilder>,
183
184    /// Spill file for high-frequency posting lists (lazily created on first spill).
185    #[cfg(feature = "native")]
186    posting_spill_file: Option<BufWriter<File>>,
187    #[cfg(feature = "native")]
188    posting_spill_path: PathBuf,
189    /// Tracks spilled ranges per term key: (file_offset, posting_count).
190    #[cfg(feature = "native")]
191    posting_spill_index: HashMap<TermKey, Vec<(u64, u32)>>,
192    #[cfg(feature = "native")]
193    posting_spill_offset: u64,
194
195    /// Streaming document store writer (native: temp file on disk, WASM: in-memory buffer)
196    #[cfg(feature = "native")]
197    store_file: BufWriter<File>,
198    #[cfg(feature = "native")]
199    store_path: PathBuf,
200    #[cfg(not(feature = "native"))]
201    store_buffer: Vec<u8>,
202
203    /// Document count
204    next_doc_id: DocId,
205
206    /// Per-field statistics for BM25F
207    field_stats: FxHashMap<u32, FieldStats>,
208
209    /// Per-document field lengths stored compactly
210    /// Uses a flat Vec instead of Vec<HashMap> for better cache locality
211    /// Layout: [doc0_field0_len, doc0_field1_len, ..., doc1_field0_len, ...]
212    doc_field_lengths: Vec<u32>,
213    num_indexed_fields: usize,
214    field_to_slot: FxHashMap<u32, usize>,
215
216    /// Reusable buffer for per-document term frequency aggregation
217    /// Avoids allocating a new hashmap for each document
218    local_tf_buffer: FxHashMap<Spur, u32>,
219
220    /// Reusable buffer for per-document position tracking (when positions enabled)
221    /// Avoids allocating a new hashmap for each text field per document
222    local_positions: FxHashMap<Spur, Vec<u32>>,
223
224    /// Reusable buffer for tokenization to avoid per-token String allocations
225    token_buffer: String,
226
227    /// Reusable buffer for numeric field term encoding (avoids format!() alloc per call)
228    numeric_buffer: String,
229
230    /// Dense vector storage per field: field -> (doc_ids, vectors)
231    /// Vectors are stored as flat f32 arrays for efficient RaBitQ indexing
232    dense_vectors: FxHashMap<u32, DenseVectorBuilder>,
233
234    /// Binary dense vector storage per field: field -> packed-bit vectors
235    binary_dense_vectors: FxHashMap<u32, BinaryDenseVectorBuilder>,
236
237    /// Sparse vector storage per field: field -> SparseVectorBuilder
238    /// Uses proper BlockSparsePostingList with configurable quantization
239    sparse_vectors: FxHashMap<u32, SparseVectorBuilder>,
240
241    /// Position index for fields with positions enabled
242    /// term key -> position posting list
243    position_index: HashMap<TermKey, PositionPostingListBuilder>,
244
245    /// Fields that have position tracking enabled, with their mode
246    position_enabled_fields: FxHashMap<u32, Option<crate::dsl::PositionMode>>,
247
248    /// Current element ordinal for multi-valued fields (reset per document)
249    current_element_ordinal: FxHashMap<u32, u32>,
250
251    /// Whether the once-per-segment position-encoding saturation warning
252    /// has already been emitted (see MAX_POSITION_ELEMENT_ORDINAL).
253    position_saturation_warned: bool,
254
255    /// Incrementally tracked memory estimate (avoids expensive stats() calls)
256    estimated_memory: usize,
257
258    /// Reusable buffer for document serialization (avoids per-document allocation)
259    doc_serialize_buffer: Vec<u8>,
260
261    /// Fast-field columnar writers per field_id (only for fields with fast=true)
262    fast_fields: FxHashMap<u32, crate::structures::fast_field::FastFieldWriter>,
263}
264
265impl SegmentBuilder {
266    /// Create a new segment builder
267    pub fn new(schema: Arc<Schema>, config: SegmentBuilderConfig) -> Result<Self> {
268        #[cfg(feature = "native")]
269        let (store_file, store_path, spill_path) = {
270            let segment_id = uuid::Uuid::new_v4();
271            let store_path = config
272                .temp_dir
273                .join(format!("hermes_store_{}.tmp", segment_id));
274            let store_file = BufWriter::with_capacity(
275                STORE_BUFFER_SIZE,
276                OpenOptions::new()
277                    .create(true)
278                    .write(true)
279                    .truncate(true)
280                    .open(&store_path)?,
281            );
282            let spill_path = config
283                .temp_dir
284                .join(format!("hermes_spill_{}.tmp", segment_id));
285            (store_file, store_path, spill_path)
286        };
287
288        // Count indexed fields, track positions, and auto-configure tokenizers
289        let registry = crate::tokenizer::TokenizerRegistry::new();
290        let mut num_indexed_fields = 0;
291        let mut field_to_slot = FxHashMap::default();
292        let mut position_enabled_fields = FxHashMap::default();
293        let mut tokenizers = FxHashMap::default();
294        for (field, entry) in schema.fields() {
295            if entry.indexed && matches!(entry.field_type, FieldType::Text) {
296                field_to_slot.insert(field.0, num_indexed_fields);
297                num_indexed_fields += 1;
298                if entry.positions.is_some() {
299                    position_enabled_fields.insert(field.0, entry.positions);
300                }
301                if let Some(ref tok_name) = entry.tokenizer
302                    && let Some(tokenizer) = registry.get(tok_name)
303                {
304                    tokenizers.insert(field, tokenizer);
305                }
306            }
307        }
308
309        // Initialize fast-field writers for fields with fast=true
310        use crate::structures::fast_field::{FastFieldColumnType, FastFieldWriter};
311        let mut fast_fields = FxHashMap::default();
312        for (field, entry) in schema.fields() {
313            if entry.fast {
314                let writer = if entry.multi {
315                    match entry.field_type {
316                        FieldType::U64 => {
317                            FastFieldWriter::new_numeric_multi(FastFieldColumnType::U64)
318                        }
319                        FieldType::I64 => {
320                            FastFieldWriter::new_numeric_multi(FastFieldColumnType::I64)
321                        }
322                        FieldType::F64 => {
323                            FastFieldWriter::new_numeric_multi(FastFieldColumnType::F64)
324                        }
325                        FieldType::Text => FastFieldWriter::new_text_multi(),
326                        _ => continue,
327                    }
328                } else {
329                    match entry.field_type {
330                        FieldType::U64 => FastFieldWriter::new_numeric(FastFieldColumnType::U64),
331                        FieldType::I64 => FastFieldWriter::new_numeric(FastFieldColumnType::I64),
332                        FieldType::F64 => FastFieldWriter::new_numeric(FastFieldColumnType::F64),
333                        FieldType::Text => FastFieldWriter::new_text(),
334                        _ => continue,
335                    }
336                };
337                fast_fields.insert(field.0, writer);
338            }
339        }
340
341        Ok(Self {
342            schema,
343            tokenizers,
344            term_interner: Rodeo::new(),
345            inverted_index: HashMap::with_capacity(config.posting_map_capacity),
346            #[cfg(feature = "native")]
347            posting_spill_file: None,
348            #[cfg(feature = "native")]
349            posting_spill_path: spill_path,
350            #[cfg(feature = "native")]
351            posting_spill_index: HashMap::new(),
352            #[cfg(feature = "native")]
353            posting_spill_offset: 0,
354            #[cfg(feature = "native")]
355            store_file,
356            #[cfg(feature = "native")]
357            store_path,
358            #[cfg(not(feature = "native"))]
359            store_buffer: Vec::with_capacity(STORE_BUFFER_SIZE),
360            next_doc_id: 0,
361            field_stats: FxHashMap::default(),
362            doc_field_lengths: Vec::new(),
363            num_indexed_fields,
364            field_to_slot,
365            local_tf_buffer: FxHashMap::default(),
366            local_positions: FxHashMap::default(),
367            token_buffer: String::with_capacity(64),
368            numeric_buffer: String::with_capacity(32),
369            config,
370            dense_vectors: FxHashMap::default(),
371            binary_dense_vectors: FxHashMap::default(),
372            sparse_vectors: FxHashMap::default(),
373            position_index: HashMap::new(),
374            position_enabled_fields,
375            current_element_ordinal: FxHashMap::default(),
376            position_saturation_warned: false,
377            estimated_memory: 0,
378            doc_serialize_buffer: Vec::with_capacity(256),
379            fast_fields,
380        })
381    }
382
383    pub fn set_tokenizer(&mut self, field: Field, tokenizer: BoxedTokenizer) {
384        self.tokenizers.insert(field, tokenizer);
385    }
386
387    /// Get the current element ordinal for a field and increment it.
388    /// Used for multi-valued fields (text, dense_vector, sparse_vector).
389    fn next_element_ordinal(&mut self, field_id: u32) -> u32 {
390        let ordinal = *self.current_element_ordinal.get(&field_id).unwrap_or(&0);
391        *self.current_element_ordinal.entry(field_id).or_insert(0) += 1;
392        ordinal
393    }
394
395    fn next_vector_ordinal(&mut self, field_id: u32) -> Result<u16> {
396        let ordinal = self.next_element_ordinal(field_id);
397        u16::try_from(ordinal).map_err(|_| {
398            crate::Error::Document(format!(
399                "field {field_id} has more than {} vector values in one document",
400                u16::MAX as usize + 1
401            ))
402        })
403    }
404
405    pub fn num_docs(&self) -> u32 {
406        self.next_doc_id
407    }
408
409    /// Fast O(1) memory estimate - updated incrementally during indexing
410    #[inline]
411    pub fn estimated_memory_bytes(&self) -> usize {
412        self.estimated_memory
413    }
414
415    /// Count total unique sparse dimensions across all fields
416    pub fn sparse_dim_count(&self) -> usize {
417        self.sparse_vectors.values().map(|b| b.postings.len()).sum()
418    }
419
420    /// Get current statistics for debugging performance (expensive - iterates all data)
421    pub fn stats(&self) -> SegmentBuilderStats {
422        use std::mem::size_of;
423
424        let postings_in_memory: usize =
425            self.inverted_index.values().map(|p| p.postings.len()).sum();
426
427        // Size constants computed from actual types
428        let compact_posting_size = size_of::<CompactPosting>();
429        let vec_overhead = size_of::<Vec<u8>>(); // Vec header: ptr + len + cap = 24 bytes on 64-bit
430        let term_key_size = size_of::<TermKey>();
431        let posting_builder_size = size_of::<PostingListBuilder>();
432        let spur_size = size_of::<Spur>();
433        let sparse_entry_size = size_of::<(DocId, u16, f32)>();
434
435        // hashbrown HashMap entry overhead: key + value + 1 byte control + padding
436        // Measured: ~(key_size + value_size + 8) per entry on average
437        let hashmap_entry_base_overhead = 8usize;
438
439        // FxHashMap uses same layout as hashbrown
440        let fxhashmap_entry_overhead = hashmap_entry_base_overhead;
441
442        // Postings memory
443        let postings_bytes: usize = self
444            .inverted_index
445            .values()
446            .map(|p| p.postings.capacity() * compact_posting_size + vec_overhead)
447            .sum();
448
449        // Inverted index overhead
450        let index_overhead_bytes = self.inverted_index.len()
451            * (term_key_size + posting_builder_size + hashmap_entry_base_overhead);
452
453        // Term interner: Rodeo stores strings + metadata
454        // Rodeo internal: string bytes + Spur + arena overhead (~2 pointers per string)
455        let interner_arena_overhead = 2 * size_of::<usize>();
456        let avg_term_len = 8; // Estimated average term length
457        let interner_bytes =
458            self.term_interner.len() * (avg_term_len + spur_size + interner_arena_overhead);
459
460        // Doc field lengths
461        let field_lengths_bytes =
462            self.doc_field_lengths.capacity() * size_of::<u32>() + vec_overhead;
463
464        // Dense vectors
465        let mut dense_vectors_bytes: usize = 0;
466        let mut dense_vector_count: usize = 0;
467        let doc_id_ordinal_size = size_of::<(DocId, u16)>();
468        for b in self.dense_vectors.values() {
469            dense_vectors_bytes += b.vectors.capacity() * size_of::<f32>()
470                + b.doc_ids.capacity() * doc_id_ordinal_size
471                + 2 * vec_overhead; // Two Vecs
472            dense_vector_count += b.doc_ids.len();
473        }
474        // Binary dense vectors
475        for b in self.binary_dense_vectors.values() {
476            dense_vectors_bytes += b.vectors.capacity()
477                + b.doc_ids.capacity() * doc_id_ordinal_size
478                + 2 * vec_overhead;
479            dense_vector_count += b.doc_ids.len();
480        }
481
482        // Local buffers
483        let local_tf_entry_size = spur_size + size_of::<u32>() + fxhashmap_entry_overhead;
484        let local_tf_buffer_bytes = self.local_tf_buffer.capacity() * local_tf_entry_size;
485
486        // Sparse vectors
487        let mut sparse_vectors_bytes: usize = 0;
488        for builder in self.sparse_vectors.values() {
489            for postings in builder.postings.values() {
490                sparse_vectors_bytes += postings.capacity() * sparse_entry_size + vec_overhead;
491            }
492            // Inner FxHashMap overhead: u32 key + Vec value ptr + overhead
493            let inner_entry_size = size_of::<u32>() + vec_overhead + fxhashmap_entry_overhead;
494            sparse_vectors_bytes += builder.postings.len() * inner_entry_size;
495        }
496        // Outer FxHashMap overhead
497        let outer_sparse_entry_size =
498            size_of::<u32>() + size_of::<SparseVectorBuilder>() + fxhashmap_entry_overhead;
499        sparse_vectors_bytes += self.sparse_vectors.len() * outer_sparse_entry_size;
500
501        // Position index
502        let mut position_index_bytes: usize = 0;
503        for pos_builder in self.position_index.values() {
504            for (_, positions) in &pos_builder.postings {
505                position_index_bytes += positions.capacity() * size_of::<u32>() + vec_overhead;
506            }
507            // Vec<(DocId, Vec<u32>)> entry size
508            let pos_entry_size = size_of::<DocId>() + vec_overhead;
509            position_index_bytes += pos_builder.postings.capacity() * pos_entry_size;
510        }
511        // HashMap overhead for position_index
512        let pos_index_entry_size =
513            term_key_size + size_of::<PositionPostingListBuilder>() + hashmap_entry_base_overhead;
514        position_index_bytes += self.position_index.len() * pos_index_entry_size;
515
516        let estimated_memory_bytes = postings_bytes
517            + index_overhead_bytes
518            + interner_bytes
519            + field_lengths_bytes
520            + dense_vectors_bytes
521            + local_tf_buffer_bytes
522            + sparse_vectors_bytes
523            + position_index_bytes;
524
525        let memory_breakdown = MemoryBreakdown {
526            postings_bytes,
527            index_overhead_bytes,
528            interner_bytes,
529            field_lengths_bytes,
530            dense_vectors_bytes,
531            dense_vector_count,
532            sparse_vectors_bytes,
533            position_index_bytes,
534        };
535
536        SegmentBuilderStats {
537            num_docs: self.next_doc_id,
538            unique_terms: self.inverted_index.len(),
539            postings_in_memory,
540            interned_strings: self.term_interner.len(),
541            doc_field_lengths_size: self.doc_field_lengths.len(),
542            estimated_memory_bytes,
543            memory_breakdown,
544        }
545    }
546
547    /// Fail-loud pre-validation of a document's field values against the
548    /// schema. Runs BEFORE any builder state is mutated, so a rejected
549    /// document never poisons the builder (doc id advanced, postings written,
550    /// store write skipped).
551    ///
552    /// - A value whose runtime type does not match the schema field type
553    ///   would previously fall through `add_document`'s match silently: the
554    ///   value was stored but never indexed, so queries on the field could
555    ///   never match the document. Reject it loudly instead.
556    /// - Sparse entries destined for a BMP-format field must fit the
557    ///   configured `dims`: the block-max grid only has rows for
558    ///   `dim_id < dims`, so out-of-range entries would be silently dropped
559    ///   from the grid and silently filtered from queries — permanently
560    ///   unsearchable.
561    fn validate_document_against_schema(&self, doc: &Document) -> Result<()> {
562        for (field, value) in doc.field_values() {
563            let Some(entry) = self.schema.get_field_entry(*field) else {
564                continue;
565            };
566
567            // Mirror the indexing skip below: values that are neither indexed
568            // nor fast (and are not vector types) are only stored verbatim.
569            if !matches!(
570                &entry.field_type,
571                FieldType::DenseVector | FieldType::BinaryDenseVector
572            ) && !entry.indexed
573                && !entry.fast
574            {
575                continue;
576            }
577
578            match (&entry.field_type, value) {
579                (FieldType::SparseVector, FieldValue::SparseVector(entries)) => {
580                    if let Some(config) = entry.sparse_vector_config.as_ref()
581                        && config.format == crate::structures::SparseFormat::Bmp
582                    {
583                        let dims = config.dims.unwrap_or(DEFAULT_BMP_SPARSE_DIMS);
584                        if let Some(&(dim_id, _)) =
585                            entries.iter().find(|&&(dim_id, _)| dim_id >= dims)
586                        {
587                            return Err(crate::Error::Schema(format!(
588                                "sparse vector for field '{}' contains dim_id {} out of \
589                                 range for the configured BMP dims={}: dimensions >= dims \
590                                 are never written to the block-max grid and can never \
591                                 match a query; raise `dims` in the field's sparse_vector \
592                                 config or fix the embedding model",
593                                entry.name, dim_id, dims
594                            )));
595                        }
596                    }
597                }
598                // Matching (type, value) pairs — indexed by `add_document`.
599                (FieldType::Text, FieldValue::Text(_))
600                | (FieldType::U64, FieldValue::U64(_))
601                | (FieldType::I64, FieldValue::I64(_))
602                | (FieldType::F64, FieldValue::F64(_))
603                | (FieldType::DenseVector, FieldValue::DenseVector(_))
604                | (FieldType::BinaryDenseVector, FieldValue::BinaryDenseVector(_))
605                // Stored-only types: no indexing support, value stored verbatim.
606                | (FieldType::Bytes, FieldValue::Bytes(_))
607                | (FieldType::Json, FieldValue::Json(_)) => {}
608                (expected, got) => {
609                    return Err(crate::Error::Schema(format!(
610                        "type mismatch for field '{}': schema expects a {} value, got {}; \
611                         the value would be stored but never indexed, so queries on this \
612                         field could never match the document — fix the document or the \
613                         schema",
614                        entry.name,
615                        field_type_name(expected),
616                        field_value_type_name(got),
617                    )));
618                }
619            }
620        }
621        Ok(())
622    }
623
624    /// Add a document - streams to disk immediately
625    pub fn add_document(&mut self, doc: Document) -> Result<DocId> {
626        // Reject schema-mismatched values before mutating any builder state.
627        self.validate_document_against_schema(&doc)?;
628
629        let doc_id = self.next_doc_id;
630        self.next_doc_id += 1;
631
632        // Initialize field lengths for this document
633        let base_idx = self.doc_field_lengths.len();
634        self.doc_field_lengths
635            .resize(base_idx + self.num_indexed_fields, 0);
636        self.estimated_memory += self.num_indexed_fields * std::mem::size_of::<u32>();
637
638        // Reset element ordinals for this document (for multi-valued fields)
639        self.current_element_ordinal.clear();
640
641        for (field, value) in doc.field_values() {
642            let Some(entry) = self.schema.get_field_entry(*field) else {
643                continue;
644            };
645
646            // Dense/binary vectors are written to .vectors when indexed || stored
647            // Other field types require indexed or fast
648            if !matches!(
649                &entry.field_type,
650                FieldType::DenseVector | FieldType::BinaryDenseVector
651            ) && !entry.indexed
652                && !entry.fast
653            {
654                continue;
655            }
656
657            match (&entry.field_type, value) {
658                (FieldType::Text, FieldValue::Text(text)) => {
659                    if entry.indexed {
660                        let element_ordinal = self.next_element_ordinal(field.0);
661                        let token_count =
662                            self.index_text_field(*field, doc_id, text, element_ordinal)?;
663
664                        let stats = self.field_stats.entry(field.0).or_default();
665                        stats.total_tokens += token_count as u64;
666                        if element_ordinal == 0 {
667                            stats.doc_count += 1;
668                        }
669
670                        if let Some(&slot) = self.field_to_slot.get(&field.0) {
671                            self.doc_field_lengths[base_idx + slot] = token_count;
672                        }
673                    }
674
675                    // Fast-field: store raw text for text ordinal column
676                    if let Some(ff) = self.fast_fields.get_mut(&field.0) {
677                        ff.add_text(doc_id, text);
678                    }
679                }
680                (FieldType::U64, FieldValue::U64(v)) => {
681                    if entry.indexed {
682                        self.index_numeric_field(*field, doc_id, *v)?;
683                    }
684                    if let Some(ff) = self.fast_fields.get_mut(&field.0) {
685                        ff.add_u64(doc_id, *v);
686                    }
687                }
688                (FieldType::I64, FieldValue::I64(v)) => {
689                    if entry.indexed {
690                        self.index_numeric_field(*field, doc_id, *v as u64)?;
691                    }
692                    if let Some(ff) = self.fast_fields.get_mut(&field.0) {
693                        ff.add_i64(doc_id, *v);
694                    }
695                }
696                (FieldType::F64, FieldValue::F64(v)) => {
697                    if entry.indexed {
698                        self.index_numeric_field(*field, doc_id, v.to_bits())?;
699                    }
700                    if let Some(ff) = self.fast_fields.get_mut(&field.0) {
701                        ff.add_f64(doc_id, *v);
702                    }
703                }
704                (FieldType::DenseVector, FieldValue::DenseVector(vec))
705                    if entry.indexed || entry.stored =>
706                {
707                    let ordinal = self.next_vector_ordinal(field.0)?;
708                    self.index_dense_vector_field(*field, doc_id, ordinal, vec)?;
709                }
710                (FieldType::BinaryDenseVector, FieldValue::BinaryDenseVector(bytes))
711                    if entry.indexed || entry.stored =>
712                {
713                    let ordinal = self.next_vector_ordinal(field.0)?;
714                    self.index_binary_dense_vector_field(*field, doc_id, ordinal, bytes)?;
715                }
716                (FieldType::SparseVector, FieldValue::SparseVector(entries)) => {
717                    let ordinal = self.next_vector_ordinal(field.0)?;
718                    self.index_sparse_vector_field(*field, doc_id, ordinal, entries)?;
719                }
720                // Only reachable for stored-only types (bytes/json) and for
721                // vector values on fields that are neither indexed nor
722                // stored: type-mismatched values are rejected loudly by
723                // `validate_document_against_schema` before this loop.
724                _ => {}
725            }
726        }
727
728        // Stream document to disk immediately
729        self.write_document_to_store(&doc)?;
730
731        Ok(doc_id)
732    }
733
734    /// Index a text field using interned terms
735    ///
736    /// Uses a custom tokenizer when set for the field (via `set_tokenizer`),
737    /// otherwise falls back to an inline zero-allocation path (split_whitespace
738    /// + lowercase + strip non-alphanumeric).
739    ///
740    /// If position recording is enabled for this field, also records token positions
741    /// encoded as (element_ordinal << 20) | token_position.
742    fn index_text_field(
743        &mut self,
744        field: Field,
745        doc_id: DocId,
746        text: &str,
747        element_ordinal: u32,
748    ) -> Result<u32> {
749        use crate::dsl::PositionMode;
750
751        let field_id = field.0;
752        let position_mode = self
753            .position_enabled_fields
754            .get(&field_id)
755            .copied()
756            .flatten();
757
758        // Saturate the packed 12-bit ordinal field instead of letting the
759        // shift silently wrap (ordinal 4096 << 20 == 0, aliasing element 0).
760        let encoded_ordinal = if position_mode.is_some_and(|m| m.tracks_ordinal())
761            && element_ordinal > MAX_POSITION_ELEMENT_ORDINAL
762        {
763            self.warn_position_saturation(
764                "element ordinal",
765                element_ordinal,
766                MAX_POSITION_ELEMENT_ORDINAL,
767            );
768            MAX_POSITION_ELEMENT_ORDINAL
769        } else {
770            element_ordinal
771        };
772
773        // Phase 1: Aggregate term frequencies within this document
774        // Also collect positions if enabled
775        // Reuse buffers to avoid allocations
776        self.local_tf_buffer.clear();
777        // Clear position Vecs in-place (keeps allocated capacity for reuse)
778        for v in self.local_positions.values_mut() {
779            v.clear();
780        }
781
782        let mut token_position = 0u32;
783
784        // Tokenize: use custom tokenizer if set, else inline zero-alloc path.
785        // The owned Vec<Token> is computed first so the immutable borrow of
786        // self.tokenizers ends before we mutate other fields.
787        let custom_tokens = self.tokenizers.get(&field).map(|t| t.tokenize(text));
788
789        if let Some(tokens) = custom_tokens {
790            // Custom tokenizer path
791            for token in &tokens {
792                let term_spur = if let Some(spur) = self.term_interner.get(&token.text) {
793                    spur
794                } else {
795                    let spur = self.term_interner.get_or_intern(&token.text);
796                    self.estimated_memory += token.text.len() + INTERN_OVERHEAD;
797                    spur
798                };
799                *self.local_tf_buffer.entry(term_spur).or_insert(0) += 1;
800
801                if let Some(mode) = position_mode {
802                    let encoded_pos = match mode {
803                        PositionMode::Ordinal => encoded_ordinal << 20,
804                        PositionMode::TokenPosition => token.position,
805                        PositionMode::Full => {
806                            (encoded_ordinal << 20) | self.saturate_token_position(token.position)
807                        }
808                    };
809                    self.local_positions
810                        .entry(term_spur)
811                        .or_default()
812                        .push(encoded_pos);
813                }
814            }
815            token_position = tokens.len() as u32;
816        } else {
817            // Inline zero-allocation path: split_whitespace + lowercase + strip non-alphanumeric
818            for word in text.split_whitespace() {
819                self.token_buffer.clear();
820                for c in word.chars() {
821                    if c.is_alphanumeric() {
822                        for lc in c.to_lowercase() {
823                            self.token_buffer.push(lc);
824                        }
825                    }
826                }
827
828                if self.token_buffer.is_empty() {
829                    continue;
830                }
831
832                let term_spur = if let Some(spur) = self.term_interner.get(&self.token_buffer) {
833                    spur
834                } else {
835                    let spur = self.term_interner.get_or_intern(&self.token_buffer);
836                    self.estimated_memory += self.token_buffer.len() + INTERN_OVERHEAD;
837                    spur
838                };
839                *self.local_tf_buffer.entry(term_spur).or_insert(0) += 1;
840
841                if let Some(mode) = position_mode {
842                    let encoded_pos = match mode {
843                        PositionMode::Ordinal => encoded_ordinal << 20,
844                        PositionMode::TokenPosition => token_position,
845                        PositionMode::Full => {
846                            (encoded_ordinal << 20) | self.saturate_token_position(token_position)
847                        }
848                    };
849                    self.local_positions
850                        .entry(term_spur)
851                        .or_default()
852                        .push(encoded_pos);
853                }
854
855                token_position += 1;
856            }
857        }
858
859        // Phase 2: Insert aggregated terms into inverted index
860        // Now we only do one inverted_index lookup per unique term in doc
861        for (&term_spur, &tf) in &self.local_tf_buffer {
862            let term_key = TermKey {
863                field: field_id,
864                term: term_spur,
865            };
866
867            match self.inverted_index.entry(term_key) {
868                hashbrown::hash_map::Entry::Occupied(mut o) => {
869                    o.get_mut().add(doc_id, tf);
870                    self.estimated_memory += size_of::<CompactPosting>();
871                    // Spill large posting lists to disk to reduce peak memory
872                    #[cfg(feature = "native")]
873                    if o.get().should_spill() {
874                        use byteorder::{LittleEndian, WriteBytesExt};
875
876                        let builder = o.get_mut();
877                        let count = builder.postings.len() as u32;
878                        let offset = self.posting_spill_offset;
879
880                        // Lazily create the spill file on first spill
881                        let spill_file = if let Some(ref mut f) = self.posting_spill_file {
882                            f
883                        } else {
884                            self.posting_spill_file = Some(BufWriter::with_capacity(
885                                256 * 1024,
886                                OpenOptions::new()
887                                    .create(true)
888                                    .write(true)
889                                    .truncate(true)
890                                    .open(&self.posting_spill_path)?,
891                            ));
892                            self.posting_spill_file.as_mut().unwrap()
893                        };
894                        for p in &builder.postings {
895                            spill_file.write_u32::<LittleEndian>(p.doc_id)?;
896                            spill_file.write_u16::<LittleEndian>(p.term_freq)?;
897                        }
898                        self.posting_spill_offset += count as u64 * 6;
899                        self.posting_spill_index
900                            .entry(term_key)
901                            .or_default()
902                            .push((offset, count));
903
904                        let freed = builder.postings.len() * size_of::<CompactPosting>();
905                        builder.spilled_count += count;
906                        builder.postings.clear();
907                        self.estimated_memory -= freed;
908                    }
909                }
910                hashbrown::hash_map::Entry::Vacant(v) => {
911                    let mut posting = PostingListBuilder::new();
912                    posting.add(doc_id, tf);
913                    v.insert(posting);
914                    self.estimated_memory += size_of::<CompactPosting>() + NEW_TERM_OVERHEAD;
915                }
916            }
917
918            if position_mode.is_some()
919                && let Some(positions) = self.local_positions.get(&term_spur)
920            {
921                match self.position_index.entry(term_key) {
922                    hashbrown::hash_map::Entry::Occupied(mut o) => {
923                        for &pos in positions {
924                            o.get_mut().add_position(doc_id, pos);
925                        }
926                        self.estimated_memory += positions.len() * size_of::<u32>();
927                    }
928                    hashbrown::hash_map::Entry::Vacant(v) => {
929                        let mut pos_posting = PositionPostingListBuilder::new();
930                        for &pos in positions {
931                            pos_posting.add_position(doc_id, pos);
932                        }
933                        self.estimated_memory +=
934                            positions.len() * size_of::<u32>() + NEW_POS_TERM_OVERHEAD;
935                        v.insert(pos_posting);
936                    }
937                }
938            }
939        }
940
941        Ok(token_position)
942    }
943
944    /// Saturate a token position at the 20-bit packed-encoding maximum so it
945    /// cannot bleed into the element-ordinal bits.
946    #[inline]
947    fn saturate_token_position(&mut self, token_position: u32) -> u32 {
948        if token_position > MAX_TOKEN_POSITION {
949            self.warn_position_saturation("token position", token_position, MAX_TOKEN_POSITION);
950            MAX_TOKEN_POSITION
951        } else {
952            token_position
953        }
954    }
955
956    /// Warn once per segment when the packed position encoding saturates.
957    #[cold]
958    fn warn_position_saturation(&mut self, what: &str, value: u32, max: u32) {
959        if !self.position_saturation_warned {
960            self.position_saturation_warned = true;
961            log::warn!(
962                "[segment_builder] {what} {value} exceeds the position-encoding limit {max}; \
963                 saturating — phrase/ordinal matching degrades for the overflowing \
964                 elements/tokens instead of corrupting other documents' matches \
965                 (further occurrences in this segment are not logged)"
966            );
967        }
968    }
969
970    fn index_numeric_field(&mut self, field: Field, doc_id: DocId, value: u64) -> Result<()> {
971        use std::fmt::Write;
972
973        self.numeric_buffer.clear();
974        write!(self.numeric_buffer, "__num_{}", value).unwrap();
975        let term_spur = if let Some(spur) = self.term_interner.get(&self.numeric_buffer) {
976            spur
977        } else {
978            let spur = self.term_interner.get_or_intern(&self.numeric_buffer);
979            self.estimated_memory += self.numeric_buffer.len() + INTERN_OVERHEAD;
980            spur
981        };
982
983        let term_key = TermKey {
984            field: field.0,
985            term: term_spur,
986        };
987
988        match self.inverted_index.entry(term_key) {
989            hashbrown::hash_map::Entry::Occupied(mut o) => {
990                o.get_mut().add(doc_id, 1);
991                self.estimated_memory += size_of::<CompactPosting>();
992            }
993            hashbrown::hash_map::Entry::Vacant(v) => {
994                let mut posting = PostingListBuilder::new();
995                posting.add(doc_id, 1);
996                v.insert(posting);
997                self.estimated_memory += size_of::<CompactPosting>() + NEW_TERM_OVERHEAD;
998            }
999        }
1000
1001        Ok(())
1002    }
1003
1004    /// Index a dense vector field with ordinal tracking
1005    fn index_dense_vector_field(
1006        &mut self,
1007        field: Field,
1008        doc_id: DocId,
1009        ordinal: u16,
1010        vector: &[f32],
1011    ) -> Result<()> {
1012        let dim = vector.len();
1013        let expected_dim = self
1014            .schema
1015            .get_field_entry(field)
1016            .and_then(|entry| entry.dense_vector_config.as_ref())
1017            .map(|config| config.dim)
1018            .ok_or_else(|| crate::Error::Schema("DenseVector field missing config".to_string()))?;
1019        if dim != expected_dim {
1020            return Err(crate::Error::Schema(format!(
1021                "Dense vector dimension mismatch: schema expects {}, got {}",
1022                expected_dim, dim
1023            )));
1024        }
1025        if let Some((index, value)) = vector
1026            .iter()
1027            .enumerate()
1028            .find(|(_, value)| !value.is_finite())
1029        {
1030            return Err(crate::Error::Document(format!(
1031                "dense vector contains non-finite value {value} at index {index}"
1032            )));
1033        }
1034
1035        let builder = self
1036            .dense_vectors
1037            .entry(field.0)
1038            .or_insert_with(|| DenseVectorBuilder::new(dim));
1039
1040        // Verify dimension consistency
1041        if builder.dim != dim && builder.len() > 0 {
1042            return Err(crate::Error::Schema(format!(
1043                "Dense vector dimension mismatch: expected {}, got {}",
1044                builder.dim, dim
1045            )));
1046        }
1047
1048        builder.add(doc_id, ordinal, vector);
1049
1050        self.estimated_memory += std::mem::size_of_val(vector) + size_of::<(DocId, u16)>();
1051
1052        Ok(())
1053    }
1054
1055    /// Index a binary dense vector field with ordinal tracking
1056    fn index_binary_dense_vector_field(
1057        &mut self,
1058        field: Field,
1059        doc_id: DocId,
1060        ordinal: u16,
1061        bytes: &[u8],
1062    ) -> Result<()> {
1063        let dim_bits = self
1064            .schema
1065            .get_field_entry(field)
1066            .and_then(|e| e.binary_dense_vector_config.as_ref())
1067            .map(|c| c.dim)
1068            .ok_or_else(|| {
1069                crate::Error::Schema("BinaryDenseVector field missing config".to_string())
1070            })?;
1071
1072        let expected_byte_len = dim_bits.div_ceil(8);
1073        if dim_bits == 0 || !dim_bits.is_multiple_of(8) {
1074            return Err(crate::Error::Schema(format!(
1075                "Binary vector dimension must be a positive multiple of 8, got {dim_bits}"
1076            )));
1077        }
1078        if bytes.len() != expected_byte_len {
1079            return Err(crate::Error::Schema(format!(
1080                "Binary vector byte length mismatch: expected {} (dim={}), got {}",
1081                expected_byte_len,
1082                dim_bits,
1083                bytes.len()
1084            )));
1085        }
1086
1087        let builder = self
1088            .binary_dense_vectors
1089            .entry(field.0)
1090            .or_insert_with(|| BinaryDenseVectorBuilder::new(dim_bits));
1091
1092        builder.add(doc_id, ordinal, bytes);
1093        self.estimated_memory += bytes.len() + size_of::<(DocId, u16)>();
1094
1095        Ok(())
1096    }
1097
1098    /// Index a sparse vector field using dedicated sparse posting lists
1099    ///
1100    /// Collects (doc_id, ordinal, weight) postings per dimension. During commit, these are
1101    /// converted to BlockSparsePostingList with proper quantization from SparseVectorConfig.
1102    ///
1103    /// Weights below the configured `weight_threshold` are not indexed. When
1104    /// `doc_mass` is configured, only the top-|weight| entries covering that
1105    /// fraction of the vector's total |weight| mass are kept (the excessive
1106    /// tail of SPLADE-style vectors is cropped).
1107    fn index_sparse_vector_field(
1108        &mut self,
1109        field: Field,
1110        doc_id: DocId,
1111        ordinal: u16,
1112        entries: &[(u32, f32)],
1113    ) -> Result<()> {
1114        if let Some((index, (_, weight))) = entries
1115            .iter()
1116            .enumerate()
1117            .find(|(_, (_, weight))| !weight.is_finite())
1118        {
1119            return Err(crate::Error::Document(format!(
1120                "sparse vector contains non-finite weight {weight} at index {index}"
1121            )));
1122        }
1123        let (weight_threshold, doc_mass, min_terms) = self
1124            .schema
1125            .get_field_entry(field)
1126            .and_then(|entry| entry.sparse_vector_config.as_ref())
1127            .map(|config| (config.weight_threshold, config.doc_mass, config.min_terms))
1128            .unwrap_or((0.0, None, 0));
1129
1130        let builder = self
1131            .sparse_vectors
1132            .entry(field.0)
1133            .or_insert_with(SparseVectorBuilder::new);
1134
1135        builder.inc_vector_count();
1136
1137        // Document-side mass cropping: determine the per-vector weight cutoff
1138        // below which entries fall outside the doc_mass fraction of total mass.
1139        // Short vectors (<= min_terms entries) are never cropped.
1140        let mass_cutoff = match doc_mass {
1141            Some(mass) if mass < 1.0 && entries.len() > min_terms => {
1142                let mut weights: Vec<f32> = entries
1143                    .iter()
1144                    .map(|&(_, w)| w.abs())
1145                    .filter(|w| *w >= weight_threshold)
1146                    .collect();
1147                weights.sort_unstable_by(|a, b| b.total_cmp(a));
1148                let total: f64 = weights.iter().map(|&w| w as f64).sum();
1149                let target = total * mass as f64;
1150                let mut cumulative = 0.0f64;
1151                let mut cutoff = 0.0f32;
1152                for &w in &weights {
1153                    if cumulative >= target {
1154                        break;
1155                    }
1156                    cumulative += w as f64;
1157                    cutoff = w;
1158                }
1159                cutoff
1160            }
1161            _ => 0.0,
1162        };
1163
1164        for &(dim_id, weight) in entries {
1165            // Skip weights below threshold or outside the doc_mass prefix
1166            if weight.abs() < weight_threshold || weight.abs() < mass_cutoff {
1167                continue;
1168            }
1169
1170            let is_new_dim = !builder.postings.contains_key(&dim_id);
1171            builder.add(dim_id, doc_id, ordinal, weight);
1172            self.estimated_memory += size_of::<(DocId, u16, f32)>();
1173            if is_new_dim {
1174                // HashMap entry overhead + Vec header
1175                self.estimated_memory += size_of::<u32>() + size_of::<Vec<(DocId, u16, f32)>>() + 8; // 8 = hashmap control byte + padding
1176            }
1177        }
1178
1179        Ok(())
1180    }
1181
1182    /// Write document to streaming store (reuses internal buffer to avoid per-doc allocation)
1183    fn write_document_to_store(&mut self, doc: &Document) -> Result<()> {
1184        use byteorder::{LittleEndian, WriteBytesExt};
1185
1186        super::store::serialize_document_into(doc, &self.schema, &mut self.doc_serialize_buffer)?;
1187
1188        #[cfg(feature = "native")]
1189        {
1190            self.store_file
1191                .write_u32::<LittleEndian>(self.doc_serialize_buffer.len() as u32)?;
1192            self.store_file.write_all(&self.doc_serialize_buffer)?;
1193        }
1194        #[cfg(not(feature = "native"))]
1195        {
1196            self.store_buffer
1197                .write_u32::<LittleEndian>(self.doc_serialize_buffer.len() as u32)?;
1198            self.store_buffer.write_all(&self.doc_serialize_buffer)?;
1199            // The in-memory store buffer is often the largest allocation on
1200            // the wasm branch (native streams docs to a temp file instead).
1201            // Count it so the memory-budget flush check can see it.
1202            self.estimated_memory += size_of::<u32>() + self.doc_serialize_buffer.len();
1203        }
1204
1205        Ok(())
1206    }
1207
1208    /// Build the final segment
1209    ///
1210    /// Streams all data directly to disk via StreamingWriter to avoid buffering
1211    /// entire serialized outputs in memory. Each phase consumes and drops its
1212    /// source data before the next phase begins.
1213    pub async fn build<D: Directory + DirectoryWriter>(
1214        mut self,
1215        dir: &D,
1216        segment_id: SegmentId,
1217        trained: Option<&super::TrainedVectorStructures>,
1218    ) -> Result<SegmentMeta> {
1219        // Flush any buffered data
1220        #[cfg(feature = "native")]
1221        self.store_file.flush()?;
1222
1223        let files = SegmentFiles::new(segment_id.0);
1224
1225        // Phase 1: Stream positions directly to disk (consumes position_index)
1226        let position_index = std::mem::take(&mut self.position_index);
1227        let position_offsets = if !position_index.is_empty() {
1228            let mut pos_writer = dir.streaming_writer(&files.positions).await?;
1229            let offsets = postings::build_positions_streaming(
1230                position_index,
1231                &self.term_interner,
1232                &mut *pos_writer,
1233            )?;
1234            pos_writer.finish()?;
1235            offsets
1236        } else {
1237            FxHashMap::default()
1238        };
1239
1240        // Phase 2: 4-way parallel build — postings, store, dense vectors, sparse vectors
1241        // These are fully independent: different source data, different output files.
1242        let inverted_index = std::mem::take(&mut self.inverted_index);
1243        let term_interner = std::mem::replace(&mut self.term_interner, Rodeo::new());
1244        #[cfg(feature = "native")]
1245        let store_path = self.store_path.clone();
1246        #[cfg(feature = "native")]
1247        let num_compression_threads = self.config.num_compression_threads;
1248        let compression_level = self.config.compression_level;
1249        let dense_vectors = std::mem::take(&mut self.dense_vectors);
1250        let binary_dense_vectors = std::mem::take(&mut self.binary_dense_vectors);
1251        let mut sparse_vectors = std::mem::take(&mut self.sparse_vectors);
1252        let schema = &self.schema;
1253
1254        // Pre-create all streaming writers (async) before entering sync rayon scope
1255        // Wrapped in OffsetWriter to track bytes written per phase.
1256        let mut term_dict_writer =
1257            super::OffsetWriter::new(dir.streaming_writer(&files.term_dict).await?);
1258        let mut postings_writer =
1259            super::OffsetWriter::new(dir.streaming_writer(&files.postings).await?);
1260        let mut store_writer = super::OffsetWriter::new(dir.streaming_writer(&files.store).await?);
1261        let mut vectors_writer = if !dense_vectors.is_empty() || !binary_dense_vectors.is_empty() {
1262            Some(super::OffsetWriter::new(
1263                dir.streaming_writer(&files.vectors).await?,
1264            ))
1265        } else {
1266            None
1267        };
1268        let mut sparse_writer = if !sparse_vectors.is_empty() {
1269            Some(super::OffsetWriter::new(
1270                dir.streaming_writer(&files.sparse).await?,
1271            ))
1272        } else {
1273            None
1274        };
1275        let mut fast_fields = std::mem::take(&mut self.fast_fields);
1276        let num_docs = self.next_doc_id;
1277        let mut fast_writer = if !fast_fields.is_empty() {
1278            Some(super::OffsetWriter::new(
1279                dir.streaming_writer(&files.fast).await?,
1280            ))
1281        } else {
1282            None
1283        };
1284
1285        #[cfg(feature = "native")]
1286        {
1287            if let Some(ref mut f) = self.posting_spill_file {
1288                f.flush()?;
1289            }
1290            let posting_spill_index = std::mem::take(&mut self.posting_spill_index);
1291            let mut spill_reader_opt = if !posting_spill_index.is_empty() {
1292                let spill_file = std::fs::File::open(&self.posting_spill_path)?;
1293                Some((std::io::BufReader::new(spill_file), posting_spill_index))
1294            } else {
1295                None
1296            };
1297
1298            let ((postings_result, store_result), ((vectors_result, sparse_result), fast_result)) =
1299                rayon::join(
1300                    || {
1301                        rayon::join(
1302                            || {
1303                                let spill_arg = spill_reader_opt.as_mut().map(|(r, idx)| {
1304                                    (
1305                                        r as &mut std::io::BufReader<std::fs::File>,
1306                                        idx as &postings::SpillIndex,
1307                                    )
1308                                });
1309                                postings::build_postings_streaming(
1310                                    inverted_index,
1311                                    term_interner,
1312                                    &position_offsets,
1313                                    &mut term_dict_writer,
1314                                    &mut postings_writer,
1315                                    spill_arg,
1316                                )
1317                            },
1318                            || {
1319                                store::build_store_streaming(
1320                                    &store_path,
1321                                    num_compression_threads,
1322                                    compression_level,
1323                                    &mut store_writer,
1324                                    num_docs,
1325                                )
1326                            },
1327                        )
1328                    },
1329                    || {
1330                        rayon::join(
1331                            || {
1332                                rayon::join(
1333                                    || -> Result<()> {
1334                                        if let Some(ref mut w) = vectors_writer {
1335                                            dense::build_vectors_streaming(
1336                                                dense_vectors,
1337                                                binary_dense_vectors,
1338                                                schema,
1339                                                trained,
1340                                                w,
1341                                            )?;
1342                                        }
1343                                        Ok(())
1344                                    },
1345                                    || -> Result<()> {
1346                                        if let Some(ref mut w) = sparse_writer {
1347                                            sparse::build_sparse_streaming(
1348                                                &mut sparse_vectors,
1349                                                schema,
1350                                                w,
1351                                            )?;
1352                                        }
1353                                        Ok(())
1354                                    },
1355                                )
1356                            },
1357                            || -> Result<()> {
1358                                if let Some(ref mut w) = fast_writer {
1359                                    build_fast_fields_streaming(&mut fast_fields, num_docs, w)?;
1360                                }
1361                                Ok(())
1362                            },
1363                        )
1364                    },
1365                );
1366            postings_result?;
1367            store_result?;
1368            vectors_result?;
1369            sparse_result?;
1370            fast_result?;
1371        }
1372
1373        #[cfg(not(feature = "native"))]
1374        {
1375            postings::build_postings_streaming(
1376                inverted_index,
1377                term_interner,
1378                &position_offsets,
1379                &mut term_dict_writer,
1380                &mut postings_writer,
1381            )?;
1382            store::build_store_streaming_from_buffer(
1383                &self.store_buffer,
1384                compression_level,
1385                &mut store_writer,
1386                num_docs,
1387            )?;
1388            if let Some(ref mut w) = vectors_writer {
1389                dense::build_vectors_streaming(
1390                    dense_vectors,
1391                    binary_dense_vectors,
1392                    schema,
1393                    trained,
1394                    w,
1395                )?;
1396            }
1397            if let Some(ref mut w) = sparse_writer {
1398                sparse::build_sparse_streaming(&mut sparse_vectors, schema, w)?;
1399            }
1400            if let Some(ref mut w) = fast_writer {
1401                build_fast_fields_streaming(&mut fast_fields, num_docs, w)?;
1402            }
1403        }
1404
1405        let term_dict_bytes = term_dict_writer.offset() as usize;
1406        let postings_bytes = postings_writer.offset() as usize;
1407        let store_bytes = store_writer.offset() as usize;
1408        let vectors_bytes = vectors_writer.as_ref().map_or(0, |w| w.offset() as usize);
1409        let sparse_bytes = sparse_writer.as_ref().map_or(0, |w| w.offset() as usize);
1410        let fast_bytes = fast_writer.as_ref().map_or(0, |w| w.offset() as usize);
1411
1412        term_dict_writer.finish()?;
1413        postings_writer.finish()?;
1414        store_writer.finish()?;
1415        if let Some(w) = vectors_writer {
1416            w.finish()?;
1417        }
1418        if let Some(w) = sparse_writer {
1419            w.finish()?;
1420        }
1421        if let Some(w) = fast_writer {
1422            w.finish()?;
1423        }
1424        drop(position_offsets);
1425        drop(sparse_vectors);
1426
1427        log::info!(
1428            "[segment_build] {} docs: term_dict={}, postings={}, store={}, vectors={}, sparse={}, fast={}",
1429            num_docs,
1430            super::format_bytes(term_dict_bytes),
1431            super::format_bytes(postings_bytes),
1432            super::format_bytes(store_bytes),
1433            super::format_bytes(vectors_bytes),
1434            super::format_bytes(sparse_bytes),
1435            super::format_bytes(fast_bytes),
1436        );
1437
1438        let meta = SegmentMeta {
1439            id: segment_id.0,
1440            num_docs: self.next_doc_id,
1441            field_stats: self.field_stats.clone(),
1442        };
1443
1444        // Durable: committed metadata.json will reference this segment, so a
1445        // torn/unsynced .meta after power loss would make the commit
1446        // unreadable (every other segment file is fsynced by its streaming
1447        // writer's finish()).
1448        dir.write_durable(&files.meta, &meta.serialize()?).await?;
1449
1450        // Cleanup temp files
1451        #[cfg(feature = "native")]
1452        {
1453            let _ = std::fs::remove_file(&self.store_path);
1454        }
1455
1456        Ok(meta)
1457    }
1458}
1459
1460/// Serialize all fast-field columns to a `.fast` file.
1461fn build_fast_fields_streaming(
1462    fast_fields: &mut FxHashMap<u32, crate::structures::fast_field::FastFieldWriter>,
1463    num_docs: u32,
1464    writer: &mut dyn Write,
1465) -> Result<()> {
1466    use crate::structures::fast_field::{FastFieldTocEntry, write_fast_field_toc_and_footer};
1467
1468    if fast_fields.is_empty() {
1469        return Ok(());
1470    }
1471
1472    // Sort fields by id for deterministic output
1473    let mut field_ids: Vec<u32> = fast_fields.keys().copied().collect();
1474    field_ids.sort_unstable();
1475
1476    let mut toc_entries: Vec<FastFieldTocEntry> = Vec::with_capacity(field_ids.len());
1477    let mut current_offset = 0u64;
1478
1479    for &field_id in &field_ids {
1480        let ff = fast_fields.get_mut(&field_id).unwrap();
1481        ff.pad_to(num_docs);
1482
1483        let (mut toc, bytes_written) = ff.serialize(writer, current_offset)?;
1484        toc.field_id = field_id;
1485        current_offset += bytes_written;
1486        toc_entries.push(toc);
1487    }
1488
1489    // Write TOC + footer
1490    let toc_offset = current_offset;
1491    write_fast_field_toc_and_footer(writer, toc_offset, &toc_entries)?;
1492
1493    Ok(())
1494}
1495
1496#[cfg(feature = "native")]
1497impl Drop for SegmentBuilder {
1498    fn drop(&mut self) {
1499        let _ = std::fs::remove_file(&self.store_path);
1500        if self.posting_spill_file.is_some() {
1501            let _ = std::fs::remove_file(&self.posting_spill_path);
1502        }
1503    }
1504}
1505
1506#[cfg(test)]
1507impl SegmentBuilder {
1508    /// Test helper: all encoded positions recorded for `(field, term)`.
1509    fn positions_for_term(&self, field: Field, term: &str) -> Vec<u32> {
1510        let Some(spur) = self.term_interner.get(term) else {
1511            return Vec::new();
1512        };
1513        let key = TermKey {
1514            field: field.0,
1515            term: spur,
1516        };
1517        self.position_index
1518            .get(&key)
1519            .map(|b| {
1520                b.postings
1521                    .iter()
1522                    .flat_map(|(_, ps)| ps.iter().copied())
1523                    .collect()
1524            })
1525            .unwrap_or_default()
1526    }
1527}
1528
1529#[cfg(test)]
1530mod tests {
1531    use super::*;
1532    use crate::dsl::SchemaBuilder;
1533
1534    fn builder_for(schema: Schema) -> SegmentBuilder {
1535        SegmentBuilder::new(Arc::new(schema), SegmentBuilderConfig::default()).unwrap()
1536    }
1537
1538    // ------------------------------------------------------------------
1539    // Finding: field values whose runtime type does not match the schema
1540    // field type fell into `_ => {}` and were silently not indexed while
1541    // still being stored — queries could never match the document.
1542    // ------------------------------------------------------------------
1543    #[test]
1544    fn test_add_document_rejects_type_mismatched_field_value() {
1545        let mut sb = SchemaBuilder::default();
1546        let views = sb.add_u64_field("views", true, true);
1547        let mut builder = builder_for(sb.build());
1548
1549        let mut doc = Document::new();
1550        doc.add_text(views, "123");
1551        let err = builder
1552            .add_document(doc)
1553            .expect_err("schema-mismatched value must be rejected loudly, not silently unindexed");
1554        let msg = err.to_string();
1555        assert!(msg.contains("views"), "error must name the field: {msg}");
1556        assert!(
1557            msg.contains("u64"),
1558            "error must name the expected type: {msg}"
1559        );
1560        assert!(msg.contains("text"), "error must name the got type: {msg}");
1561
1562        // The rejected document must not have consumed a doc id (no poisoning).
1563        assert_eq!(builder.num_docs(), 0);
1564
1565        // A well-typed document still indexes fine afterwards.
1566        let mut doc = Document::new();
1567        doc.add_u64(views, 123);
1568        builder.add_document(doc).unwrap();
1569        assert_eq!(builder.num_docs(), 1);
1570    }
1571
1572    // ------------------------------------------------------------------
1573    // Finding: sparse entries with dim_id >= the configured BMP `dims`
1574    // were accepted at index time but silently dropped from the BMP grid
1575    // and silently filtered from queries — permanently unsearchable.
1576    // ------------------------------------------------------------------
1577    #[test]
1578    fn test_add_document_rejects_bmp_sparse_dim_out_of_range() {
1579        use crate::structures::{SparseFormat, SparseVectorConfig};
1580
1581        let mut sb = SchemaBuilder::default();
1582        let config = SparseVectorConfig {
1583            format: SparseFormat::Bmp,
1584            dims: Some(100),
1585            ..Default::default()
1586        };
1587        let spv = sb.add_sparse_vector_field_with_config("spv", true, false, config);
1588        let mut builder = builder_for(sb.build());
1589
1590        // In-range dims are accepted.
1591        let mut doc = Document::new();
1592        doc.add_sparse_vector(spv, vec![(50, 1.0)]);
1593        builder.add_document(doc).unwrap();
1594
1595        // dim_id >= dims must be rejected with an actionable error.
1596        let mut doc = Document::new();
1597        doc.add_sparse_vector(spv, vec![(50, 1.0), (150, 2.0)]);
1598        let err = builder
1599            .add_document(doc)
1600            .expect_err("out-of-range BMP dim must be rejected, not silently unsearchable");
1601        let msg = err.to_string();
1602        assert!(msg.contains("spv"), "error must name the field: {msg}");
1603        assert!(msg.contains("150"), "error must name the dim_id: {msg}");
1604        assert!(
1605            msg.contains("100"),
1606            "error must name the configured dims: {msg}"
1607        );
1608        assert_eq!(
1609            builder.num_docs(),
1610            1,
1611            "rejected doc must not consume a doc id"
1612        );
1613    }
1614
1615    #[test]
1616    fn test_add_document_maxscore_sparse_dims_unbounded() {
1617        // MaxScore-format sparse fields have no dims bound — large dim ids
1618        // stay legal (the per-dim TOC addresses any u32 dimension).
1619        let mut sb = SchemaBuilder::default();
1620        let spv = sb.add_sparse_vector_field("spv", true, false);
1621        let mut builder = builder_for(sb.build());
1622
1623        let mut doc = Document::new();
1624        doc.add_sparse_vector(spv, vec![(3_000_000, 1.0)]);
1625        builder.add_document(doc).unwrap();
1626    }
1627
1628    // ------------------------------------------------------------------
1629    // Finding: `(element_ordinal << 20) | token_position` silently
1630    // corrupted when element_ordinal >= 4096 (shifted out of the u32,
1631    // aliasing element 0) or token_position >= 2^20 (bleeding into the
1632    // ordinal bits). Both must saturate at their field maxima.
1633    // ------------------------------------------------------------------
1634    #[test]
1635    fn test_position_element_ordinal_overflow_saturates_instead_of_wrapping() {
1636        use crate::dsl::PositionMode;
1637
1638        let mut sb = SchemaBuilder::default();
1639        let body = sb.add_text_field("body", true, false);
1640        sb.set_positions(body, PositionMode::Full);
1641        let mut builder = builder_for(sb.build());
1642
1643        // 4097 values: element ordinal 4096 does not fit the 12-bit ordinal
1644        // field ((4096u32 << 20) wraps to 0, colliding with element 0).
1645        let mut doc = Document::new();
1646        doc.add_text(body, "anchor");
1647        for _ in 0..4095 {
1648            doc.add_text(body, "filler");
1649        }
1650        doc.add_text(body, "needle");
1651        builder.add_document(doc).unwrap();
1652
1653        let positions = builder.positions_for_term(body, "needle");
1654        assert_eq!(positions.len(), 1);
1655        let encoded = positions[0];
1656        assert_ne!(
1657            encoded >> 20,
1658            0,
1659            "element ordinal 4096 must not alias element 0"
1660        );
1661        assert_eq!(
1662            encoded >> 20,
1663            4095,
1664            "overflowing element ordinal must saturate at 4095"
1665        );
1666    }
1667
1668    #[test]
1669    fn test_position_token_position_overflow_saturates_instead_of_bleeding() {
1670        use crate::dsl::PositionMode;
1671
1672        let mut sb = SchemaBuilder::default();
1673        let body = sb.add_text_field("body", true, false);
1674        sb.set_positions(body, PositionMode::Full);
1675        let mut builder = builder_for(sb.build());
1676
1677        // One value with 2^20 + 1 tokens: the last token's position does not
1678        // fit the 20-bit position field and would bleed into ordinal bit 0.
1679        let mut text = "w ".repeat(1 << 20);
1680        text.push_str("needle");
1681        let mut doc = Document::new();
1682        doc.add_text(body, text);
1683        builder.add_document(doc).unwrap();
1684
1685        let positions = builder.positions_for_term(body, "needle");
1686        assert_eq!(positions.len(), 1);
1687        let encoded = positions[0];
1688        assert_eq!(
1689            encoded >> 20,
1690            0,
1691            "token position overflow must not decode as a different element ordinal"
1692        );
1693        assert_eq!(
1694            encoded & 0xFFFFF,
1695            0xFFFFF,
1696            "overflowing token position must saturate at 2^20 - 1"
1697        );
1698    }
1699
1700    // ------------------------------------------------------------------
1701    // Finding: a posting-list spill firing between two values of the same
1702    // document split that document's postings across the spilled range and
1703    // the in-memory tail; the build-time merge concatenated them without
1704    // deduplication (inflated doc_freq, doc visited twice, split tf).
1705    // ------------------------------------------------------------------
1706    #[cfg(feature = "native")]
1707    #[tokio::test]
1708    async fn test_spill_mid_document_does_not_duplicate_postings() {
1709        use crate::directories::RamDirectory;
1710        use crate::structures::TERMINATED;
1711
1712        let mut sb = SchemaBuilder::default();
1713        let body = sb.add_text_field("body", true, false);
1714        let schema = Arc::new(sb.build());
1715        let mut builder =
1716            SegmentBuilder::new(Arc::clone(&schema), SegmentBuilderConfig::default()).unwrap();
1717
1718        // Docs 0..16382 each contribute one posting for "hot", leaving the
1719        // in-memory posting list one entry short of SPILL_THRESHOLD (16384).
1720        for _ in 0..16383 {
1721            let mut doc = Document::new();
1722            doc.add_text(body, "hot");
1723            builder.add_document(doc).unwrap();
1724        }
1725
1726        // Doc 16383 has TWO values containing "hot": indexing the first value
1727        // reaches the spill threshold and spills the list INCLUDING this doc's
1728        // entry; the second value then re-adds the same doc to the now-empty
1729        // in-memory tail.
1730        let mut doc = Document::new();
1731        doc.add_text(body, "hot");
1732        doc.add_text(body, "hot");
1733        let boundary_doc = builder.add_document(doc).unwrap();
1734        assert_eq!(boundary_doc, 16383);
1735
1736        let dir = RamDirectory::new();
1737        let segment_id = crate::segment::SegmentId::new();
1738        builder.build(&dir, segment_id, None).await.unwrap();
1739
1740        let reader = crate::segment::SegmentReader::open(&dir, segment_id, schema, 16)
1741            .await
1742            .unwrap();
1743        let postings = reader
1744            .get_postings(body, b"hot")
1745            .await
1746            .unwrap()
1747            .expect("postings for 'hot'");
1748        assert_eq!(
1749            postings.doc_count(),
1750            16384,
1751            "each document must appear exactly once per term (spill-boundary duplicate)"
1752        );
1753
1754        // Doc ids must be strictly increasing and the boundary document's
1755        // split term frequency must be merged into a single posting.
1756        let mut it = postings.iterator();
1757        let mut prev: Option<DocId> = None;
1758        let mut boundary_tf = 0u32;
1759        let mut d = it.doc();
1760        while d != TERMINATED {
1761            if let Some(p) = prev {
1762                assert!(p < d, "duplicate/unordered doc id {d} after {p}");
1763            }
1764            if d == boundary_doc {
1765                boundary_tf = it.term_freq();
1766            }
1767            prev = Some(d);
1768            d = it.advance();
1769        }
1770        assert_eq!(prev, Some(boundary_doc));
1771        assert_eq!(
1772            boundary_tf, 2,
1773            "boundary doc's term frequency must combine both values"
1774        );
1775    }
1776}