vera2-core 0.12.16-aristoddle.1

Core engine for Vera: parsing, indexing, retrieval, storage, and embedding
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
//! Tantivy-based BM25 full-text index over chunk content.
//!
//! Provides keyword search with BM25 scoring. Indexes chunk content,
//! symbol names, and file paths for comprehensive text search.

use std::path::Path;

use anyhow::{Context, Result};
use tantivy::collector::TopDocs;
use tantivy::query::QueryParser;
use tantivy::schema::{
    IndexRecordOption, STORED, STRING, Schema, TextFieldIndexing, TextOptions, Value,
};
use tantivy::tokenizer::{LowerCaser, RemoveLongFilter, SimpleTokenizer, TextAnalyzer};
use tantivy::{Index, IndexWriter, ReloadPolicy, TantivyDocument, doc};

use crate::chunk_text;

/// Tantivy-backed BM25 full-text search index.
pub struct Bm25Index {
    index: Index,
    schema: Bm25Schema,
    reader: tantivy::IndexReader,
}

/// Pre-resolved schema field handles for efficient access.
#[derive(Clone)]
struct Bm25Schema {
    schema: Schema,
    chunk_id: tantivy::schema::Field,
    file_path: tantivy::schema::Field,
    filename: tantivy::schema::Field,
    path_tokens: tantivy::schema::Field,
    content: tantivy::schema::Field,
    symbol_name: tantivy::schema::Field,
    language: tantivy::schema::Field,
}

/// A single BM25 search result.
#[derive(Debug, Clone)]
pub struct Bm25SearchResult {
    /// The chunk ID.
    pub chunk_id: String,
    /// BM25 relevance score (higher is better).
    pub score: f32,
}

/// Writer heap size for Tantivy (50MB).
const WRITER_HEAP_SIZE: usize = 50_000_000;

/// Custom tokenizer name: SimpleTokenizer + LowerCaser + English stemmer.
///
/// English stemming lets "dependency" match "dependencies", "configure" match
/// "configuration", etc. This is standard search-engine behaviour and fixes
/// a large class of recall failures for natural-language queries.
const STEMMED_TOKENIZER: &str = "code_en_stem";

fn register_stemmed_tokenizer(index: &Index) {
    let analyzer = TextAnalyzer::builder(SimpleTokenizer::default())
        .filter(RemoveLongFilter::limit(40))
        .filter(LowerCaser)
        .filter(tantivy::tokenizer::Stemmer::new(
            tantivy::tokenizer::Language::English,
        ))
        .build();
    index.tokenizers().register(STEMMED_TOKENIZER, analyzer);
}

impl Bm25Index {
    /// Open (or create) a BM25 index at the given directory path.
    pub fn open(index_dir: &Path) -> Result<Self> {
        let schema = build_schema();

        let index = if index_dir.exists() && index_dir.join("meta.json").exists() {
            Index::open_in_dir(index_dir)
                .with_context(|| format!("failed to open BM25 index: {}", index_dir.display()))?
        } else {
            std::fs::create_dir_all(index_dir)
                .with_context(|| format!("failed to create BM25 dir: {}", index_dir.display()))?;
            Index::create_in_dir(index_dir, schema.schema.clone())
                .with_context(|| format!("failed to create BM25 index: {}", index_dir.display()))?
        };

        register_stemmed_tokenizer(&index);
        let reader = index
            .reader_builder()
            .reload_policy(ReloadPolicy::Manual)
            .try_into()
            .context("failed to create BM25 reader")?;
        Ok(Self {
            index,
            schema,
            reader,
        })
    }

    /// Create an in-memory BM25 index (useful for testing).
    pub fn open_in_memory() -> Result<Self> {
        let schema = build_schema();
        let index = Index::create_in_ram(schema.schema.clone());
        register_stemmed_tokenizer(&index);
        let reader = index
            .reader_builder()
            .reload_policy(ReloadPolicy::Manual)
            .try_into()
            .context("failed to create BM25 reader")?;
        Ok(Self {
            index,
            schema,
            reader,
        })
    }

    /// Insert a batch of documents into the index.
    ///
    /// Each document is a tuple of (chunk_id, file_path, content, symbol_name, language).
    ///
    /// The per-call cost is the writer lifecycle: allocating a
    /// `WRITER_HEAP_SIZE` writer, committing a segment and joining the merge
    /// threads costs on the order of tens of milliseconds regardless of batch
    /// size. Incremental updates batch many files into one call; full builds
    /// must use [`Bm25Index::begin_bulk_build`] instead of calling this once
    /// per window.
    pub fn insert_batch(&self, docs: &[Bm25Document<'_>]) -> Result<()> {
        let mut writer: IndexWriter = self
            .index
            .writer(WRITER_HEAP_SIZE)
            .context("failed to create BM25 index writer")?;

        for doc_data in docs {
            add_document(&writer, &self.schema, doc_data)?;
        }

        writer.commit().context("failed to commit BM25 index")?;
        // Wait for merging to complete.
        writer
            .wait_merging_threads()
            .map_err(|e| anyhow::anyhow!("BM25 merge failed: {e}"))?;

        Ok(())
    }

    /// Open a long-lived writer for a full-index build.
    ///
    /// A windowed build would otherwise pay the writer lifecycle (creation,
    /// commit, merge-thread join) once per window. The bulk writer amortizes
    /// all three: documents flow in continuously, Tantivy merges segments in
    /// the background while the pipeline parses and embeds the next window,
    /// and [`Bm25BulkWriter::finish`] commits exactly once. Memory stays
    /// bounded by the writer heap because Tantivy flushes segments as the
    /// heap fills, same as with per-window writers.
    pub fn begin_bulk_build(&self) -> Result<Bm25BulkWriter> {
        let writer = self
            .index
            .writer(WRITER_HEAP_SIZE)
            .context("failed to create BM25 bulk writer")?;
        Ok(Bm25BulkWriter {
            writer,
            schema: self.schema.clone(),
        })
    }

    /// Insert all chunks as BM25 documents in one batch.
    pub fn insert_chunks(&self, chunks: &[crate::types::Chunk]) -> Result<()> {
        let lang_strings: Vec<String> = chunks.iter().map(|c| c.language.to_string()).collect();
        let docs: Vec<Bm25Document<'_>> = chunks
            .iter()
            .zip(lang_strings.iter())
            .map(|(c, lang)| Bm25Document {
                chunk_id: &c.id,
                file_path: &c.file_path,
                content: &c.content,
                symbol_name: c.symbol_name.as_deref(),
                language: lang,
            })
            .collect();
        self.insert_batch(&docs)
    }

    /// Search the index with a text query.
    ///
    /// Searches across content and symbol_name fields.
    pub fn search(&self, query_text: &str, limit: usize) -> Result<Vec<Bm25SearchResult>> {
        self.reader
            .reload()
            .context("failed to reload BM25 reader")?;
        let searcher = self.reader.searcher();
        let mut query_parser = QueryParser::for_index(
            &self.index,
            vec![
                self.schema.filename,
                self.schema.path_tokens,
                self.schema.symbol_name,
                self.schema.content,
            ],
        );
        let path_weighted = looks_path_weighted(query_text);
        query_parser.set_field_boost(self.schema.content, 1.0);
        query_parser.set_field_boost(
            self.schema.symbol_name,
            if path_weighted { 2.0 } else { 3.0 },
        );
        query_parser.set_field_boost(
            self.schema.path_tokens,
            if path_weighted { 5.0 } else { 1.5 },
        );
        query_parser.set_field_boost(self.schema.filename, if path_weighted { 8.0 } else { 2.0 });

        // Sanitize query for tantivy: strip characters that the query parser
        // interprets as operators (e.g. `:` as field separator, `(`, `)`, etc.).
        let sanitized = sanitize_query(query_text);
        let query = query_parser
            .parse_query(&sanitized)
            .with_context(|| format!("failed to parse BM25 query: {query_text}"))?;

        let top_docs = searcher
            .search(&query, &TopDocs::with_limit(limit).order_by_score())
            .context("BM25 search failed")?;

        let mut results = Vec::with_capacity(top_docs.len());
        for (score, doc_addr) in top_docs {
            let doc: TantivyDocument = searcher
                .doc(doc_addr)
                .context("failed to retrieve BM25 doc")?;
            let chunk_id = doc
                .get_first(self.schema.chunk_id)
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();

            results.push(Bm25SearchResult { chunk_id, score });
        }

        Ok(results)
    }

    /// Count total documents in the index.
    pub fn doc_count(&self) -> Result<u64> {
        self.reader
            .reload()
            .context("failed to reload BM25 reader for count")?;
        let searcher = self.reader.searcher();
        Ok(searcher.num_docs())
    }

    /// Delete all documents matching a chunk ID.
    pub fn delete_by_chunk_id(&self, chunk_id: &str) -> Result<()> {
        let mut writer: IndexWriter = self
            .index
            .writer(WRITER_HEAP_SIZE)
            .context("failed to create BM25 writer for delete")?;

        let term = tantivy::Term::from_field_text(self.schema.chunk_id, chunk_id);
        writer.delete_term(term);
        writer.commit().context("failed to commit BM25 delete")?;
        writer
            .wait_merging_threads()
            .map_err(|e| anyhow::anyhow!("BM25 merge after delete failed: {e}"))?;

        Ok(())
    }

    /// Delete all documents for every given file path, using one writer.
    ///
    /// The per-call cost here is the writer lifecycle, not the deletion:
    /// allocating a `WRITER_HEAP_SIZE` writer, committing a segment and
    /// joining the merge threads costs on the order of tens of milliseconds
    /// regardless of how many terms are deleted. Callers removing many files
    /// must therefore batch, or they pay that fixed cost per file.
    pub fn delete_by_files(&self, file_paths: &[&str]) -> Result<()> {
        if file_paths.is_empty() {
            return Ok(());
        }

        let mut writer: IndexWriter = self
            .index
            .writer(WRITER_HEAP_SIZE)
            .context("failed to create BM25 writer for file delete")?;

        for file_path in file_paths {
            let term = tantivy::Term::from_field_text(self.schema.file_path, file_path);
            writer.delete_term(term);
        }
        writer
            .commit()
            .context("failed to commit BM25 file delete")?;
        writer
            .wait_merging_threads()
            .map_err(|e| anyhow::anyhow!("BM25 merge after file delete failed: {e}"))?;

        Ok(())
    }

    /// Clear the entire index (drop and recreate).
    pub fn clear(&self) -> Result<()> {
        let mut writer: IndexWriter = self
            .index
            .writer(WRITER_HEAP_SIZE)
            .context("failed to create BM25 writer for clear")?;
        writer
            .delete_all_documents()
            .context("failed to clear BM25 index")?;
        writer.commit().context("failed to commit BM25 clear")?;
        writer
            .wait_merging_threads()
            .map_err(|e| anyhow::anyhow!("BM25 merge after clear failed: {e}"))?;
        Ok(())
    }
}

/// Data for a single BM25 document insertion.
pub struct Bm25Document<'a> {
    pub chunk_id: &'a str,
    pub file_path: &'a str,
    pub content: &'a str,
    pub symbol_name: Option<&'a str>,
    pub language: &'a str,
}

/// Long-lived Tantivy writer for full-index builds; see
/// [`Bm25Index::begin_bulk_build`].
pub struct Bm25BulkWriter {
    writer: IndexWriter,
    schema: Bm25Schema,
}

impl Bm25BulkWriter {
    /// Buffer one window of chunks. Nothing is committed here; segments flush
    /// to disk automatically as the writer heap fills.
    pub fn insert_chunks(&self, chunks: &[crate::types::Chunk]) -> Result<()> {
        for_each_chunk_document(chunks, |doc_data| {
            add_document(&self.writer, &self.schema, doc_data)
        })
    }

    /// Commit the index once and wait for the final merge to finish.
    pub fn finish(self) -> Result<()> {
        let mut writer = self.writer;
        writer.commit().context("failed to commit BM25 index")?;
        writer
            .wait_merging_threads()
            .map_err(|e| anyhow::anyhow!("BM25 merge failed: {e}"))?;
        Ok(())
    }
}

/// Borrow each chunk as a BM25 document for the duration of `f`, avoiding a
/// materialized document vector for callers that stream into a writer.
fn for_each_chunk_document(
    chunks: &[crate::types::Chunk],
    mut f: impl FnMut(&Bm25Document<'_>) -> Result<()>,
) -> Result<()> {
    let lang_strings: Vec<String> = chunks.iter().map(|c| c.language.to_string()).collect();
    for (chunk, language) in chunks.iter().zip(lang_strings.iter()) {
        f(&Bm25Document {
            chunk_id: &chunk.id,
            file_path: &chunk.file_path,
            content: &chunk.content,
            symbol_name: chunk.symbol_name.as_deref(),
            language,
        })?;
    }
    Ok(())
}

fn add_document(
    writer: &IndexWriter,
    schema: &Bm25Schema,
    doc_data: &Bm25Document<'_>,
) -> Result<()> {
    let sym_name = doc_data.symbol_name.unwrap_or("");
    let chunk = crate::types::Chunk {
        id: doc_data.chunk_id.to_string(),
        file_path: doc_data.file_path.to_string(),
        line_start: 0,
        line_end: 0,
        content: doc_data.content.to_string(),
        language: doc_data
            .language
            .parse()
            .unwrap_or(crate::types::Language::Unknown),
        symbol_type: None,
        symbol_name: doc_data.symbol_name.map(ToString::to_string),
    };
    let searchable_text = chunk_text::build_bm25_text(&chunk);
    writer
        .add_document(doc!(
            schema.chunk_id => doc_data.chunk_id.to_string(),
            schema.file_path => doc_data.file_path.to_string(),
            schema.filename => chunk_text::file_name(doc_data.file_path).to_string(),
            schema.path_tokens => chunk_text::normalize_path_tokens(doc_data.file_path),
            schema.content => searchable_text,
            schema.symbol_name => sym_name.to_string(),
            schema.language => doc_data.language.to_string(),
        ))
        .context("failed to add document to BM25 index")?;
    Ok(())
}

/// Build the Tantivy schema for BM25 indexing.
fn build_schema() -> Bm25Schema {
    let mut builder = Schema::builder();

    // Stemmed text: indexed with English stemmer so "dependency" matches "dependencies".
    let stemmed_indexing = TextFieldIndexing::default()
        .set_tokenizer(STEMMED_TOKENIZER)
        .set_index_option(IndexRecordOption::WithFreqsAndPositions);
    let stemmed = TextOptions::default().set_indexing_options(stemmed_indexing.clone());
    let stemmed_stored = stemmed.clone() | STORED;

    // chunk_id and file_path use STRING (exact match, no tokenization) for deletion.
    let chunk_id = builder.add_text_field("chunk_id", STRING | STORED);
    let file_path = builder.add_text_field("file_path", STRING | STORED);
    let filename = builder.add_text_field("filename", stemmed_stored.clone());
    let path_tokens = builder.add_text_field("path_tokens", stemmed.clone());
    let content = builder.add_text_field("content", stemmed_stored.clone());
    let symbol_name = builder.add_text_field("symbol_name", stemmed_stored);
    let language = builder.add_text_field("language", stemmed);
    let schema = builder.build();

    Bm25Schema {
        schema,
        chunk_id,
        file_path,
        filename,
        path_tokens,
        content,
        symbol_name,
        language,
    }
}

fn sanitize_query(query_text: &str) -> String {
    let sanitized = query_text
        .chars()
        .map(|c| match c {
            ':' | '(' | ')' | '[' | ']' | '{' | '}' | '^' | '~' | '!' | '\'' | '"' | '`' => ' ',
            _ => c,
        })
        .collect::<String>();

    sanitized
        .split_whitespace()
        .map(|token| {
            // Tantivy treats a leading `-`/`+` as must-not/must and `*`/`?`
            // as wildcards. Strip them only at token edges so hyphenated
            // identifiers like `e-mail` survive as single terms.
            let token = token.trim_start_matches(['-', '+']);
            let token = token.trim_end_matches(['*', '?']);
            match token {
                "AND" => "and",
                "OR" => "or",
                "NOT" => "not",
                "IN" => "in",
                _ => token,
            }
        })
        .filter(|token| !token.is_empty())
        .collect::<Vec<_>>()
        .join(" ")
}

fn looks_path_weighted(query_text: &str) -> bool {
    let lower = query_text.trim().to_ascii_lowercase();
    lower.contains('/')
        || lower.contains('\\')
        || lower.contains(".toml")
        || lower.contains(".json")
        || lower.contains(".yaml")
        || lower.contains(".yml")
        || lower.contains(".ini")
        || lower.contains(".conf")
        || lower.contains("dockerfile")
        || lower.contains("makefile")
        || lower.contains("cmakelists.txt")
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_docs() -> Vec<Bm25Document<'static>> {
        vec![
            Bm25Document {
                chunk_id: "src/main.rs:0",
                file_path: "src/main.rs",
                content: "fn main() {\n    println!(\"Hello, world!\");\n}",
                symbol_name: Some("main"),
                language: "rust",
            },
            Bm25Document {
                chunk_id: "src/main.rs:1",
                file_path: "src/main.rs",
                content: "struct Config {\n    name: String,\n    port: u16,\n}",
                symbol_name: Some("Config"),
                language: "rust",
            },
            Bm25Document {
                chunk_id: "src/lib.py:0",
                file_path: "src/lib.py",
                content: "def hello_world():\n    print('Hello from Python')",
                symbol_name: Some("hello_world"),
                language: "python",
            },
            Bm25Document {
                chunk_id: "src/server.ts:0",
                file_path: "src/server.ts",
                content: "function handleRequest(req: Request): Response {\n    return new Response('ok');\n}",
                symbol_name: Some("handleRequest"),
                language: "typescript",
            },
            Bm25Document {
                chunk_id: "Cargo.toml:0",
                file_path: "Cargo.toml",
                content: "[workspace]\nmembers = [\"crates/vera-core\"]\nresolver = \"2\"",
                symbol_name: Some("Cargo.toml"),
                language: "toml",
            },
            Bm25Document {
                chunk_id: "fuzz/Cargo.toml:0",
                file_path: "fuzz/Cargo.toml",
                content: "[package]\nname = \"vera-fuzz\"\nversion = \"0.1.0\"",
                symbol_name: Some("Cargo.toml"),
                language: "toml",
            },
            Bm25Document {
                chunk_id: "turbo.json:0",
                file_path: "turbo.json",
                content: "{ \"pipeline\": { \"build\": { \"dependsOn\": [\"^build\"] } } }",
                symbol_name: Some("turbo.json"),
                language: "json",
            },
            Bm25Document {
                chunk_id: "crates/turbo/src/pipeline.ts:0",
                file_path: "crates/turbo/src/pipeline.ts",
                content: "export type Pipeline = { dependsOn?: string[]; outputs?: string[] }",
                symbol_name: Some("Pipeline"),
                language: "typescript",
            },
        ]
    }

    #[test]
    fn insert_and_count() {
        let index = Bm25Index::open_in_memory().unwrap();
        index.insert_batch(&sample_docs()).unwrap();
        assert_eq!(index.doc_count().unwrap(), 8);
    }

    #[test]
    fn bulk_writer_matches_insert_batch_results() {
        let docs = sample_docs();

        let batched = Bm25Index::open_in_memory().unwrap();
        batched.insert_batch(&docs).unwrap();

        let bulk = Bm25Index::open_in_memory().unwrap();
        let writer = bulk.begin_bulk_build().unwrap();
        // Split into two "windows" to prove the final commit covers all adds.
        writer
            .insert_chunks(
                &docs[..4]
                    .iter()
                    .map(|d| crate::types::Chunk {
                        id: d.chunk_id.to_string(),
                        file_path: d.file_path.to_string(),
                        line_start: 0,
                        line_end: 0,
                        content: d.content.to_string(),
                        language: d.language.parse().unwrap(),
                        symbol_type: None,
                        symbol_name: d.symbol_name.map(ToString::to_string),
                    })
                    .collect::<Vec<_>>(),
            )
            .unwrap();
        writer
            .insert_chunks(
                &docs[4..]
                    .iter()
                    .map(|d| crate::types::Chunk {
                        id: d.chunk_id.to_string(),
                        file_path: d.file_path.to_string(),
                        line_start: 0,
                        line_end: 0,
                        content: d.content.to_string(),
                        language: d.language.parse().unwrap(),
                        symbol_type: None,
                        symbol_name: d.symbol_name.map(ToString::to_string),
                    })
                    .collect::<Vec<_>>(),
            )
            .unwrap();
        writer.finish().unwrap();

        assert_eq!(bulk.doc_count().unwrap(), batched.doc_count().unwrap());
        for query in ["println hello world", "Config port", "Pipeline outputs"] {
            let mut expected: Vec<_> = batched
                .search(query, 10)
                .unwrap()
                .into_iter()
                .map(|r| r.chunk_id)
                .collect();
            let mut actual: Vec<_> = bulk
                .search(query, 10)
                .unwrap()
                .into_iter()
                .map(|r| r.chunk_id)
                .collect();
            expected.sort();
            actual.sort();
            assert_eq!(actual, expected, "bulk writer diverged on query {query}");
        }
    }

    #[test]
    fn keyword_search_finds_content() {
        let index = Bm25Index::open_in_memory().unwrap();
        index.insert_batch(&sample_docs()).unwrap();

        let results = index.search("println hello world", 10).unwrap();
        assert!(
            !results.is_empty(),
            "should find documents matching keywords"
        );

        // The main function chunk contains "println" and "Hello, world!"
        let main_found = results.iter().any(|r| r.chunk_id == "src/main.rs:0");
        assert!(main_found, "should find the main function chunk");
    }

    #[test]
    fn symbol_name_search() {
        let index = Bm25Index::open_in_memory().unwrap();
        index.insert_batch(&sample_docs()).unwrap();

        let results = index.search("Config", 10).unwrap();
        assert!(!results.is_empty());
        assert_eq!(
            results[0].chunk_id, "src/main.rs:1",
            "Config struct should be top result for 'Config' query"
        );
    }

    #[test]
    fn search_returns_ranked_scores() {
        let index = Bm25Index::open_in_memory().unwrap();
        index.insert_batch(&sample_docs()).unwrap();

        let results = index.search("hello", 10).unwrap();
        assert!(results.len() >= 2, "should find multiple hello matches");

        // Scores should be in descending order.
        for i in 1..results.len() {
            assert!(
                results[i - 1].score >= results[i].score,
                "scores should be descending"
            );
        }
    }

    #[test]
    fn search_respects_limit() {
        let index = Bm25Index::open_in_memory().unwrap();
        index.insert_batch(&sample_docs()).unwrap();

        let results = index.search("hello", 1).unwrap();
        assert!(results.len() <= 1);
    }

    #[test]
    fn search_no_results() {
        let index = Bm25Index::open_in_memory().unwrap();
        index.insert_batch(&sample_docs()).unwrap();

        let results = index.search("xyznonexistent", 10).unwrap();
        assert!(results.is_empty());
    }

    #[test]
    fn delete_by_files_removes_every_path_and_keeps_the_rest() {
        let index = Bm25Index::open_in_memory().unwrap();
        let mut docs = sample_docs();
        docs.push(Bm25Document {
            chunk_id: "src/keep.rs:0",
            file_path: "src/keep.rs",
            content: "fn hello_survivor() {}",
            symbol_name: Some("hello_survivor"),
            language: "rust",
        });
        index.insert_batch(&docs).unwrap();
        let before = index.doc_count().unwrap();

        // src/main.rs has two documents; deleting it and one other path must
        // take all of theirs and none of anyone else's.
        index
            .delete_by_files(&["src/main.rs", "src/lib.py"])
            .unwrap();

        assert_eq!(index.doc_count().unwrap(), before - 3);

        // "hello" occurs in both deleted paths and in src/keep.rs, so every
        // path assertion below can fail while the result set stays non-empty.
        let hits = index.search("hello", 50).unwrap();
        assert!(
            hits.iter()
                .any(|hit| hit.chunk_id.starts_with("src/keep.rs:")),
            "the unrelated hello document must survive"
        );
        for path in ["src/main.rs:", "src/lib.py:"] {
            assert!(
                hits.iter().all(|hit| !hit.chunk_id.starts_with(path)),
                "{path} should have no documents left, got {:?}",
                hits.iter().map(|h| &h.chunk_id).collect::<Vec<_>>()
            );
        }
        // An unrelated path is untouched.
        let remaining = index.search("server", 50).unwrap();
        assert!(
            remaining
                .iter()
                .any(|hit| hit.chunk_id.starts_with("src/server.ts:")),
            "unrelated documents must survive"
        );
    }

    #[test]
    fn delete_by_files_with_no_paths_is_a_no_op() {
        // The update path calls this unconditionally, so an update with
        // nothing deleted or modified must not touch the index — and must not
        // pay for a writer to do nothing.
        let index = Bm25Index::open_in_memory().unwrap();
        index.insert_batch(&sample_docs()).unwrap();
        let before = index.doc_count().unwrap();

        index.delete_by_files(&[]).unwrap();

        assert_eq!(index.doc_count().unwrap(), before);
    }

    #[test]
    fn delete_by_chunk_id() {
        let index = Bm25Index::open_in_memory().unwrap();
        index.insert_batch(&sample_docs()).unwrap();
        assert_eq!(index.doc_count().unwrap(), 8);

        index.delete_by_chunk_id("src/main.rs:0").unwrap();
        assert_eq!(index.doc_count().unwrap(), 7);
    }

    #[test]
    fn clear_index() {
        let index = Bm25Index::open_in_memory().unwrap();
        index.insert_batch(&sample_docs()).unwrap();

        index.clear().unwrap();
        assert_eq!(index.doc_count().unwrap(), 0);
    }

    #[test]
    fn handlerequest_found_by_request() {
        let index = Bm25Index::open_in_memory().unwrap();
        index.insert_batch(&sample_docs()).unwrap();

        let results = index.search("handleRequest", 10).unwrap();
        assert!(!results.is_empty());
        let found = results.iter().any(|r| r.chunk_id == "src/server.ts:0");
        assert!(found, "handleRequest should be found");
    }

    #[test]
    fn filename_queries_rank_config_files() {
        let index = Bm25Index::open_in_memory().unwrap();
        index.insert_batch(&sample_docs()).unwrap();

        let results = index
            .search("Cargo.toml workspace configuration", 10)
            .unwrap();
        assert!(!results.is_empty());
        assert_eq!(results[0].chunk_id, "Cargo.toml:0");
    }

    #[test]
    fn path_boost_prefers_root_config_over_nested_match() {
        let index = Bm25Index::open_in_memory().unwrap();
        index.insert_batch(&sample_docs()).unwrap();

        let results = index
            .search("Cargo.toml workspace configuration", 10)
            .unwrap();
        assert_eq!(results[0].chunk_id, "Cargo.toml:0");
    }

    #[test]
    fn path_boost_prefers_turbo_json_over_pipeline_symbol() {
        let index = Bm25Index::open_in_memory().unwrap();
        index.insert_batch(&sample_docs()).unwrap();

        let results = index
            .search("turbo.json pipeline configuration", 10)
            .unwrap();
        assert_eq!(results[0].chunk_id, "turbo.json:0");
    }

    #[test]
    fn stemming_matches_morphological_variants() {
        let index = Bm25Index::open_in_memory().unwrap();
        index
            .insert_batch(&[Bm25Document {
                chunk_id: "deps.py:0",
                file_path: "fastapi/dependencies/utils.py",
                content: "def solve_dependencies(dependant, sub_dependant):\n    return resolved",
                symbol_name: Some("solve_dependencies"),
                language: "python",
            }])
            .unwrap();

        // "dependency" should match "dependencies" via English stemming.
        let results = index.search("dependency injection", 10).unwrap();
        assert!(
            !results.is_empty(),
            "stemming should match 'dependency' to 'dependencies'"
        );
    }

    #[test]
    fn sanitize_query_strips_possessive_apostrophes() {
        assert_eq!(
            sanitize_query("how pandoc's app module orchestrates"),
            "how pandoc s app module orchestrates"
        );
    }

    #[test]
    fn sanitize_query_neutralizes_tantivy_operators() {
        assert_eq!(
            sanitize_query("NOT NULL -required +must wildcard? * AND OR IN"),
            "not NULL required must wildcard and or in"
        );
    }

    #[test]
    fn sanitize_query_preserves_hyphenated_identifiers() {
        assert_eq!(
            sanitize_query("e-mail client read-line"),
            "e-mail client read-line"
        );
    }

    #[test]
    fn operator_queries_match_plain_terms() {
        let index = Bm25Index::open_in_memory().unwrap();
        index
            .insert_batch(&[
                Bm25Document {
                    chunk_id: "null:0",
                    file_path: "null.sql",
                    content: "NOT NULL constraint",
                    symbol_name: None,
                    language: "sql",
                },
                Bm25Document {
                    chunk_id: "null:1",
                    file_path: "other.sql",
                    content: "NULL value validation",
                    symbol_name: None,
                    language: "sql",
                },
            ])
            .unwrap();

        let ids = |query| {
            index
                .search(query, 10)
                .unwrap()
                .into_iter()
                .map(|result| result.chunk_id)
                .collect::<Vec<_>>()
        };

        assert_eq!(ids("NOT NULL"), ids("not null"));
        assert_eq!(ids("-null"), ids("null"));
        assert_eq!(ids("+null"), ids("null"));
        assert_eq!(ids("* null?"), ids("null"));
    }
}