Skip to main content

ix/
builder.rs

1//! Index builder — the complete pipeline from files to .ix shard.
2//!
3//! Phase 1: Discovery (walk directory, respect .gitignore)
4//! Phase 2: Scan (mmap, check binary, extract trigrams, bloom filter)
5//! Phase 3: Serialize (write sections, compute CRCs, atomic rename)
6
7use crate::bloom::BloomFilter;
8use crate::decompress::maybe_decompress;
9use crate::error::{Error, Result};
10use crate::format::{
11    FileStatus, HEADER_SIZE, MAGIC, VERSION_MAJOR, VERSION_MINOR, flags, is_binary,
12};
13use crate::posting::{PostingEntry, PostingList};
14use crate::trigram::{Extractor, Trigram};
15use crate::varint;
16use ignore::WalkBuilder;
17use libc;
18use llmosafe::ResourceGuard;
19use memmap2::Mmap;
20use std::collections::{BinaryHeap, HashMap};
21use std::fs::{self, File};
22use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write};
23use std::path::{Path, PathBuf};
24use std::time::{Instant, SystemTime, UNIX_EPOCH};
25
26/// Index builder — orchestrates the full pipeline from file discovery to shard
27/// serialization.
28pub struct Builder {
29    root: PathBuf,
30    ix_dir: PathBuf,
31    file_count: u32,
32
33    // O(1) memory streaming writers for temporary file table and blooms.
34    // Wrapped in Option so they can be recreated per-build (clean-before-build pattern).
35    files_writer: Option<BufWriter<File>>,
36    blooms_writer: Option<BufWriter<File>>,
37    strings_writer: Option<BufWriter<File>>,
38
39    // Postings batching for external sort
40    postings: HashMap<Trigram, Vec<PostingEntry>>,
41    postings_count: usize,
42    temp_runs: Vec<PathBuf>,
43
44    extractor: Extractor,
45    stats: BuildStats,
46    decompress: bool,
47    resource_guard: Option<ResourceGuard>,
48    dead_ends: Vec<PathBuf>,
49    max_file_size: u64,
50    committed: bool,
51}
52
53/// Accumulated metrics collected during a build run.
54#[derive(Default, Debug)]
55pub struct BuildStats {
56    /// Number of files processed (text only, after filtering).
57    pub files_scanned: u64,
58    /// Number of files skipped because they were detected as binary.
59    pub files_skipped_binary: u64,
60    /// Number of files skipped because they exceeded the size limit.
61    pub files_skipped_size: u64,
62    /// Total number of raw bytes scanned across all files.
63    pub bytes_scanned: u64,
64    /// Number of distinct trigrams discovered across all files.
65    pub unique_trigrams: u64,
66}
67
68struct RunIterator {
69    file: BufReader<File>,
70}
71
72impl RunIterator {
73    fn new(path: &Path) -> Result<Self> {
74        let f = File::open(path)?;
75        Ok(Self {
76            file: BufReader::new(f),
77        })
78    }
79
80    fn next_trigram(&mut self) -> Result<Option<(Trigram, Vec<PostingEntry>)>> {
81        let mut tri_buf = [0u8; 4];
82        if let Err(e) = self.file.read_exact(&mut tri_buf) {
83            if e.kind() == std::io::ErrorKind::UnexpectedEof {
84                return Ok(None);
85            }
86            return Err(e.into());
87        }
88        let tri = u32::from_le_bytes(tri_buf);
89
90        let mut len_buf = [0u8; 4];
91        self.file.read_exact(&mut len_buf)?;
92        let entries_len = usize::try_from(u32::from_le_bytes(len_buf)).unwrap_or(0);
93
94        let mut entries = Vec::with_capacity(entries_len);
95        for _ in 0..entries_len {
96            self.file.read_exact(&mut len_buf)?;
97            let file_id = u32::from_le_bytes(len_buf);
98
99            self.file.read_exact(&mut len_buf)?;
100            let offsets_len = usize::try_from(u32::from_le_bytes(len_buf)).unwrap_or(0);
101
102            let mut offsets = Vec::with_capacity(offsets_len);
103            for _ in 0..offsets_len {
104                self.file.read_exact(&mut len_buf)?;
105                offsets.push(u32::from_le_bytes(len_buf));
106            }
107            entries.push(PostingEntry { file_id, offsets });
108        }
109
110        Ok(Some((tri, entries)))
111    }
112}
113
114#[derive(Eq, PartialEq)]
115struct MergeItem {
116    tri: Trigram,
117    run_idx: usize,
118}
119
120impl PartialOrd for MergeItem {
121    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
122        Some(self.cmp(other))
123    }
124}
125
126impl Ord for MergeItem {
127    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
128        other.tri.cmp(&self.tri) // Min-heap
129    }
130}
131
132#[allow(clippy::as_conversions)] // binary format: usize→u32/u16 for index encoding
133#[allow(clippy::indexing_slicing)] // binary format: fixed-size buffer ops
134impl Builder {
135    /// Creates a new builder for the given root directory.
136    ///
137    /// # Errors
138    ///
139    /// Returns an error if the `.ix` directory cannot be created or temp files
140    /// cannot be opened.
141    pub fn new(root: &Path) -> Result<Self> {
142        let ix_dir = root.join(".ix");
143        fs::create_dir_all(&ix_dir)?;
144
145        Ok(Self {
146            root: root.to_owned(),
147            ix_dir,
148            file_count: 0,
149            files_writer: None,
150            blooms_writer: None,
151            strings_writer: None,
152            postings: HashMap::new(),
153            postings_count: 0,
154            temp_runs: Vec::new(),
155            extractor: Extractor::new(),
156            stats: BuildStats::default(),
157            decompress: false,
158            resource_guard: None,
159            dead_ends: Vec::new(),
160            max_file_size: 100 * 1024 * 1024,
161            committed: false,
162        })
163    }
164
165    /// Attach a [`ResourceGuard`] for memory-pressure-driven flush.
166    #[must_use]
167    pub const fn with_resource_guard(mut self, guard: ResourceGuard) -> Self {
168        self.resource_guard = Some(guard);
169        self
170    }
171
172    /// Enable or disable transparent decompression of archives during
173    /// scanning.
174    pub const fn set_decompress(&mut self, decompress: bool) {
175        self.decompress = decompress;
176    }
177
178    /// Set the maximum file size to index (0 = unlimited). Default: 100 MB.
179    pub const fn set_max_file_size(&mut self, max_bytes: u64) {
180        self.max_file_size = max_bytes;
181    }
182
183    /// Initialize temporary files and writers for building.
184    ///
185    /// Called at start of each `build()` to ensure fresh file handles.
186    /// This is the core of the "clean-before-build" pattern: temp files
187    /// are BUILD ARTIFACTS, not struct state — created fresh each build,
188    /// cleaned at NEXT build start, never deleted mid-lifecycle.
189    ///
190    /// # Errors
191    ///
192    /// Returns an error if temp files cannot be created.
193    fn init_writers(&mut self) -> Result<()> {
194        let files_tmp = self.ix_dir.join("shard.ix.tmp.files");
195        let blooms_tmp = self.ix_dir.join("shard.ix.tmp.blooms");
196        let strings_tmp = self.ix_dir.join("shard.ix.tmp.strings");
197
198        self.files_writer = Some(BufWriter::new(File::create(&files_tmp)?));
199        self.blooms_writer = Some(BufWriter::new(File::create(&blooms_tmp)?));
200        let mut strings_writer = BufWriter::new(File::create(&strings_tmp)?);
201
202        // Initialize strings table header (10 bytes total):
203        // version(u32) + size(u16) + count(u16) + padding(2)
204        strings_writer.write_all(&1u32.to_le_bytes())?; // version
205        strings_writer.write_all(&0u16.to_le_bytes())?; // size placeholder
206        strings_writer.write_all(&0u16.to_le_bytes())?; // count
207        strings_writer.write_all(&[0u8; 2])?; // padding
208
209        self.strings_writer = Some(strings_writer);
210        Ok(())
211    }
212
213    /// Clean up old temporary files from a previous build.
214    ///
215    /// Called at start of `build()` to release disk space before
216    /// allocating new temp files. On Linux, deleting a file while a
217    /// process holds an open FD keeps the inode alive; dropping the
218    /// old writers first ensures inodes are released.
219    fn cleanup_old_temp_files(&mut self) {
220        // Drop writers first to release inode references on Linux
221        self.files_writer = None;
222        self.blooms_writer = None;
223        self.strings_writer = None;
224
225        let patterns = [
226            "shard.ix.tmp.files",
227            "shard.ix.tmp.blooms",
228            "shard.ix.tmp.strings",
229            "shard.ix.tmp",
230            "shard.ix.bak",
231        ];
232
233        for pattern in &patterns {
234            let path = self.ix_dir.join(pattern);
235            if path.exists() {
236                let _ = fs::remove_file(&path);
237            }
238        }
239
240        if let Ok(entries) = fs::read_dir(&self.ix_dir) {
241            for entry in entries.flatten() {
242                let name = entry.file_name().to_string_lossy().into_owned();
243                if name.starts_with("shard.ix.run.") || name.starts_with("shard.ix.merged.") {
244                    let _ = fs::remove_file(entry.path());
245                }
246            }
247        }
248    }
249    /// Helper to get mutable writer reference with proper error handling.
250    ///
251    /// Returns an error if the writer is not initialized (violates clean-before-build contract).
252    fn get_writer<'a, T>(writer: &'a mut Option<T>, context: &'static str) -> Result<&'a mut T> {
253        writer.as_mut().ok_or_else(|| {
254        Error::Io(std::io::Error::other(format!(
255            "Builder invariant violated: {context} not initialized (clean-before-build contract)"
256        )))
257        })
258    }
259
260    fn flush_run(&mut self) -> Result<()> {
261        if self.postings.is_empty() {
262            return Ok(());
263        }
264        let old_postings = std::mem::take(&mut self.postings);
265        let mut sorted: Vec<_> = old_postings.into_iter().collect();
266        sorted.sort_unstable_by_key(|(t, _)| *t);
267
268        let run_path = self
269            .ix_dir
270            .join(format!("shard.ix.run.{}", self.temp_runs.len()));
271        let mut f = BufWriter::new(File::create(&run_path)?);
272
273        for (tri, entries) in sorted {
274            f.write_all(&tri.to_le_bytes())?;
275            f.write_all(&u32::try_from(entries.len()).unwrap_or(0).to_le_bytes())?;
276            for entry in entries {
277                f.write_all(&entry.file_id.to_le_bytes())?;
278                f.write_all(
279                    &u32::try_from(entry.offsets.len())
280                        .unwrap_or(0)
281                        .to_le_bytes(),
282                )?;
283                for off in entry.offsets {
284                    f.write_all(&off.to_le_bytes())?;
285                }
286            }
287        }
288        f.flush()?;
289
290        self.temp_runs.push(run_path);
291        self.postings_count = 0;
292        Ok(())
293    }
294
295    /// Build or rebuild the index from scratch.
296    ///
297    /// # Errors
298    ///
299    /// Returns an error if the build process fails (I/O, disk space, etc.).
300    pub fn build(&mut self) -> Result<PathBuf> {
301        // Upfront disk space check: estimate required bytes before any I/O.
302        // === Clean-before-build: release old temp files + create fresh writers ===
303        // This fixes the stale FD bug where serialize() deletes temp files but
304        // Builder keeps BufWriter handles pointing to deleted inodes.
305        // On Linux, dropping the writers releases the inode references first.
306        self.cleanup_old_temp_files();
307        self.init_writers()?;
308
309        // Peak overhead is ~3× existing shard (old + tmp + bak + runs).
310        // For first builds, use a 200 MB floor.
311        if let Ok(free) = Self::free_bytes_at(&self.ix_dir) {
312            let existing_shard_size =
313                fs::metadata(self.ix_dir.join("shard.ix")).map_or(0, |m| m.len());
314            let required = if existing_shard_size > 0 {
315                existing_shard_size.saturating_mul(3)
316            } else {
317                200 * 1024 * 1024 // 200 MB floor for first builds
318            };
319            if free < required {
320                return Err(Error::Io(std::io::Error::other(format!(
321                    "insufficient disk space: {} MB free, need ≥{} MB (path: {})",
322                    free / 1024 / 1024,
323                    required / 1024 / 1024,
324                    self.ix_dir.display(),
325                ))));
326            }
327        }
328
329        // Cleanup old intermediate shard files before building
330        if self.ix_dir.exists()
331            && let Ok(entries) = std::fs::read_dir(&self.ix_dir)
332        {
333            for entry in entries.flatten() {
334                let name = entry.file_name();
335                let name_str = name.to_string_lossy();
336                if (name_str.starts_with("shard.ix.run.")
337                    || name_str.starts_with("shard.ix.merged."))
338                    && let Err(e) = std::fs::remove_file(entry.path())
339                {
340                    tracing::warn!("Failed to cleanup shard file {}: {}", name_str, e);
341                }
342            }
343        }
344
345        let start = Instant::now();
346        let root = self.root.clone();
347
348        // LLMOSafe Formal Law: Sensitive filesystem traversal (Root)
349        if root.to_string_lossy() == "/" {
350            tracing::warn!(
351                "LLMOSafe Advisory: Indexing root filesystem. Ensure adequate resource guards are in place."
352            );
353        }
354
355        let walker = WalkBuilder::new(&root)
356            .hidden(false)
357            .git_ignore(true)
358            .git_global(true)
359            .git_exclude(true)
360            .require_git(false)
361            .add_custom_ignore_filename(".ixignore")
362            .filter_entry(move |entry| {
363                let path = entry.path();
364                let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
365
366                if entry.file_type().is_some_and(|t| t.is_dir())
367                    && (name == "lost+found" || name == ".git" || name == ".ix")
368                {
369                    return false;
370                }
371
372                if entry.file_type().is_some_and(|t| t.is_file())
373                    && (name == "shard.ix"
374                        || name == "shard.ix.tmp"
375                        || name.starts_with("shard.ix."))
376                {
377                    return false;
378                }
379
380                if entry.file_type().is_some_and(|t| t.is_file()) {
381                    let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
382                    match ext {
383                        "so" | "o" | "dylib" | "a" | "dll" | "exe" | "pyc" | "jpg" | "png"
384                        | "gif" | "mp4" | "mp3" | "pdf" | "zip" | "7z" | "rar" | "sqlite"
385                        | "db" | "bin" => return false,
386                        _ => {}
387                    }
388                    if name.ends_with(".tar.gz") {
389                        return false;
390                    }
391                }
392                true
393            })
394            .build();
395
396        let mut files_processed = 0u64;
397        for entry_res in walker {
398            let entry = match entry_res {
399                Ok(e) => e,
400                Err(e) => {
401                    // Handle KernelError::BacktrackSignaled (-7) during the walk
402                    let backtrack_path = match &e {
403                        ignore::Error::Io(io_err) if io_err.raw_os_error() == Some(-7) => {
404                            Some(None)
405                        }
406                        ignore::Error::WithPath { path, err } => {
407                            if let ignore::Error::Io(io_err) = err.as_ref() {
408                                if io_err.raw_os_error() == Some(-7) {
409                                    Some(Some(path.clone()))
410                                } else {
411                                    None
412                                }
413                            } else {
414                                None
415                            }
416                        }
417                        _ => None,
418                    };
419
420                    if let Some(path_opt) = backtrack_path {
421                        tracing::warn!(
422                            "Immune Memory Triggered: Skipping path due to backtrack signal."
423                        );
424                        if let Some(path) = path_opt {
425                            self.dead_ends.push(path);
426                        }
427                    }
428                    continue;
429                }
430            };
431
432            if entry.file_type().is_some_and(|t| t.is_file()) {
433                self.process_file(entry.path())?;
434                files_processed += 1;
435
436                // Resource Guard Check: check every 250 files to prevent OOM
437                // allow: manual_is_multiple_of — MSRV 1.85 compat; is_multiple_of not available
438                #[allow(clippy::manual_is_multiple_of)]
439                if files_processed % 250 == 0 {
440                    if let Some(guard) = &self.resource_guard {
441                        if let Err(_err) = guard.check() {
442                            eprintln!(
443                                "ixd: memory ceiling reached... flushing intermediate chunk ({files_processed} files processed)"
444                            );
445                            self.flush_run()?;
446                        }
447                    } else {
448                        // Fallback to manual RSS limit if no formal guard provided
449                        if let Ok(rss) = Self::current_rss_bytes()
450                            && rss > 512 * 1024 * 1024
451                        {
452                            eprintln!(
453                                "ixd: RSS ceiling reached ({} MB) after {} files — flushing intermediate chunk",
454                                rss / 1024 / 1024,
455                                files_processed
456                            );
457                            self.flush_run()?;
458                        }
459                    }
460                }
461            }
462        }
463
464        let output_path = self.serialize()?;
465        tracing::info!("Build completed in {:?}: {:?}", start.elapsed(), self.stats);
466        Ok(output_path)
467    }
468
469    /// Update the index for changed files (currently does a full rebuild).
470    ///
471    /// # Errors
472    ///
473    /// Returns an error if the build process fails.
474    pub fn update(&mut self, _changed_files: &[PathBuf]) -> Result<PathBuf> {
475        self.build()
476    }
477
478    /// Number of files indexed so far (snapshot for progress reporting).
479    #[must_use]
480    pub const fn files_len(&self) -> usize {
481        self.file_count as usize
482    }
483
484    /// Number of unique trigrams accumulated so far.
485    #[must_use]
486    pub const fn trigrams_len(&self) -> usize {
487        self.stats.unique_trigrams as usize
488    }
489
490    /// Returns current process RSS in bytes by reading /proc/self/status.
491    fn current_rss_bytes() -> std::io::Result<u64> {
492        let status = std::fs::read_to_string("/proc/self/status")?;
493        for line in status.lines() {
494            if let Some(rest) = line.strip_prefix("VmRSS:") {
495                let kb: u64 = rest
496                    .split_whitespace()
497                    .next()
498                    .and_then(|s| s.parse().ok())
499                    .unwrap_or(0);
500                return Ok(kb * 1024);
501            }
502        }
503        Ok(0)
504    }
505
506    /// Returns free bytes available on the filesystem containing `path`.
507    fn free_bytes_at(path: &Path) -> std::io::Result<u64> {
508        use std::os::unix::ffi::OsStrExt;
509        let path_c = std::ffi::CString::new(path.as_os_str().as_bytes())
510            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;
511        let mut stat: libc::statvfs = unsafe { std::mem::zeroed() };
512        let ret = unsafe { libc::statvfs(path_c.as_ptr(), &raw mut stat) };
513        if ret != 0 {
514            return Err(std::io::Error::last_os_error());
515        }
516        #[allow(clippy::unnecessary_cast)]
517        Ok(stat.f_bavail as u64 * stat.f_frsize as u64)
518    }
519
520    fn cleanup_temp_files(&self) {
521        let paths = [
522            self.ix_dir.join("shard.ix.tmp.files"),
523            self.ix_dir.join("shard.ix.tmp.blooms"),
524            self.ix_dir.join("shard.ix.tmp.strings"),
525            self.ix_dir.join("shard.ix.tmp"),
526            self.ix_dir.join("shard.ix.bak"),
527        ];
528        for p in &paths {
529            if let Err(e) = fs::remove_file(p)
530                && e.kind() != std::io::ErrorKind::NotFound
531            {
532                tracing::warn!("Failed to cleanup temp file {}: {}", p.display(), e);
533            }
534        }
535        for run_path in &self.temp_runs {
536            if let Err(e) = fs::remove_file(run_path)
537                && e.kind() != std::io::ErrorKind::NotFound
538            {
539                tracing::warn!("Failed to cleanup temp run {}: {}", run_path.display(), e);
540            }
541        }
542    }
543
544    fn process_file(&mut self, path: &Path) -> Result<bool> {
545        let path_str = path.display().to_string();
546        // TOCTOU guard: file may have been deleted between walk and open
547        let metadata = match fs::metadata(path) {
548            Ok(m) => m,
549            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
550            Err(e) => return Err(e.into()),
551        };
552        let size = metadata.len();
553        let mtime = metadata
554            .modified()?
555            .duration_since(UNIX_EPOCH)
556            .map_or(0, |d| u64::try_from(d.as_nanos()).unwrap_or(0));
557
558        if self.max_file_size > 0 && size > self.max_file_size {
559            tracing::debug!("SKIP: file too large ({size} bytes): {path_str}");
560            self.stats.files_skipped_size += 1;
561            return Ok(false);
562        }
563
564        let file = match File::open(path) {
565            Ok(f) => f,
566            Err(e)
567                if e.kind() == std::io::ErrorKind::NotFound
568                    || e.kind() == std::io::ErrorKind::PermissionDenied =>
569            {
570                return Ok(false);
571            }
572            Err(e) => return Err(e.into()),
573        };
574        let mmap = unsafe { Mmap::map(&file)? };
575
576        let raw_data = if self.decompress {
577            if let Some(mut reader) = maybe_decompress(path, &mmap)? {
578                let mut buf = Vec::new();
579                let take_limit = if self.max_file_size > 0 {
580                    self.max_file_size
581                } else {
582                    100 * 1024 * 1024
583                };
584                reader.by_ref().take(take_limit).read_to_end(&mut buf)?;
585                std::borrow::Cow::Owned(buf)
586            } else {
587                std::borrow::Cow::Borrowed(&mmap[..])
588            }
589        } else {
590            std::borrow::Cow::Borrowed(&mmap[..])
591        };
592
593        let data = &raw_data[..];
594        if is_binary(data) {
595            tracing::debug!("SKIP: binary detection ({size} bytes): {path_str}");
596            self.stats.files_skipped_binary += 1;
597            return Ok(false);
598        }
599
600        let content_hash = xxhash_rust::xxh64::xxh64(data, 0);
601        let pairs = self.extractor.extract_with_offsets(data);
602
603        if pairs.is_empty() && !data.is_empty() {
604            tracing::debug!("SKIP: no trigrams extracted ({size} bytes): {path_str}");
605        }
606
607        let file_id = self.file_count;
608        self.file_count += 1;
609
610        let path_str = path.to_string_lossy();
611        let path_bytes = path_str.as_bytes();
612        let path_off = u32::try_from(
613            Self::get_writer(&mut self.strings_writer, "strings_writer")?.stream_position()?,
614        )
615        .unwrap_or(0);
616        let path_len = u16::try_from(path_bytes.len()).unwrap_or(0);
617
618        self.strings_writer
619            .as_mut()
620            .ok_or_else(|| Error::Io(std::io::Error::other("strings_writer not initialized")))?
621            .write_all(&0u16.to_le_bytes())?;
622        self.strings_writer
623            .as_mut()
624            .ok_or_else(|| Error::Io(std::io::Error::other("strings_writer not initialized")))?
625            .write_all(&path_len.to_le_bytes())?;
626        self.strings_writer
627            .as_mut()
628            .ok_or_else(|| Error::Io(std::io::Error::other("strings_writer not initialized")))?
629            .write_all(path_bytes)?;
630
631        let mut bloom = BloomFilter::new(256, 5);
632        let mut trigram_count = 0u32;
633
634        let mut i = 0;
635        while i < pairs.len() {
636            let tri = pairs[i].0;
637            let mut j = i + 1;
638            while j < pairs.len() && pairs[j].0 == tri {
639                j += 1;
640            }
641
642            let take_count = (j - i).min(10_000);
643            let offsets: Vec<u32> = pairs[i..i + take_count].iter().map(|p| p.1).collect();
644
645            bloom.insert(tri);
646            self.postings
647                .entry(tri)
648                .or_default()
649                .push(PostingEntry { file_id, offsets });
650            self.postings_count += take_count + 8;
651
652            trigram_count += 1;
653            i = j;
654        }
655
656        bloom.serialize(
657            self.blooms_writer
658                .as_mut()
659                .ok_or_else(|| Error::Io(std::io::Error::other("blooms_writer not initialized")))?,
660        )?;
661
662        let bloom_offset = u64::from(file_id)
663            .checked_mul(260)
664            .ok_or_else(|| Error::Config("file_id * 260 overflow".into()))?;
665        let bloom_offset_u32 = u32::try_from(bloom_offset)
666            .map_err(|_| Error::Config(format!("bloom_offset {bloom_offset} exceeds u32::MAX")))?;
667        self.files_writer
668            .as_mut()
669            .ok_or_else(|| Error::Io(std::io::Error::other("files_writer not initialized")))?
670            .write_all(&file_id.to_le_bytes())?;
671        self.files_writer
672            .as_mut()
673            .ok_or_else(|| Error::Io(std::io::Error::other("files_writer not initialized")))?
674            .write_all(&path_off.to_le_bytes())?;
675        self.files_writer
676            .as_mut()
677            .ok_or_else(|| Error::Io(std::io::Error::other("files_writer not initialized")))?
678            .write_all(&path_len.to_le_bytes())?;
679        self.files_writer
680            .as_mut()
681            .ok_or_else(|| Error::Io(std::io::Error::other("files_writer not initialized")))?
682            .write_all(&[FileStatus::Fresh as u8])?;
683        self.files_writer
684            .as_mut()
685            .ok_or_else(|| Error::Io(std::io::Error::other("files_writer not initialized")))?
686            .write_all(&[0u8])?;
687        self.files_writer
688            .as_mut()
689            .ok_or_else(|| Error::Io(std::io::Error::other("files_writer not initialized")))?
690            .write_all(&mtime.to_le_bytes())?;
691        self.files_writer
692            .as_mut()
693            .ok_or_else(|| Error::Io(std::io::Error::other("files_writer not initialized")))?
694            .write_all(&size.to_le_bytes())?;
695        self.files_writer
696            .as_mut()
697            .ok_or_else(|| Error::Io(std::io::Error::other("files_writer not initialized")))?
698            .write_all(&content_hash.to_le_bytes())?;
699        self.files_writer
700            .as_mut()
701            .ok_or_else(|| Error::Io(std::io::Error::other("files_writer not initialized")))?
702            .write_all(&trigram_count.to_le_bytes())?;
703        self.files_writer
704            .as_mut()
705            .ok_or_else(|| Error::Io(std::io::Error::other("files_writer not initialized")))?
706            .write_all(&bloom_offset_u32.to_le_bytes())?;
707        self.files_writer
708            .as_mut()
709            .ok_or_else(|| Error::Io(std::io::Error::other("files_writer not initialized")))?
710            .write_all(&[0u8; 4])?;
711
712        self.stats.files_scanned += 1;
713        self.stats.bytes_scanned += size;
714
715        if std::env::var("IX_DEBUG_BUILD").is_ok() {
716            eprintln!(
717                "IX-INDEXED: file_id={file_id} unique_trigrams={trigram_count} size={size}: {path_str}"
718            );
719        }
720
721        // Flush every 500k entries (~8MB peak RAM) to prevent unbounded HashMap growth.
722        // This was the RAM DDOS root cause in v0.1.1 — threshold was 5M (far too high).
723        if self.postings_count >= 500_000 {
724            if std::env::var("IX_DEBUG_BUILD").is_ok() {
725                eprintln!(
726                    "IX-FLUSH: postings_count={} after file_id={file_id}",
727                    self.postings_count
728                );
729            }
730            self.flush_run()?;
731        }
732
733        Ok(true)
734    }
735
736    fn serialize(&mut self) -> Result<PathBuf> {
737        self.flush_run()?;
738
739        self.files_writer
740            .as_mut()
741            .ok_or_else(|| Error::Io(std::io::Error::other("files_writer not initialized")))?
742            .flush()?;
743        self.blooms_writer
744            .as_mut()
745            .ok_or_else(|| Error::Io(std::io::Error::other("blooms_writer not initialized")))?
746            .flush()?;
747        self.strings_writer
748            .as_mut()
749            .ok_or_else(|| Error::Io(std::io::Error::other("strings_writer not initialized")))?
750            .flush()?;
751
752        // Hierarchical Merge to stay under ulimit
753        while self.temp_runs.len() > 128 {
754            let mut next_generation = Vec::new();
755            for chunk in self.temp_runs.chunks(128) {
756                let out_path = self.ix_dir.join(format!(
757                    "shard.ix.merged.{}.{}",
758                    next_generation.len(),
759                    SystemTime::now()
760                        .duration_since(UNIX_EPOCH)
761                        .map_err(|e| Error::Config(format!("time went backwards: {e}")))?
762                        .as_micros()
763                ));
764                Self::merge_to_run(chunk, &out_path)?;
765                next_generation.push(out_path);
766                for p in chunk {
767                    if let Err(e) = fs::remove_file(p) {
768                        tracing::warn!("Failed to cleanup temp run {}: {}", p.display(), e);
769                    }
770                }
771            }
772            self.temp_runs = next_generation;
773        }
774
775        let tmp_path = self.ix_dir.join("shard.ix.tmp");
776        let final_path = self.ix_dir.join("shard.ix");
777
778        let mut f = BufWriter::new(File::create(&tmp_path)?);
779        f.write_all(&[0u8; HEADER_SIZE])?;
780
781        let file_table_offset = Self::align_to_8(&mut f)?;
782        let mut files_reader = File::open(self.ix_dir.join("shard.ix.tmp.files"))?;
783        std::io::copy(&mut files_reader, &mut f)?;
784        let file_table_size = f.stream_position()? - file_table_offset;
785
786        Self::align_to_8(&mut f)?;
787        let posting_data_offset = f.stream_position()?;
788
789        let mut cdx_entries: Vec<(Trigram, u64, u32, u32)> = Vec::new();
790        let mut global_trigram_count = 0u32;
791
792        let mut runs = Vec::new();
793        for path in &self.temp_runs {
794            runs.push(RunIterator::new(path)?);
795        }
796
797        let mut heap = BinaryHeap::new();
798        let mut current_items = vec![None; runs.len()];
799
800        for (i, run) in runs.iter_mut().enumerate() {
801            if let Some(item) = run.next_trigram()? {
802                heap.push(MergeItem {
803                    tri: item.0,
804                    run_idx: i,
805                });
806                current_items[i] = Some(item);
807            }
808        }
809
810        let mut current_tri: Option<Trigram> = None;
811        let mut merged_entries: Vec<PostingEntry> = Vec::new();
812
813        while let Some(MergeItem { tri, run_idx }) = heap.pop() {
814            if Some(tri) != current_tri {
815                if let Some(t) = current_tri {
816                    let cdx_entry = Self::write_merged_posting(
817                        &mut f,
818                        t,
819                        posting_data_offset,
820                        &mut merged_entries,
821                    )?;
822                    cdx_entries.push(cdx_entry);
823                    global_trigram_count += 1;
824                    merged_entries.clear();
825                }
826                current_tri = Some(tri);
827            }
828
829            let item = current_items
830                .get_mut(run_idx)
831                .ok_or(Error::Config("run_idx out of bounds".into()))?
832                .take()
833                .ok_or(Error::Config("current item is None".into()))?;
834            merged_entries.extend(item.1);
835
836            if let Some(next_item) = runs
837                .get_mut(run_idx)
838                .ok_or(Error::Config("run_idx out of bounds".into()))?
839                .next_trigram()?
840            {
841                heap.push(MergeItem {
842                    tri: next_item.0,
843                    run_idx,
844                });
845                *current_items
846                    .get_mut(run_idx)
847                    .ok_or(Error::Config("run_idx out of bounds".into()))? = Some(next_item);
848            }
849        }
850
851        if let Some(t) = current_tri {
852            let cdx_entry =
853                Self::write_merged_posting(&mut f, t, posting_data_offset, &mut merged_entries)?;
854            cdx_entries.push(cdx_entry);
855            global_trigram_count += 1;
856        }
857
858        self.stats.unique_trigrams = u64::from(global_trigram_count);
859        let posting_data_size = f.stream_position()? - posting_data_offset;
860
861        Self::align_to_8(&mut f)?;
862        let trigram_table_offset = f.stream_position()?;
863
864        // CDX encode: delta + varint + ZSTD per block
865        let cdx_block_index = Self::write_cdx_blocks(&mut f, &cdx_entries)?;
866        let trigram_table_size = f.stream_position()? - trigram_table_offset;
867
868        Self::align_to_8(&mut f)?;
869        let cdx_block_index_offset = f.stream_position()?;
870        for entry in &cdx_block_index {
871            f.write_all(&entry.0.to_le_bytes())?;
872            f.write_all(&entry.1.to_le_bytes())?;
873        }
874        // Sentinel entry
875        f.write_all(&u32::MAX.to_le_bytes())?;
876        f.write_all(&(trigram_table_offset + trigram_table_size).to_le_bytes())?;
877        let cdx_block_index_size = f.stream_position()? - cdx_block_index_offset;
878
879        Self::align_to_8(&mut f)?;
880        let bloom_offset = f.stream_position()?;
881        let mut blooms_reader = File::open(self.ix_dir.join("shard.ix.tmp.blooms"))?;
882        std::io::copy(&mut blooms_reader, &mut f)?;
883        let bloom_size = f.stream_position()? - bloom_offset;
884
885        Self::align_to_8(&mut f)?;
886        let string_pool_offset = f.stream_position()?;
887        let mut strings_reader = File::open(self.ix_dir.join("shard.ix.tmp.strings"))?;
888        std::io::copy(&mut strings_reader, &mut f)?;
889        let string_pool_size = f.stream_position()? - string_pool_offset;
890
891        let name_index_offset = f.stream_position()?;
892        let name_index_size = 0u64;
893
894        let created_at = u64::try_from(
895            SystemTime::now()
896                .duration_since(UNIX_EPOCH)
897                .map_err(|e| Error::Config(format!("time went backwards: {e}")))?
898                .as_micros(),
899        )
900        .unwrap_or(0);
901        let mut header_bytes = [0u8; HEADER_SIZE];
902        header_bytes[0..4].copy_from_slice(&MAGIC);
903        header_bytes[0x04..0x06].copy_from_slice(&VERSION_MAJOR.to_le_bytes());
904        header_bytes[0x06..0x08].copy_from_slice(&VERSION_MINOR.to_le_bytes());
905        header_bytes[0x08..0x10].copy_from_slice(
906            &(flags::HAS_BLOOM_FILTERS
907                | flags::HAS_CONTENT_HASHES
908                | flags::POSTING_LISTS_CHECKSUMMED
909                | flags::HAS_CDX_INDEX)
910                .to_le_bytes(),
911        );
912        header_bytes[0x10..0x18].copy_from_slice(&created_at.to_le_bytes());
913        header_bytes[0x18..0x20].copy_from_slice(&self.stats.bytes_scanned.to_le_bytes());
914        header_bytes[0x20..0x24].copy_from_slice(&self.file_count.to_le_bytes());
915        header_bytes[0x24..0x28].copy_from_slice(&(global_trigram_count).to_le_bytes());
916        header_bytes[0x28..0x30].copy_from_slice(&file_table_offset.to_le_bytes());
917        header_bytes[0x30..0x38].copy_from_slice(&file_table_size.to_le_bytes());
918        header_bytes[0x38..0x40].copy_from_slice(&trigram_table_offset.to_le_bytes());
919        header_bytes[0x40..0x48].copy_from_slice(&trigram_table_size.to_le_bytes());
920        header_bytes[0x48..0x50].copy_from_slice(&posting_data_offset.to_le_bytes());
921        header_bytes[0x50..0x58].copy_from_slice(&posting_data_size.to_le_bytes());
922        header_bytes[0x58..0x60].copy_from_slice(&bloom_offset.to_le_bytes());
923        header_bytes[0x60..0x68].copy_from_slice(&bloom_size.to_le_bytes());
924        header_bytes[0x68..0x70].copy_from_slice(&string_pool_offset.to_le_bytes());
925        header_bytes[0x70..0x78].copy_from_slice(&string_pool_size.to_le_bytes());
926        header_bytes[0x78..0x80].copy_from_slice(&name_index_offset.to_le_bytes());
927        header_bytes[0x80..0x88].copy_from_slice(&name_index_size.to_le_bytes());
928        header_bytes[0x88..0x90].copy_from_slice(&cdx_block_index_offset.to_le_bytes());
929        header_bytes[0x90..0x98].copy_from_slice(&cdx_block_index_size.to_le_bytes());
930
931        let crc = crc32c::crc32c(&header_bytes[0..0xF8]);
932        header_bytes[0xF8..0xFC].copy_from_slice(&crc.to_le_bytes());
933
934        f.seek(SeekFrom::Start(0))?;
935        f.write_all(&header_bytes)?;
936        f.flush()?;
937        drop(f);
938
939        // Atomic swap: backup old index, rename new to final
940        let backup_path = self.ix_dir.join("shard.ix.bak");
941        let old_index_exists = final_path.exists();
942        if old_index_exists {
943            // Remove old backup if exists
944            let _ = fs::remove_file(&backup_path);
945            // Backup current index
946            if let Err(e) = fs::rename(&final_path, &backup_path) {
947                tracing::warn!("Failed to backup existing index: {}", e);
948            }
949        }
950        fs::rename(&tmp_path, &final_path)?;
951        self.committed = true;
952        // Remove backup after successful rename
953        if old_index_exists {
954            let _ = fs::remove_file(&backup_path);
955        }
956
957        let _ = fs::remove_file(self.ix_dir.join("shard.ix.tmp.files"));
958        let _ = fs::remove_file(self.ix_dir.join("shard.ix.tmp.blooms"));
959        let _ = fs::remove_file(self.ix_dir.join("shard.ix.tmp.strings"));
960        for path in &self.temp_runs {
961            if let Err(e) = fs::remove_file(path) {
962                tracing::warn!("Failed to cleanup temp run {}: {}", path.display(), e);
963            }
964        }
965        self.temp_runs.clear();
966
967        Ok(final_path)
968    }
969
970    fn merge_to_run(run_paths: &[PathBuf], out_path: &Path) -> Result<()> {
971        let mut runs = Vec::new();
972        for path in run_paths {
973            runs.push(RunIterator::new(path)?);
974        }
975        let mut heap = BinaryHeap::new();
976        let mut current_items = vec![None; runs.len()];
977        for (i, run) in runs.iter_mut().enumerate() {
978            if let Some(item) = run.next_trigram()? {
979                heap.push(MergeItem {
980                    tri: item.0,
981                    run_idx: i,
982                });
983                current_items[i] = Some(item);
984            }
985        }
986        let mut out = BufWriter::new(File::create(out_path)?);
987        let mut current_tri: Option<Trigram> = None;
988        let mut merged_entries: Vec<PostingEntry> = Vec::new();
989        while let Some(MergeItem { tri, run_idx }) = heap.pop() {
990            if Some(tri) != current_tri {
991                if let Some(t) = current_tri {
992                    Self::write_run_entry(&mut out, t, &mut merged_entries)?;
993                    merged_entries.clear();
994                }
995                current_tri = Some(tri);
996            }
997            let item = current_items[run_idx].take().ok_or_else(|| {
998                Error::Config(format!(
999                    "merge invariant broken: no item at run index {run_idx}"
1000                ))
1001            })?;
1002            merged_entries.extend(item.1);
1003            if let Some(next_item) = runs[run_idx].next_trigram()? {
1004                heap.push(MergeItem {
1005                    tri: next_item.0,
1006                    run_idx,
1007                });
1008                current_items[run_idx] = Some(next_item);
1009            }
1010        }
1011        if let Some(t) = current_tri {
1012            Self::write_run_entry(&mut out, t, &mut merged_entries)?;
1013        }
1014        out.flush()?;
1015        Ok(())
1016    }
1017
1018    fn write_run_entry<W: Write>(
1019        w: &mut W,
1020        tri: Trigram,
1021        entries: &mut [PostingEntry],
1022    ) -> Result<()> {
1023        entries.sort_by_key(|e| e.file_id);
1024        w.write_all(&tri.to_le_bytes())?;
1025        w.write_all(&(entries.len() as u32).to_le_bytes())?;
1026        for entry in entries {
1027            w.write_all(&entry.file_id.to_le_bytes())?;
1028            w.write_all(&(entry.offsets.len() as u32).to_le_bytes())?;
1029            for off in &entry.offsets {
1030                w.write_all(&off.to_le_bytes())?;
1031            }
1032        }
1033        Ok(())
1034    }
1035
1036    fn write_merged_posting<W: Write + Seek>(
1037        f: &mut W,
1038        tri: Trigram,
1039        base_off: u64,
1040        entries: &mut [PostingEntry],
1041    ) -> Result<(Trigram, u64, u32, u32)> {
1042        entries.sort_by_key(|e| e.file_id);
1043        let count = entries.len() as u32;
1044        let list = PostingList {
1045            entries: entries.to_vec(),
1046        };
1047        let encoded = list.encode()?;
1048        let offset = f.stream_position()? - base_off;
1049        f.write_all(&encoded)?;
1050        let abs_off = base_off + offset;
1051        Ok((tri, abs_off, encoded.len() as u32, count))
1052    }
1053
1054    fn write_cdx_blocks<W: Write + Seek>(
1055        f: &mut W,
1056        cdx_entries: &[(Trigram, u64, u32, u32)],
1057    ) -> Result<Vec<(u32, u64)>> {
1058        let mut block_index = Vec::new();
1059        for chunk in cdx_entries.chunks(crate::format::CDX_BLOCK_SIZE) {
1060            let first_key = chunk[0].0;
1061            let block_offset = f.stream_position()?;
1062            block_index.push((first_key, block_offset));
1063
1064            let mut buf = Vec::new();
1065            varint::encode(u64::try_from(chunk.len()).unwrap_or(0), &mut buf);
1066            let mut last_key = 0u32;
1067            for &(tri, posting_offset, posting_length, doc_frequency) in chunk {
1068                varint::encode(u64::from(tri - last_key), &mut buf);
1069                last_key = tri;
1070                varint::encode(posting_offset, &mut buf);
1071                varint::encode(u64::from(posting_length), &mut buf);
1072                varint::encode(u64::from(doc_frequency), &mut buf);
1073            }
1074
1075            let compressed = zstd::encode_all(&buf[..], PostingList::ZSTD_COMPRESSION_LEVEL)
1076                .map_err(|e| Error::Config(format!("cdx zstd encode: {e}")))?;
1077            f.write_all(&compressed)?;
1078        }
1079        Ok(block_index)
1080    }
1081
1082    fn align_to_8<W: Write + Seek>(mut w: W) -> std::io::Result<u64> {
1083        let pos = w.stream_position()?;
1084        let padding = (8 - (pos % 8)) % 8;
1085        if padding > 0 {
1086            w.write_all(&vec![0u8; padding as usize])?;
1087        }
1088        w.stream_position()
1089    }
1090}
1091
1092impl Drop for Builder {
1093    fn drop(&mut self) {
1094        if !self.committed {
1095            self.cleanup_temp_files();
1096        }
1097    }
1098}