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//! - **Incremental posting flush**: Large posting lists flushed to temp file
8//! - **Memory-mapped intermediate files**: Reduces memory pressure
9//! - **Arena allocation**: Batch allocations for reduced fragmentation
10
11mod config;
12mod posting;
13mod vectors;
14
15pub use config::{MemoryBreakdown, SegmentBuilderConfig, SegmentBuilderStats};
16
17use std::fs::{File, OpenOptions};
18use std::io::{BufWriter, Write};
19use std::path::PathBuf;
20
21use hashbrown::HashMap;
22use lasso::{Rodeo, Spur};
23use rayon::prelude::*;
24use rustc_hash::FxHashMap;
25
26use crate::compression::CompressionLevel;
27
28use super::types::{FieldStats, SegmentFiles, SegmentId, SegmentMeta};
29use crate::directories::{Directory, DirectoryWriter};
30use crate::dsl::{Document, Field, FieldType, FieldValue, Schema};
31use crate::structures::{PostingList, SSTableWriter, TermInfo};
32use crate::tokenizer::BoxedTokenizer;
33use crate::{DocId, Result};
34
35use posting::{
36    CompactPosting, PositionPostingListBuilder, PostingListBuilder, SerializedPosting, TermKey,
37};
38use vectors::{DenseVectorBuilder, SparseVectorBuilder};
39
40// Re-export from vector_data for backwards compatibility
41pub use super::vector_data::{FlatVectorData, IVFRaBitQIndexData, ScaNNIndexData};
42
43/// Size of the document store buffer before writing to disk
44const STORE_BUFFER_SIZE: usize = 16 * 1024 * 1024; // 16MB
45
46/// Segment builder with optimized memory usage
47///
48/// Features:
49/// - Streams documents to disk immediately (no in-memory document storage)
50/// - Uses string interning for terms (reduced allocations)
51/// - Uses hashbrown HashMap (faster than BTreeMap)
52pub struct SegmentBuilder {
53    schema: Schema,
54    config: SegmentBuilderConfig,
55    tokenizers: FxHashMap<Field, BoxedTokenizer>,
56
57    /// String interner for terms - O(1) lookup and deduplication
58    term_interner: Rodeo,
59
60    /// Inverted index: term key -> posting list
61    inverted_index: HashMap<TermKey, PostingListBuilder>,
62
63    /// Streaming document store writer
64    store_file: BufWriter<File>,
65    store_path: PathBuf,
66
67    /// Document count
68    next_doc_id: DocId,
69
70    /// Per-field statistics for BM25F
71    field_stats: FxHashMap<u32, FieldStats>,
72
73    /// Per-document field lengths stored compactly
74    /// Uses a flat Vec instead of Vec<HashMap> for better cache locality
75    /// Layout: [doc0_field0_len, doc0_field1_len, ..., doc1_field0_len, ...]
76    doc_field_lengths: Vec<u32>,
77    num_indexed_fields: usize,
78    field_to_slot: FxHashMap<u32, usize>,
79
80    /// Reusable buffer for per-document term frequency aggregation
81    /// Avoids allocating a new hashmap for each document
82    local_tf_buffer: FxHashMap<Spur, u32>,
83
84    /// Reusable buffer for tokenization to avoid per-token String allocations
85    token_buffer: String,
86
87    /// Dense vector storage per field: field -> (doc_ids, vectors)
88    /// Vectors are stored as flat f32 arrays for efficient RaBitQ indexing
89    dense_vectors: FxHashMap<u32, DenseVectorBuilder>,
90
91    /// Sparse vector storage per field: field -> SparseVectorBuilder
92    /// Uses proper BlockSparsePostingList with configurable quantization
93    sparse_vectors: FxHashMap<u32, SparseVectorBuilder>,
94
95    /// Position index for fields with positions enabled
96    /// term key -> position posting list
97    position_index: HashMap<TermKey, PositionPostingListBuilder>,
98
99    /// Fields that have position tracking enabled, with their mode
100    position_enabled_fields: FxHashMap<u32, Option<crate::dsl::PositionMode>>,
101
102    /// Current element ordinal for multi-valued fields (reset per document)
103    current_element_ordinal: FxHashMap<u32, u32>,
104
105    /// Incrementally tracked memory estimate (avoids expensive stats() calls)
106    estimated_memory: usize,
107}
108
109impl SegmentBuilder {
110    /// Create a new segment builder
111    pub fn new(schema: Schema, config: SegmentBuilderConfig) -> Result<Self> {
112        let segment_id = uuid::Uuid::new_v4();
113        let store_path = config
114            .temp_dir
115            .join(format!("hermes_store_{}.tmp", segment_id));
116
117        let store_file = BufWriter::with_capacity(
118            STORE_BUFFER_SIZE,
119            OpenOptions::new()
120                .create(true)
121                .write(true)
122                .truncate(true)
123                .open(&store_path)?,
124        );
125
126        // Count indexed fields for compact field length storage
127        // Also track which fields have position recording enabled
128        let mut num_indexed_fields = 0;
129        let mut field_to_slot = FxHashMap::default();
130        let mut position_enabled_fields = FxHashMap::default();
131        for (field, entry) in schema.fields() {
132            if entry.indexed && matches!(entry.field_type, FieldType::Text) {
133                field_to_slot.insert(field.0, num_indexed_fields);
134                num_indexed_fields += 1;
135                if entry.positions.is_some() {
136                    position_enabled_fields.insert(field.0, entry.positions);
137                }
138            }
139        }
140
141        Ok(Self {
142            schema,
143            tokenizers: FxHashMap::default(),
144            term_interner: Rodeo::new(),
145            inverted_index: HashMap::with_capacity(config.posting_map_capacity),
146            store_file,
147            store_path,
148            next_doc_id: 0,
149            field_stats: FxHashMap::default(),
150            doc_field_lengths: Vec::new(),
151            num_indexed_fields,
152            field_to_slot,
153            local_tf_buffer: FxHashMap::default(),
154            token_buffer: String::with_capacity(64),
155            config,
156            dense_vectors: FxHashMap::default(),
157            sparse_vectors: FxHashMap::default(),
158            position_index: HashMap::new(),
159            position_enabled_fields,
160            current_element_ordinal: FxHashMap::default(),
161            estimated_memory: 0,
162        })
163    }
164
165    pub fn set_tokenizer(&mut self, field: Field, tokenizer: BoxedTokenizer) {
166        self.tokenizers.insert(field, tokenizer);
167    }
168
169    pub fn num_docs(&self) -> u32 {
170        self.next_doc_id
171    }
172
173    /// Fast O(1) memory estimate - updated incrementally during indexing
174    #[inline]
175    pub fn estimated_memory_bytes(&self) -> usize {
176        self.estimated_memory
177    }
178
179    /// Get current statistics for debugging performance (expensive - iterates all data)
180    pub fn stats(&self) -> SegmentBuilderStats {
181        use std::mem::size_of;
182
183        let postings_in_memory: usize =
184            self.inverted_index.values().map(|p| p.postings.len()).sum();
185
186        // Size constants computed from actual types
187        let compact_posting_size = size_of::<CompactPosting>();
188        let vec_overhead = size_of::<Vec<u8>>(); // Vec header: ptr + len + cap = 24 bytes on 64-bit
189        let term_key_size = size_of::<TermKey>();
190        let posting_builder_size = size_of::<PostingListBuilder>();
191        let spur_size = size_of::<lasso::Spur>();
192        let sparse_entry_size = size_of::<(DocId, u16, f32)>();
193
194        // hashbrown HashMap entry overhead: key + value + 1 byte control + padding
195        // Measured: ~(key_size + value_size + 8) per entry on average
196        let hashmap_entry_base_overhead = 8usize;
197
198        // FxHashMap uses same layout as hashbrown
199        let fxhashmap_entry_overhead = hashmap_entry_base_overhead;
200
201        // Postings memory
202        let postings_bytes: usize = self
203            .inverted_index
204            .values()
205            .map(|p| p.postings.capacity() * compact_posting_size + vec_overhead)
206            .sum();
207
208        // Inverted index overhead
209        let index_overhead_bytes = self.inverted_index.len()
210            * (term_key_size + posting_builder_size + hashmap_entry_base_overhead);
211
212        // Term interner: Rodeo stores strings + metadata
213        // Rodeo internal: string bytes + Spur + arena overhead (~2 pointers per string)
214        let interner_arena_overhead = 2 * size_of::<usize>();
215        let avg_term_len = 8; // Estimated average term length
216        let interner_bytes =
217            self.term_interner.len() * (avg_term_len + spur_size + interner_arena_overhead);
218
219        // Doc field lengths
220        let field_lengths_bytes =
221            self.doc_field_lengths.capacity() * size_of::<u32>() + vec_overhead;
222
223        // Dense vectors
224        let mut dense_vectors_bytes: usize = 0;
225        let mut dense_vector_count: usize = 0;
226        let doc_id_ordinal_size = size_of::<(DocId, u16)>();
227        for b in self.dense_vectors.values() {
228            dense_vectors_bytes += b.vectors.capacity() * size_of::<f32>()
229                + b.doc_ids.capacity() * doc_id_ordinal_size
230                + 2 * vec_overhead; // Two Vecs
231            dense_vector_count += b.doc_ids.len();
232        }
233
234        // Local buffers
235        let local_tf_entry_size = spur_size + size_of::<u32>() + fxhashmap_entry_overhead;
236        let local_tf_buffer_bytes = self.local_tf_buffer.capacity() * local_tf_entry_size;
237
238        // Sparse vectors
239        let mut sparse_vectors_bytes: usize = 0;
240        for builder in self.sparse_vectors.values() {
241            for postings in builder.postings.values() {
242                sparse_vectors_bytes += postings.capacity() * sparse_entry_size + vec_overhead;
243            }
244            // Inner FxHashMap overhead: u32 key + Vec value ptr + overhead
245            let inner_entry_size = size_of::<u32>() + vec_overhead + fxhashmap_entry_overhead;
246            sparse_vectors_bytes += builder.postings.len() * inner_entry_size;
247        }
248        // Outer FxHashMap overhead
249        let outer_sparse_entry_size =
250            size_of::<u32>() + size_of::<SparseVectorBuilder>() + fxhashmap_entry_overhead;
251        sparse_vectors_bytes += self.sparse_vectors.len() * outer_sparse_entry_size;
252
253        // Position index
254        let mut position_index_bytes: usize = 0;
255        for pos_builder in self.position_index.values() {
256            for (_, positions) in &pos_builder.postings {
257                position_index_bytes += positions.capacity() * size_of::<u32>() + vec_overhead;
258            }
259            // Vec<(DocId, Vec<u32>)> entry size
260            let pos_entry_size = size_of::<DocId>() + vec_overhead;
261            position_index_bytes += pos_builder.postings.capacity() * pos_entry_size;
262        }
263        // HashMap overhead for position_index
264        let pos_index_entry_size =
265            term_key_size + size_of::<PositionPostingListBuilder>() + hashmap_entry_base_overhead;
266        position_index_bytes += self.position_index.len() * pos_index_entry_size;
267
268        let estimated_memory_bytes = postings_bytes
269            + index_overhead_bytes
270            + interner_bytes
271            + field_lengths_bytes
272            + dense_vectors_bytes
273            + local_tf_buffer_bytes
274            + sparse_vectors_bytes
275            + position_index_bytes;
276
277        let memory_breakdown = MemoryBreakdown {
278            postings_bytes,
279            index_overhead_bytes,
280            interner_bytes,
281            field_lengths_bytes,
282            dense_vectors_bytes,
283            dense_vector_count,
284            sparse_vectors_bytes,
285            position_index_bytes,
286        };
287
288        SegmentBuilderStats {
289            num_docs: self.next_doc_id,
290            unique_terms: self.inverted_index.len(),
291            postings_in_memory,
292            interned_strings: self.term_interner.len(),
293            doc_field_lengths_size: self.doc_field_lengths.len(),
294            estimated_memory_bytes,
295            memory_breakdown,
296        }
297    }
298
299    /// Add a document - streams to disk immediately
300    pub fn add_document(&mut self, doc: Document) -> Result<DocId> {
301        let doc_id = self.next_doc_id;
302        self.next_doc_id += 1;
303
304        // Initialize field lengths for this document
305        let base_idx = self.doc_field_lengths.len();
306        self.doc_field_lengths
307            .resize(base_idx + self.num_indexed_fields, 0);
308
309        // Reset element ordinals for this document (for multi-valued fields)
310        self.current_element_ordinal.clear();
311
312        for (field, value) in doc.field_values() {
313            let entry = self.schema.get_field_entry(*field);
314            if entry.is_none() || !entry.unwrap().indexed {
315                continue;
316            }
317
318            let entry = entry.unwrap();
319            match (&entry.field_type, value) {
320                (FieldType::Text, FieldValue::Text(text)) => {
321                    // Get current element ordinal for multi-valued fields
322                    let element_ordinal = *self.current_element_ordinal.get(&field.0).unwrap_or(&0);
323                    let token_count =
324                        self.index_text_field(*field, doc_id, text, element_ordinal)?;
325                    // Increment element ordinal for next value of this field
326                    *self.current_element_ordinal.entry(field.0).or_insert(0) += 1;
327
328                    // Update field statistics
329                    let stats = self.field_stats.entry(field.0).or_default();
330                    stats.total_tokens += token_count as u64;
331                    stats.doc_count += 1;
332
333                    // Store field length compactly
334                    if let Some(&slot) = self.field_to_slot.get(&field.0) {
335                        self.doc_field_lengths[base_idx + slot] = token_count;
336                    }
337                }
338                (FieldType::U64, FieldValue::U64(v)) => {
339                    self.index_numeric_field(*field, doc_id, *v)?;
340                }
341                (FieldType::I64, FieldValue::I64(v)) => {
342                    self.index_numeric_field(*field, doc_id, *v as u64)?;
343                }
344                (FieldType::F64, FieldValue::F64(v)) => {
345                    self.index_numeric_field(*field, doc_id, v.to_bits())?;
346                }
347                (FieldType::DenseVector, FieldValue::DenseVector(vec)) => {
348                    // Get current element ordinal for multi-valued fields
349                    let element_ordinal = *self.current_element_ordinal.get(&field.0).unwrap_or(&0);
350                    self.index_dense_vector_field(*field, doc_id, element_ordinal as u16, vec)?;
351                    // Increment element ordinal for next value of this field
352                    *self.current_element_ordinal.entry(field.0).or_insert(0) += 1;
353                }
354                (FieldType::SparseVector, FieldValue::SparseVector(entries)) => {
355                    // Get current element ordinal for multi-valued fields
356                    let element_ordinal = *self.current_element_ordinal.get(&field.0).unwrap_or(&0);
357                    self.index_sparse_vector_field(
358                        *field,
359                        doc_id,
360                        element_ordinal as u16,
361                        entries,
362                    )?;
363                    // Increment element ordinal for next value of this field
364                    *self.current_element_ordinal.entry(field.0).or_insert(0) += 1;
365                }
366                _ => {}
367            }
368        }
369
370        // Stream document to disk immediately
371        self.write_document_to_store(&doc)?;
372
373        Ok(doc_id)
374    }
375
376    /// Index a text field using interned terms
377    ///
378    /// Optimization: Zero-allocation inline tokenization + term frequency aggregation.
379    /// Instead of allocating a String per token, we:
380    /// 1. Iterate over whitespace-split words
381    /// 2. Build lowercase token in a reusable buffer
382    /// 3. Intern directly from the buffer
383    ///
384    /// If position recording is enabled for this field, also records token positions
385    /// encoded as (element_ordinal << 20) | token_position.
386    fn index_text_field(
387        &mut self,
388        field: Field,
389        doc_id: DocId,
390        text: &str,
391        element_ordinal: u32,
392    ) -> Result<u32> {
393        use crate::dsl::PositionMode;
394
395        let field_id = field.0;
396        let position_mode = self
397            .position_enabled_fields
398            .get(&field_id)
399            .copied()
400            .flatten();
401
402        // Phase 1: Aggregate term frequencies within this document
403        // Also collect positions if enabled
404        // Reuse buffer to avoid allocations
405        self.local_tf_buffer.clear();
406
407        // For position tracking: term -> list of positions in this text
408        let mut local_positions: FxHashMap<Spur, Vec<u32>> = FxHashMap::default();
409
410        let mut token_position = 0u32;
411
412        // Zero-allocation tokenization: iterate words, lowercase inline, intern directly
413        for word in text.split_whitespace() {
414            // Build lowercase token in reusable buffer
415            self.token_buffer.clear();
416            for c in word.chars() {
417                if c.is_alphanumeric() {
418                    for lc in c.to_lowercase() {
419                        self.token_buffer.push(lc);
420                    }
421                }
422            }
423
424            if self.token_buffer.is_empty() {
425                continue;
426            }
427
428            // Intern the term directly from buffer - O(1) amortized
429            let term_spur = self.term_interner.get_or_intern(&self.token_buffer);
430            *self.local_tf_buffer.entry(term_spur).or_insert(0) += 1;
431
432            // Record position based on mode
433            if let Some(mode) = position_mode {
434                let encoded_pos = match mode {
435                    // Ordinal only: just store element ordinal (token position = 0)
436                    PositionMode::Ordinal => element_ordinal << 20,
437                    // Token position only: just store token position (ordinal = 0)
438                    PositionMode::TokenPosition => token_position,
439                    // Full: encode both
440                    PositionMode::Full => (element_ordinal << 20) | token_position,
441                };
442                local_positions
443                    .entry(term_spur)
444                    .or_default()
445                    .push(encoded_pos);
446            }
447
448            token_position += 1;
449        }
450
451        // Phase 2: Insert aggregated terms into inverted index
452        // Now we only do one inverted_index lookup per unique term in doc
453        for (&term_spur, &tf) in &self.local_tf_buffer {
454            let term_key = TermKey {
455                field: field_id,
456                term: term_spur,
457            };
458
459            let posting = self
460                .inverted_index
461                .entry(term_key)
462                .or_insert_with(PostingListBuilder::new);
463            posting.add(doc_id, tf);
464
465            // Add positions if enabled
466            if position_mode.is_some()
467                && let Some(positions) = local_positions.get(&term_spur)
468            {
469                let pos_posting = self
470                    .position_index
471                    .entry(term_key)
472                    .or_insert_with(PositionPostingListBuilder::new);
473                for &pos in positions {
474                    pos_posting.add_position(doc_id, pos);
475                }
476            }
477        }
478
479        Ok(token_position)
480    }
481
482    fn index_numeric_field(&mut self, field: Field, doc_id: DocId, value: u64) -> Result<()> {
483        // For numeric fields, we use a special encoding
484        let term_str = format!("__num_{}", value);
485        let term_spur = self.term_interner.get_or_intern(&term_str);
486
487        let term_key = TermKey {
488            field: field.0,
489            term: term_spur,
490        };
491
492        let posting = self
493            .inverted_index
494            .entry(term_key)
495            .or_insert_with(PostingListBuilder::new);
496        posting.add(doc_id, 1);
497
498        Ok(())
499    }
500
501    /// Index a dense vector field with ordinal tracking
502    fn index_dense_vector_field(
503        &mut self,
504        field: Field,
505        doc_id: DocId,
506        ordinal: u16,
507        vector: &[f32],
508    ) -> Result<()> {
509        let dim = vector.len();
510
511        let builder = self
512            .dense_vectors
513            .entry(field.0)
514            .or_insert_with(|| DenseVectorBuilder::new(dim));
515
516        // Verify dimension consistency
517        if builder.dim != dim && builder.len() > 0 {
518            return Err(crate::Error::Schema(format!(
519                "Dense vector dimension mismatch: expected {}, got {}",
520                builder.dim, dim
521            )));
522        }
523
524        builder.add(doc_id, ordinal, vector);
525        Ok(())
526    }
527
528    /// Index a sparse vector field using dedicated sparse posting lists
529    ///
530    /// Collects (doc_id, ordinal, weight) postings per dimension. During commit, these are
531    /// converted to BlockSparsePostingList with proper quantization from SparseVectorConfig.
532    ///
533    /// Weights below the configured `weight_threshold` are not indexed.
534    fn index_sparse_vector_field(
535        &mut self,
536        field: Field,
537        doc_id: DocId,
538        ordinal: u16,
539        entries: &[(u32, f32)],
540    ) -> Result<()> {
541        // Get weight threshold from field config (default 0.0 = no filtering)
542        let weight_threshold = self
543            .schema
544            .get_field_entry(field)
545            .and_then(|entry| entry.sparse_vector_config.as_ref())
546            .map(|config| config.weight_threshold)
547            .unwrap_or(0.0);
548
549        let builder = self
550            .sparse_vectors
551            .entry(field.0)
552            .or_insert_with(SparseVectorBuilder::new);
553
554        for &(dim_id, weight) in entries {
555            // Skip weights below threshold
556            if weight.abs() < weight_threshold {
557                continue;
558            }
559
560            builder.add(dim_id, doc_id, ordinal, weight);
561        }
562
563        Ok(())
564    }
565
566    /// Write document to streaming store
567    fn write_document_to_store(&mut self, doc: &Document) -> Result<()> {
568        use byteorder::{LittleEndian, WriteBytesExt};
569
570        let doc_bytes = super::store::serialize_document(doc, &self.schema)?;
571
572        self.store_file
573            .write_u32::<LittleEndian>(doc_bytes.len() as u32)?;
574        self.store_file.write_all(&doc_bytes)?;
575
576        Ok(())
577    }
578
579    /// Build the final segment
580    pub async fn build<D: Directory + DirectoryWriter>(
581        mut self,
582        dir: &D,
583        segment_id: SegmentId,
584    ) -> Result<SegmentMeta> {
585        // Flush any buffered data
586        self.store_file.flush()?;
587
588        let files = SegmentFiles::new(segment_id.0);
589
590        // Build positions FIRST to get offsets for TermInfo
591        let (positions_data, position_offsets) = self.build_positions_file()?;
592
593        // Extract data needed for parallel processing
594        let store_path = self.store_path.clone();
595        let schema = self.schema.clone();
596        let num_compression_threads = self.config.num_compression_threads;
597        let compression_level = self.config.compression_level;
598
599        // Build postings and document store in parallel
600        let (postings_result, store_result) = rayon::join(
601            || self.build_postings(&position_offsets),
602            || {
603                Self::build_store_parallel(
604                    &store_path,
605                    &schema,
606                    num_compression_threads,
607                    compression_level,
608                )
609            },
610        );
611
612        let (term_dict_data, postings_data) = postings_result?;
613        let store_data = store_result?;
614
615        // Write to directory
616        dir.write(&files.term_dict, &term_dict_data).await?;
617        dir.write(&files.postings, &postings_data).await?;
618        dir.write(&files.store, &store_data).await?;
619
620        // Write positions file (data only, offsets are in TermInfo)
621        if !positions_data.is_empty() {
622            dir.write(&files.positions, &positions_data).await?;
623        }
624
625        // Build and write dense vector indexes (RaBitQ) - all in one file
626        if !self.dense_vectors.is_empty() {
627            let vectors_data = self.build_vectors_file()?;
628            if !vectors_data.is_empty() {
629                dir.write(&files.vectors, &vectors_data).await?;
630            }
631        }
632
633        // Build and write sparse vector posting lists
634        if !self.sparse_vectors.is_empty() {
635            let sparse_data = self.build_sparse_file()?;
636            if !sparse_data.is_empty() {
637                dir.write(&files.sparse, &sparse_data).await?;
638            }
639        }
640
641        let meta = SegmentMeta {
642            id: segment_id.0,
643            num_docs: self.next_doc_id,
644            field_stats: self.field_stats.clone(),
645        };
646
647        dir.write(&files.meta, &meta.serialize()?).await?;
648
649        // Cleanup temp files
650        let _ = std::fs::remove_file(&self.store_path);
651
652        Ok(meta)
653    }
654
655    /// Build unified vectors file containing all dense vector indexes
656    ///
657    /// File format:
658    /// - Header: num_fields (u32)
659    /// - For each field: field_id (u32), index_type (u8), offset (u64), length (u64)
660    /// - Data: concatenated serialized indexes (RaBitQ, IVF-RaBitQ, or ScaNN)
661    fn build_vectors_file(&self) -> Result<Vec<u8>> {
662        use byteorder::{LittleEndian, WriteBytesExt};
663
664        // Build all indexes first: (field_id, index_type, data)
665        let mut field_indexes: Vec<(u32, u8, Vec<u8>)> = Vec::new();
666
667        for (&field_id, builder) in &self.dense_vectors {
668            if builder.len() == 0 {
669                continue;
670            }
671
672            let field = crate::dsl::Field(field_id);
673
674            // Get dense vector config
675            let dense_config = self
676                .schema
677                .get_field_entry(field)
678                .and_then(|e| e.dense_vector_config.as_ref());
679
680            // Get vectors, potentially trimmed for matryoshka/MRL indexing
681            let index_dim = dense_config.map(|c| c.index_dim()).unwrap_or(builder.dim);
682            let vectors = if index_dim < builder.dim {
683                // Trim vectors to mrl_dim for indexing
684                builder.get_vectors_trimmed(index_dim)
685            } else {
686                builder.get_vectors()
687            };
688
689            // During normal indexing, segments always store Flat (raw vectors).
690            // ANN indexes are built at index-level via build_vector_index() which
691            // trains centroids/codebooks once from all vectors and triggers rebuild.
692            let flat_data = FlatVectorData {
693                dim: index_dim,
694                vectors: vectors.clone(),
695                doc_ids: builder.doc_ids.clone(),
696            };
697            let index_bytes = serde_json::to_vec(&flat_data)
698                .map_err(|e| crate::Error::Serialization(e.to_string()))?;
699            let index_type = 3u8; // 3 = Flat
700
701            field_indexes.push((field_id, index_type, index_bytes));
702        }
703
704        if field_indexes.is_empty() {
705            return Ok(Vec::new());
706        }
707
708        // Sort by field_id for consistent ordering
709        field_indexes.sort_by_key(|(id, _, _)| *id);
710
711        // Calculate header size: num_fields + (field_id, index_type, offset, len) per field
712        let header_size = 4 + field_indexes.len() * (4 + 1 + 8 + 8);
713
714        // Build output
715        let mut output = Vec::new();
716
717        // Write number of fields
718        output.write_u32::<LittleEndian>(field_indexes.len() as u32)?;
719
720        // Calculate offsets and write header entries
721        let mut current_offset = header_size as u64;
722        for (field_id, index_type, data) in &field_indexes {
723            output.write_u32::<LittleEndian>(*field_id)?;
724            output.write_u8(*index_type)?;
725            output.write_u64::<LittleEndian>(current_offset)?;
726            output.write_u64::<LittleEndian>(data.len() as u64)?;
727            current_offset += data.len() as u64;
728        }
729
730        // Write data
731        for (_, _, data) in field_indexes {
732            output.extend_from_slice(&data);
733        }
734
735        Ok(output)
736    }
737
738    /// Build sparse vectors file containing BlockSparsePostingList per field/dimension
739    ///
740    /// File format (direct-indexed table for O(1) dimension lookup):
741    /// - Header: num_fields (u32)
742    /// - For each field:
743    ///   - field_id (u32)
744    ///   - quantization (u8)
745    ///   - max_dim_id (u32)          ← highest dimension ID + 1 (table size)
746    ///   - table: [(offset: u64, length: u32)] × max_dim_id  ← direct indexed by dim_id
747    ///     (offset=0, length=0 means dimension not present)
748    /// - Data: concatenated serialized BlockSparsePostingList
749    fn build_sparse_file(&self) -> Result<Vec<u8>> {
750        use crate::structures::{BlockSparsePostingList, WeightQuantization};
751        use byteorder::{LittleEndian, WriteBytesExt};
752
753        if self.sparse_vectors.is_empty() {
754            return Ok(Vec::new());
755        }
756
757        // Collect field data: (field_id, quantization, max_dim_id, dim_id -> serialized_bytes)
758        type SparseFieldData = (u32, WeightQuantization, u32, FxHashMap<u32, Vec<u8>>);
759        let mut field_data: Vec<SparseFieldData> = Vec::new();
760
761        for (&field_id, builder) in &self.sparse_vectors {
762            if builder.is_empty() {
763                continue;
764            }
765
766            let field = crate::dsl::Field(field_id);
767
768            // Get config from field
769            let sparse_config = self
770                .schema
771                .get_field_entry(field)
772                .and_then(|e| e.sparse_vector_config.as_ref());
773
774            let quantization = sparse_config
775                .map(|c| c.weight_quantization)
776                .unwrap_or(WeightQuantization::Float32);
777
778            let block_size = sparse_config.map(|c| c.block_size).unwrap_or(128);
779
780            // Find max dimension ID
781            let max_dim_id = builder.postings.keys().max().copied().unwrap_or(0);
782
783            // Build BlockSparsePostingList for each dimension
784            let mut dim_bytes: FxHashMap<u32, Vec<u8>> = FxHashMap::default();
785
786            for (&dim_id, postings) in &builder.postings {
787                // Sort postings by doc_id, then by ordinal
788                let mut sorted_postings = postings.clone();
789                sorted_postings.sort_by_key(|(doc_id, ordinal, _)| (*doc_id, *ordinal));
790
791                // Build BlockSparsePostingList with configured block size
792                let block_list = BlockSparsePostingList::from_postings_with_block_size(
793                    &sorted_postings,
794                    quantization,
795                    block_size,
796                )
797                .map_err(crate::Error::Io)?;
798
799                // Serialize
800                let mut bytes = Vec::new();
801                block_list.serialize(&mut bytes).map_err(crate::Error::Io)?;
802
803                dim_bytes.insert(dim_id, bytes);
804            }
805
806            field_data.push((field_id, quantization, max_dim_id + 1, dim_bytes));
807        }
808
809        if field_data.is_empty() {
810            return Ok(Vec::new());
811        }
812
813        // Sort by field_id
814        field_data.sort_by_key(|(id, _, _, _)| *id);
815
816        // Calculate header size
817        // Header: num_fields (4)
818        // Per field: field_id (4) + quant (1) + max_dim_id (4) + table (12 * max_dim_id)
819        let mut header_size = 4u64;
820        for (_, _, max_dim_id, _) in &field_data {
821            header_size += 4 + 1 + 4; // field_id + quant + max_dim_id
822            header_size += (*max_dim_id as u64) * 12; // table entries: (offset: u64, length: u32)
823        }
824
825        // Build output
826        let mut output = Vec::new();
827
828        // Write num_fields
829        output.write_u32::<LittleEndian>(field_data.len() as u32)?;
830
831        // Track current data offset (after all headers)
832        let mut current_offset = header_size;
833
834        // First, collect all data bytes in order and build offset tables
835        let mut all_data: Vec<u8> = Vec::new();
836        let mut field_tables: Vec<Vec<(u64, u32)>> = Vec::new();
837
838        for (_, _, max_dim_id, dim_bytes) in &field_data {
839            let mut table: Vec<(u64, u32)> = vec![(0, 0); *max_dim_id as usize];
840
841            // Process dimensions in order
842            for dim_id in 0..*max_dim_id {
843                if let Some(bytes) = dim_bytes.get(&dim_id) {
844                    table[dim_id as usize] = (current_offset, bytes.len() as u32);
845                    current_offset += bytes.len() as u64;
846                    all_data.extend_from_slice(bytes);
847                }
848                // else: table entry stays (0, 0) meaning dimension not present
849            }
850
851            field_tables.push(table);
852        }
853
854        // Write field headers and tables
855        for (i, (field_id, quantization, max_dim_id, _)) in field_data.iter().enumerate() {
856            output.write_u32::<LittleEndian>(*field_id)?;
857            output.write_u8(*quantization as u8)?;
858            output.write_u32::<LittleEndian>(*max_dim_id)?;
859
860            // Write table (direct indexed by dim_id)
861            for &(offset, length) in &field_tables[i] {
862                output.write_u64::<LittleEndian>(offset)?;
863                output.write_u32::<LittleEndian>(length)?;
864            }
865        }
866
867        // Write data
868        output.extend_from_slice(&all_data);
869
870        Ok(output)
871    }
872
873    /// Build positions file for phrase queries
874    ///
875    /// File format:
876    /// - Data only: concatenated serialized PositionPostingList
877    /// - Position offsets are stored in TermInfo (no separate header needed)
878    ///
879    /// Returns: (positions_data, term_key -> (offset, len) mapping)
880    #[allow(clippy::type_complexity)]
881    fn build_positions_file(&self) -> Result<(Vec<u8>, FxHashMap<Vec<u8>, (u64, u32)>)> {
882        use crate::structures::PositionPostingList;
883
884        let mut position_offsets: FxHashMap<Vec<u8>, (u64, u32)> = FxHashMap::default();
885
886        if self.position_index.is_empty() {
887            return Ok((Vec::new(), position_offsets));
888        }
889
890        // Collect and sort entries by key
891        let mut entries: Vec<(Vec<u8>, &PositionPostingListBuilder)> = self
892            .position_index
893            .iter()
894            .map(|(term_key, pos_list)| {
895                let term_str = self.term_interner.resolve(&term_key.term);
896                let mut key = Vec::with_capacity(4 + term_str.len());
897                key.extend_from_slice(&term_key.field.to_le_bytes());
898                key.extend_from_slice(term_str.as_bytes());
899                (key, pos_list)
900            })
901            .collect();
902
903        entries.sort_by(|a, b| a.0.cmp(&b.0));
904
905        // Serialize all position lists and track offsets
906        let mut output = Vec::new();
907
908        for (key, pos_builder) in entries {
909            // Convert builder to PositionPostingList
910            let mut pos_list = PositionPostingList::with_capacity(pos_builder.postings.len());
911            for (doc_id, positions) in &pos_builder.postings {
912                pos_list.push(*doc_id, positions.clone());
913            }
914
915            // Serialize and track offset
916            let offset = output.len() as u64;
917            pos_list.serialize(&mut output).map_err(crate::Error::Io)?;
918            let len = (output.len() as u64 - offset) as u32;
919
920            position_offsets.insert(key, (offset, len));
921        }
922
923        Ok((output, position_offsets))
924    }
925
926    /// Build postings from inverted index
927    ///
928    /// Uses parallel processing to serialize posting lists concurrently.
929    /// Position offsets are looked up and embedded in TermInfo.
930    fn build_postings(
931        &mut self,
932        position_offsets: &FxHashMap<Vec<u8>, (u64, u32)>,
933    ) -> Result<(Vec<u8>, Vec<u8>)> {
934        // Phase 1: Collect and sort term keys (parallel key generation)
935        // Key format: field_id (4 bytes) + term bytes
936        let mut term_entries: Vec<(Vec<u8>, &PostingListBuilder)> = self
937            .inverted_index
938            .iter()
939            .map(|(term_key, posting_list)| {
940                let term_str = self.term_interner.resolve(&term_key.term);
941                let mut key = Vec::with_capacity(4 + term_str.len());
942                key.extend_from_slice(&term_key.field.to_le_bytes());
943                key.extend_from_slice(term_str.as_bytes());
944                (key, posting_list)
945            })
946            .collect();
947
948        // Sort by key for SSTable ordering
949        term_entries.par_sort_unstable_by(|a, b| a.0.cmp(&b.0));
950
951        // Phase 2: Parallel serialization of posting lists
952        // Each term's posting list is serialized independently
953        let serialized: Vec<(Vec<u8>, SerializedPosting)> = term_entries
954            .into_par_iter()
955            .map(|(key, posting_builder)| {
956                // Build posting list from in-memory postings
957                let mut full_postings = PostingList::with_capacity(posting_builder.len());
958                for p in &posting_builder.postings {
959                    full_postings.push(p.doc_id, p.term_freq as u32);
960                }
961
962                // Build term info
963                let doc_ids: Vec<u32> = full_postings.iter().map(|p| p.doc_id).collect();
964                let term_freqs: Vec<u32> = full_postings.iter().map(|p| p.term_freq).collect();
965
966                // Don't inline if term has positions (inline format doesn't support position offsets)
967                let has_positions = position_offsets.contains_key(&key);
968                let result = if !has_positions
969                    && let Some(inline) = TermInfo::try_inline(&doc_ids, &term_freqs)
970                {
971                    SerializedPosting::Inline(inline)
972                } else {
973                    // Serialize to local buffer
974                    let mut posting_bytes = Vec::new();
975                    let block_list =
976                        crate::structures::BlockPostingList::from_posting_list(&full_postings)
977                            .expect("BlockPostingList creation failed");
978                    block_list
979                        .serialize(&mut posting_bytes)
980                        .expect("BlockPostingList serialization failed");
981                    SerializedPosting::External {
982                        bytes: posting_bytes,
983                        doc_count: full_postings.doc_count(),
984                    }
985                };
986
987                (key, result)
988            })
989            .collect();
990
991        // Phase 3: Sequential assembly (must be sequential for offset calculation)
992        let mut term_dict = Vec::new();
993        let mut postings = Vec::new();
994        let mut writer = SSTableWriter::<TermInfo>::new(&mut term_dict);
995
996        for (key, serialized_posting) in serialized {
997            let term_info = match serialized_posting {
998                SerializedPosting::Inline(info) => info,
999                SerializedPosting::External { bytes, doc_count } => {
1000                    let posting_offset = postings.len() as u64;
1001                    let posting_len = bytes.len() as u32;
1002                    postings.extend_from_slice(&bytes);
1003
1004                    // Look up position offset for this term
1005                    if let Some(&(pos_offset, pos_len)) = position_offsets.get(&key) {
1006                        TermInfo::external_with_positions(
1007                            posting_offset,
1008                            posting_len,
1009                            doc_count,
1010                            pos_offset,
1011                            pos_len,
1012                        )
1013                    } else {
1014                        TermInfo::external(posting_offset, posting_len, doc_count)
1015                    }
1016                }
1017            };
1018
1019            writer.insert(&key, &term_info)?;
1020        }
1021
1022        writer.finish()?;
1023        Ok((term_dict, postings))
1024    }
1025
1026    /// Build document store from streamed temp file (static method for parallel execution)
1027    ///
1028    /// Uses parallel processing to deserialize documents concurrently.
1029    fn build_store_parallel(
1030        store_path: &PathBuf,
1031        schema: &Schema,
1032        num_compression_threads: usize,
1033        compression_level: CompressionLevel,
1034    ) -> Result<Vec<u8>> {
1035        use super::store::EagerParallelStoreWriter;
1036
1037        let file = File::open(store_path)?;
1038        let mmap = unsafe { memmap2::Mmap::map(&file)? };
1039
1040        // Phase 1: Parse document boundaries (sequential, fast)
1041        let mut doc_ranges: Vec<(usize, usize)> = Vec::new();
1042        let mut offset = 0usize;
1043        while offset + 4 <= mmap.len() {
1044            let doc_len = u32::from_le_bytes([
1045                mmap[offset],
1046                mmap[offset + 1],
1047                mmap[offset + 2],
1048                mmap[offset + 3],
1049            ]) as usize;
1050            offset += 4;
1051
1052            if offset + doc_len > mmap.len() {
1053                break;
1054            }
1055
1056            doc_ranges.push((offset, doc_len));
1057            offset += doc_len;
1058        }
1059
1060        // Phase 2: Parallel deserialization of documents
1061        let docs: Vec<Document> = doc_ranges
1062            .into_par_iter()
1063            .filter_map(|(start, len)| {
1064                let doc_bytes = &mmap[start..start + len];
1065                super::store::deserialize_document(doc_bytes, schema).ok()
1066            })
1067            .collect();
1068
1069        // Phase 3: Write to store (compression is already parallel in EagerParallelStoreWriter)
1070        let mut store_data = Vec::new();
1071        let mut store_writer = EagerParallelStoreWriter::with_compression_level(
1072            &mut store_data,
1073            num_compression_threads,
1074            compression_level,
1075        );
1076
1077        for doc in &docs {
1078            store_writer.store(doc, schema)?;
1079        }
1080
1081        store_writer.finish()?;
1082        Ok(store_data)
1083    }
1084}
1085
1086impl Drop for SegmentBuilder {
1087    fn drop(&mut self) {
1088        // Cleanup temp files on drop
1089        let _ = std::fs::remove_file(&self.store_path);
1090    }
1091}