memd 1.9.0

Local memory CLI for AI agents with hybrid retrieval
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
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
//! BM25 sparse index using Tantivy.
//!
//! Implements the SparseIndex trait with Tantivy's inverted index for
//! keyword-based retrieval. Uses CodeTokenizer for code-aware tokenization.

use std::collections::HashSet;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};

use tantivy::collector::TopDocs;
use tantivy::directory::error::{DeleteError, LockError, OpenReadError, OpenWriteError};
use tantivy::directory::{
    Directory, DirectoryLock, FileHandle, Lock, MmapDirectory, WatchCallback, WatchHandle, WritePtr,
};
use tantivy::query::{BooleanQuery, Occur, Query, QueryParser, TermQuery};
use tantivy::schema::{
    Field, IndexRecordOption, Schema, TextFieldIndexing, TextOptions, Value, STORED, STRING,
};
use tantivy::tokenizer::TextAnalyzer;
use tantivy::{doc, Index, IndexReader, IndexWriter, ReloadPolicy, Term};

use crate::error::{MemdError, Result};
use crate::index::sparse::{SparseIndex, SparseSearchResult};
use crate::text::CodeTokenizer;
use crate::types::{ChunkId, TenantId};

/// Default memory budget for index writer (50MB).
const DEFAULT_WRITER_MEMORY_BYTES: usize = 50_000_000;

/// Over-fetch factor for sparse search. BM25 indexes each sentence of a chunk
/// as its own document, so `search` fetches this many times `k` sentence hits
/// and collapses them to at most `k` distinct chunks. 8 comfortably covers
/// multi-sentence turns; the collapse loop breaks early once `k` chunks are
/// found, so the extra window costs nothing on the common (mostly-distinct) path.
const SPARSE_CHUNK_OVERFETCH: usize = 8;

/// Absolute ceiling on the sparse over-fetch window. A query matching many
/// sentences of only a few chunks would otherwise drive up to
/// `k * SPARSE_CHUNK_OVERFETCH` stored-document retrievals before the collapse
/// loop can fill `k` distinct chunks; this bounds that worst case. Sized well
/// above `sparse_k` (200) times the typical sentences-per-turn, so it never
/// limits the distinct-chunk yield on conversational corpora.
const SPARSE_FETCH_CEILING: usize = 1024;

/// Directory for a read-only index handle.
///
/// Tantivy locks `.tantivy-meta.lock` whenever a reader opens segments, so a
/// writer's garbage collection cannot delete them mid-open. Creating that file
/// needs a writable directory. Where the lock file cannot be opened (a read-only
/// mount or file mode), this wrapper proceeds without the lock instead of
/// failing the whole index. A reader that races a collection then fails on a
/// missing segment, and the caller falls back to the other search lanes. A
/// writable directory keeps the real lock.
#[derive(Clone, Debug)]
struct ReadOnlyDirectory(MmapDirectory);

impl Directory for ReadOnlyDirectory {
    fn get_file_handle(
        &self,
        path: &Path,
    ) -> std::result::Result<Arc<dyn FileHandle>, OpenReadError> {
        self.0.get_file_handle(path)
    }

    fn delete(&self, path: &Path) -> std::result::Result<(), DeleteError> {
        self.0.delete(path)
    }

    fn exists(&self, path: &Path) -> std::result::Result<bool, OpenReadError> {
        self.0.exists(path)
    }

    fn open_write(&self, path: &Path) -> std::result::Result<WritePtr, OpenWriteError> {
        self.0.open_write(path)
    }

    fn atomic_read(&self, path: &Path) -> std::result::Result<Vec<u8>, OpenReadError> {
        self.0.atomic_read(path)
    }

    fn atomic_write(&self, path: &Path, data: &[u8]) -> io::Result<()> {
        self.0.atomic_write(path, data)
    }

    fn sync_directory(&self) -> io::Result<()> {
        self.0.sync_directory()
    }

    fn acquire_lock(&self, lock: &Lock) -> std::result::Result<DirectoryLock, LockError> {
        match self.0.acquire_lock(lock) {
            Err(LockError::IoError(_)) => Ok(DirectoryLock::from(Box::new(()))),
            result => result,
        }
    }

    fn watch(&self, watch_callback: WatchCallback) -> tantivy::Result<WatchHandle> {
        self.0.watch(watch_callback)
    }
}

fn escape_query_text(query: &str) -> String {
    const SPECIAL_CHARS: &str = "\\+-&|!(){}[]^\"~*?:/";
    let mut escaped = String::with_capacity(query.len() + 8);
    for ch in query.chars() {
        if SPECIAL_CHARS.contains(ch) {
            escaped.push('\\');
        }
        escaped.push(ch);
    }
    escaped
}

fn plain_query_text(query: &str) -> String {
    query
        .chars()
        .map(|ch| {
            if ch.is_alphanumeric() || ch == '_' {
                ch
            } else {
                ' '
            }
        })
        .collect()
}

fn parse_text_query(parser: &QueryParser, query: &str) -> Result<Box<dyn Query>> {
    match parser.parse_query(query) {
        Ok(parsed) => Ok(parsed),
        Err(primary_err) => {
            let escaped_query = escape_query_text(query);
            if let Ok(parsed) = parser.parse_query(&escaped_query) {
                return Ok(parsed);
            }

            let (lenient_query, parse_errors) = parser.parse_query_lenient(&escaped_query);
            if parse_errors.is_empty() {
                return Ok(lenient_query);
            }

            let plain_query = plain_query_text(query);
            if !plain_query.trim().is_empty() {
                if let Ok(parsed) = parser.parse_query(&plain_query) {
                    return Ok(parsed);
                }

                let (plain_lenient_query, plain_parse_errors) =
                    parser.parse_query_lenient(&plain_query);
                if plain_parse_errors.is_empty() {
                    return Ok(plain_lenient_query);
                }
            }

            Err(MemdError::ValidationError(format!(
                "parse query: {}; lenient parser also reported syntax issues",
                primary_err
            )))
        }
    }
}

/// BM25 sparse index using Tantivy.
///
/// Provides keyword-based search with BM25 scoring and code-aware tokenization.
/// Thread-safe: reader is cloneable, writer is mutex-protected.
pub struct Bm25Index {
    /// The Tantivy index
    index: Index,
    /// Index reader for search operations
    reader: IndexReader,
    /// Index writer for insert/delete (mutex for thread safety)
    writer: Option<Mutex<IndexWriter>>,
    /// Schema for document structure (kept for potential future use)
    #[allow(dead_code)]
    schema: Schema,
    /// Field for tenant ID
    tenant_field: Field,
    /// Field for chunk ID
    chunk_field: Field,
    /// Field for sentence index within chunk
    sentence_field: Field,
    /// Field for indexed text
    text_field: Field,
    /// Whether writes are pending commit.
    dirty: AtomicBool,
}

struct Bm25SchemaFields {
    schema: Schema,
    tenant_field: Field,
    chunk_field: Field,
    sentence_field: Field,
    text_field: Field,
}

fn build_schema_fields() -> Bm25SchemaFields {
    let mut schema_builder = Schema::builder();

    let tenant_field = schema_builder.add_text_field("tenant_id", STRING | STORED);
    let chunk_field = schema_builder.add_text_field("chunk_id", STRING | STORED);
    let sentence_field = schema_builder.add_u64_field("sentence_idx", STORED);

    let text_indexing = TextFieldIndexing::default()
        .set_tokenizer("code")
        .set_index_option(IndexRecordOption::WithFreqsAndPositions);
    let text_options = TextOptions::default()
        .set_indexing_options(text_indexing)
        .set_stored();
    let text_field = schema_builder.add_text_field("text", text_options);

    Bm25SchemaFields {
        schema: schema_builder.build(),
        tenant_field,
        chunk_field,
        sentence_field,
        text_field,
    }
}

impl Bm25Index {
    /// Create a new in-memory BM25 index.
    pub fn new() -> Result<Self> {
        Self::with_path(None)
    }

    /// Create a new BM25 index with optional persistence path.
    ///
    /// If path is None, creates an in-memory index.
    /// If path is Some, creates a persistent index at the given directory.
    pub fn with_path(path: Option<PathBuf>) -> Result<Self> {
        let fields = build_schema_fields();

        // Create or reopen the index. `Index::create_in_dir` fails when the
        // directory already contains a tantivy index, which would silently
        // disable hybrid search on restart. Use `open_or_create` via an
        // `MmapDirectory` so the same code path works for fresh and existing
        // directories.
        let index = match path {
            Some(p) => {
                std::fs::create_dir_all(&p)?;
                let directory = MmapDirectory::open(&p)
                    .map_err(|e| MemdError::StorageError(format!("open index directory: {}", e)))?;
                Index::open_or_create(directory, fields.schema.clone())
                    .map_err(|e| MemdError::StorageError(format!("open_or_create index: {}", e)))?
            }
            None => Index::create_in_ram(fields.schema.clone()),
        };

        // Create writer
        let writer = index
            .writer(DEFAULT_WRITER_MEMORY_BYTES)
            .map_err(|e| MemdError::StorageError(format!("create writer: {}", e)))?;

        Self::from_index(index, fields, Some(writer))
    }

    /// Open an existing persistent BM25 index without creating a writer.
    pub fn with_path_read_only(path: PathBuf) -> Result<Option<Self>> {
        if !path.exists() {
            tracing::debug!(
                path = %path.display(),
                "sparse index directory missing; read-only sparse search unavailable"
            );
            return Ok(None);
        }

        let fields = build_schema_fields();
        let directory = MmapDirectory::open(&path)
            .map_err(|e| MemdError::StorageError(format!("open index directory: {}", e)))?;
        let index = Index::open(ReadOnlyDirectory(directory))
            .map_err(|e| MemdError::StorageError(format!("open read-only index: {}", e)))?;

        Ok(Some(Self::from_index(index, fields, None)?))
    }

    fn from_index(
        index: Index,
        fields: Bm25SchemaFields,
        writer: Option<IndexWriter>,
    ) -> Result<Self> {
        let code_tokenizer = TextAnalyzer::builder(CodeTokenizer::new()).build();
        index.tokenizers().register("code", code_tokenizer);

        let reader = index
            .reader_builder()
            .reload_policy(ReloadPolicy::OnCommitWithDelay)
            .try_into()
            .map_err(|e| MemdError::StorageError(format!("create reader: {}", e)))?;

        Ok(Self {
            index,
            reader,
            writer: writer.map(Mutex::new),
            schema: fields.schema,
            tenant_field: fields.tenant_field,
            chunk_field: fields.chunk_field,
            sentence_field: fields.sentence_field,
            text_field: fields.text_field,
            dirty: AtomicBool::new(false),
        })
    }

    /// Commit pending writes if needed.
    fn commit_if_dirty(&self) -> Result<()> {
        let Some(writer) = self.writer.as_ref() else {
            return Ok(());
        };
        let mut writer = writer
            .lock()
            .map_err(|e| MemdError::StorageError(format!("lock writer: {}", e)))?;
        if self.dirty.swap(false, Ordering::AcqRel) {
            writer
                .commit()
                .map_err(|e| MemdError::StorageError(format!("commit: {}", e)))?;
        }
        Ok(())
    }

    /// Commit pending changes to make them searchable.
    ///
    /// Called automatically after batch operations, but can be called
    /// manually to force visibility of recent writes.
    pub fn commit(&self) -> Result<()> {
        self.commit_if_dirty()
    }

    /// Get total number of documents in the index.
    pub fn total_docs(&self) -> Result<u64> {
        let searcher = self.reader.searcher();
        Ok(searcher.num_docs())
    }

    /// Get the number of segments in the index
    ///
    /// Used by compaction to check if segment merge is needed.
    pub fn segment_count(&self) -> Result<usize> {
        self.commit_if_dirty()?;

        // Reload to see recent changes
        self.reader
            .reload()
            .map_err(|e| MemdError::StorageError(format!("reload reader: {}", e)))?;

        let searcher = self.reader.searcher();
        Ok(searcher.segment_readers().len())
    }

    /// Merge every searchable Tantivy segment and wait for the merged segment
    /// to become durable. A plain commit does not force existing segments to
    /// merge, so maintenance callers must use this operation explicitly.
    pub fn merge_all_segments(&self) -> Result<()> {
        self.commit_if_dirty()?;
        let segment_ids = self
            .index
            .searchable_segment_ids()
            .map_err(|e| MemdError::StorageError(format!("list segments: {e}")))?;
        if segment_ids.len() <= 1 {
            return Ok(());
        }

        let merge = {
            let mut writer = self
                .writer
                .as_ref()
                .ok_or_else(|| MemdError::ReadOnlyStore {
                    op: "bm25_merge_all_segments".to_string(),
                })?
                .lock()
                .map_err(|e| MemdError::StorageError(format!("lock writer: {e}")))?;
            writer.merge(&segment_ids)
        };
        merge
            .wait()
            .map_err(|e| MemdError::StorageError(format!("merge segments: {e}")))?;
        self.reader
            .reload()
            .map_err(|e| MemdError::StorageError(format!("reload merged index: {e}")))?;
        Ok(())
    }
}

impl Default for Bm25Index {
    fn default() -> Self {
        Self::new().expect("failed to create default Bm25Index")
    }
}

impl SparseIndex for Bm25Index {
    fn insert(&self, tenant_id: &TenantId, chunk_id: &ChunkId, sentences: &[String]) -> Result<()> {
        self.insert_batch(&[(tenant_id.clone(), chunk_id.clone(), sentences.to_vec())])
    }

    fn insert_batch(&self, items: &[(TenantId, ChunkId, Vec<String>)]) -> Result<()> {
        if items.is_empty() {
            return Ok(());
        }

        let Some(writer) = self.writer.as_ref() else {
            return Err(MemdError::ReadOnlyStore {
                op: "bm25_insert_batch".to_string(),
            });
        };
        let writer = writer
            .lock()
            .map_err(|e| MemdError::StorageError(format!("lock writer: {}", e)))?;

        for (tenant_id, chunk_id, sentences) in items {
            for (idx, sentence) in sentences.iter().enumerate() {
                let doc = doc!(
                    self.tenant_field => tenant_id.as_str(),
                    self.chunk_field => chunk_id.to_string(),
                    self.sentence_field => idx as u64,
                    self.text_field => sentence.clone(),
                );
                writer
                    .add_document(doc)
                    .map_err(|e| MemdError::StorageError(format!("add document: {}", e)))?;
            }
        }
        self.dirty.store(true, Ordering::Release);

        Ok(())
    }

    fn search(
        &self,
        tenant_id: &TenantId,
        query: &str,
        k: usize,
    ) -> Result<Vec<SparseSearchResult>> {
        // Nothing to return, and TopDocs::with_limit(0) panics in tantivy.
        if k == 0 {
            return Ok(Vec::new());
        }

        self.commit_if_dirty()?;

        // Reload to see recent commits (BEFORE getting searcher)
        self.reader
            .reload()
            .map_err(|e| MemdError::StorageError(format!("reload reader: {}", e)))?;

        let searcher = self.reader.searcher();

        // Build tenant filter
        let tenant_term = Term::from_field_text(self.tenant_field, tenant_id.as_str());
        let tenant_query: Box<dyn Query> =
            Box::new(TermQuery::new(tenant_term, IndexRecordOption::Basic));

        // Build text query using tokenizer
        let query_parser = QueryParser::for_index(&self.index, vec![self.text_field]);
        let text_query = parse_text_query(&query_parser, query)?;

        // Combine with boolean query: must match tenant AND text
        let combined_query =
            BooleanQuery::new(vec![(Occur::Must, tenant_query), (Occur::Must, text_query)]);

        // BM25 indexes each sentence of a chunk as its own document, so a
        // multi-sentence chunk can match on several sentences and take several
        // of the top slots. Left uncollapsed that (a) burns sparse candidate
        // slots — fewer distinct chunks reach RRF fusion, hurting recall — and
        // (b) double-counts the chunk in fusion, whose accumulator sums a
        // contribution per occurrence. Over-fetch a wider window and keep each
        // chunk once, at its best-scoring sentence (= min rank), returning up
        // to `k` distinct chunks. The window is a heuristic — a query dominated
        // by a few many-sentence chunks can still yield fewer than `k` — so the
        // ceiling bounds the worst-case retrieval count while `.max(k)` keeps
        // room for at least `k` distinct chunks when `k` exceeds the ceiling.
        let fetch_limit = k
            .saturating_mul(SPARSE_CHUNK_OVERFETCH)
            .min(SPARSE_FETCH_CEILING)
            .max(k);
        let top_docs = searcher
            .search(&combined_query, &TopDocs::with_limit(fetch_limit))
            .map_err(|e| MemdError::StorageError(format!("search: {}", e)))?;

        // `top_docs` is ordered by score descending, so the first hit seen for
        // a chunk is its best; skip any later (worse-ranked) sentence of a
        // chunk already kept.
        let mut results = Vec::with_capacity(k);
        let mut seen: HashSet<ChunkId> = HashSet::with_capacity(k);
        for (score, doc_address) in top_docs {
            let doc = searcher
                .doc::<tantivy::TantivyDocument>(doc_address)
                .map_err(|e| MemdError::StorageError(format!("retrieve doc: {}", e)))?;

            // Extract fields
            let chunk_id_str = doc
                .get_first(self.chunk_field)
                .and_then(|v| v.as_str())
                .ok_or_else(|| MemdError::StorageError("missing chunk_id".into()))?;

            let sentence_idx = doc
                .get_first(self.sentence_field)
                .and_then(|v| v.as_u64())
                .unwrap_or(0) as usize;

            let chunk_id = ChunkId::parse(chunk_id_str)?;

            if !seen.insert(chunk_id.clone()) {
                continue;
            }

            results.push(SparseSearchResult {
                chunk_id,
                score,
                sentence_idx,
            });

            if results.len() >= k {
                break;
            }
        }

        Ok(results)
    }

    fn delete(&self, tenant_id: &TenantId, chunk_id: &ChunkId) -> Result<bool> {
        self.commit_if_dirty()?;

        let Some(writer) = self.writer.as_ref() else {
            return Err(MemdError::ReadOnlyStore {
                op: "bm25_delete".to_string(),
            });
        };
        let writer = writer
            .lock()
            .map_err(|e| MemdError::StorageError(format!("lock writer: {}", e)))?;

        // Build query to match both tenant and chunk
        let tenant_term = Term::from_field_text(self.tenant_field, tenant_id.as_str());
        let chunk_term = Term::from_field_text(self.chunk_field, &chunk_id.to_string());

        // Delete by term queries combined
        // Tantivy delete_term deletes all docs matching that term
        // We need to be more precise, so we use delete_query
        let tenant_query: Box<dyn Query> =
            Box::new(TermQuery::new(tenant_term, IndexRecordOption::Basic));
        let chunk_query: Box<dyn Query> =
            Box::new(TermQuery::new(chunk_term, IndexRecordOption::Basic));

        let delete_query = BooleanQuery::new(vec![
            (Occur::Must, tenant_query),
            (Occur::Must, chunk_query),
        ]);

        // Get count before delete to determine if anything was deleted
        self.reader
            .reload()
            .map_err(|e| MemdError::StorageError(format!("reload reader: {}", e)))?;
        let searcher = self.reader.searcher();
        let count_before = searcher
            .search(&delete_query, &tantivy::collector::Count)
            .unwrap_or(0);

        writer
            .delete_query(Box::new(delete_query))
            .map_err(|e| MemdError::StorageError(format!("delete query: {}", e)))?;
        self.dirty.store(true, Ordering::Release);

        Ok(count_before > 0)
    }

    fn doc_count(&self, tenant_id: &TenantId) -> Result<u64> {
        self.commit_if_dirty()?;

        // Reload to see recent commits
        self.reader
            .reload()
            .map_err(|e| MemdError::StorageError(format!("reload reader: {}", e)))?;

        let searcher = self.reader.searcher();

        let tenant_term = Term::from_field_text(self.tenant_field, tenant_id.as_str());
        let tenant_query = TermQuery::new(tenant_term, IndexRecordOption::Basic);

        let count = searcher
            .search(&tenant_query, &tantivy::collector::Count)
            .map_err(|e| MemdError::StorageError(format!("count: {}", e)))?;

        Ok(count as u64)
    }
}

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

    fn create_test_tenant() -> TenantId {
        TenantId::new("test_tenant").unwrap()
    }

    #[cfg(unix)]
    #[test]
    fn read_only_open_searches_an_index_in_an_unwritable_directory() {
        use std::os::unix::fs::PermissionsExt;

        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("sparse_index");
        let tenant = create_test_tenant();
        let chunk_id = ChunkId::new();
        {
            let index = Bm25Index::with_path(Some(path.clone())).unwrap();
            index
                .insert(&tenant, &chunk_id, &["readonly mount token".to_string()])
                .unwrap();
            index.commit().unwrap();
        }
        let _ = std::fs::remove_file(path.join(".tantivy-meta.lock"));
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o500)).unwrap();
        let writable = crate::store::path_is_writable(&path);

        let opened = Bm25Index::with_path_read_only(path.clone());
        let found = opened
            .as_ref()
            .ok()
            .and_then(|index| index.as_ref())
            .map(|index| index.search(&tenant, "mount", 5).unwrap());
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)).unwrap();
        if writable {
            return; // root ignores the mode bits; nothing to prove here
        }
        let found = found.expect("read-only open must work without a lock file");
        assert_eq!(found[0].chunk_id, chunk_id);
        assert!(
            !path.join(".tantivy-meta.lock").exists(),
            "the read-only open must not create the lock file"
        );
    }

    #[test]
    fn test_insert_and_search() {
        let index = Bm25Index::new().unwrap();
        let tenant = create_test_tenant();
        let chunk_id = ChunkId::new();

        let sentences = vec![
            "function parseJSON() { return JSON.parse(data); }".to_string(),
            "Returns parsed data from JSON string".to_string(),
        ];

        index.insert(&tenant, &chunk_id, &sentences).unwrap();

        // Search for parseJSON
        let results = index.search(&tenant, "parseJSON", 10).unwrap();
        assert!(!results.is_empty(), "should find parseJSON");
        assert_eq!(results[0].chunk_id, chunk_id);
        assert!(results[0].score > 0.0);

        // Search for parsed data
        let results = index.search(&tenant, "parsed data", 10).unwrap();
        assert!(!results.is_empty(), "should find 'parsed data'");
    }

    #[test]
    fn test_insert_batch_and_search() {
        let index = Bm25Index::new().unwrap();
        let tenant = create_test_tenant();
        let chunk_a = ChunkId::new();
        let chunk_b = ChunkId::new();

        let items = vec![
            (
                tenant.clone(),
                chunk_a.clone(),
                vec!["alpha parser".to_string(), "json utility".to_string()],
            ),
            (
                tenant.clone(),
                chunk_b.clone(),
                vec!["beta formatter".to_string()],
            ),
        ];
        index.insert_batch(&items).unwrap();

        let results = index.search(&tenant, "alpha", 10).unwrap();
        assert!(!results.is_empty(), "should find batch-inserted chunk");
        assert_eq!(results[0].chunk_id, chunk_a);

        let results = index.search(&tenant, "formatter", 10).unwrap();
        assert!(
            !results.is_empty(),
            "should find second batch-inserted chunk"
        );
        assert_eq!(results[0].chunk_id, chunk_b);
    }

    #[test]
    fn test_keyword_exact_match() {
        let index = Bm25Index::new().unwrap();
        let tenant = create_test_tenant();
        let chunk_id = ChunkId::new();

        let sentences = vec!["The getUserById function returns a User object".to_string()];

        index.insert(&tenant, &chunk_id, &sentences).unwrap();

        // Identifier should be split: getUserById -> get, user, by, id
        let results = index.search(&tenant, "getUserById", 10).unwrap();
        assert!(!results.is_empty(), "should find getUserById");

        // Individual tokens should also match
        let results = index.search(&tenant, "user", 10).unwrap();
        assert!(!results.is_empty(), "should find 'user' token");
    }

    #[test]
    fn test_tenant_isolation() {
        let index = Bm25Index::new().unwrap();
        let tenant_a = TenantId::new("tenant_a").unwrap();
        let tenant_b = TenantId::new("tenant_b").unwrap();
        let chunk_id = ChunkId::new();

        let sentences = vec!["secret data for tenant A".to_string()];

        index.insert(&tenant_a, &chunk_id, &sentences).unwrap();

        // Tenant B should not see tenant A's data
        let results = index.search(&tenant_b, "secret", 10).unwrap();
        assert!(results.is_empty(), "tenant B should not see tenant A data");

        // Tenant A should see their own data
        let results = index.search(&tenant_a, "secret", 10).unwrap();
        assert!(!results.is_empty(), "tenant A should see their data");
    }

    #[test]
    fn test_delete() {
        let index = Bm25Index::new().unwrap();
        let tenant = create_test_tenant();
        let chunk_id = ChunkId::new();

        let sentences = vec!["deletable content here".to_string()];

        index.insert(&tenant, &chunk_id, &sentences).unwrap();

        // Verify it exists
        let results = index.search(&tenant, "deletable", 10).unwrap();
        assert!(!results.is_empty(), "should find before delete");

        // Delete it
        let deleted = index.delete(&tenant, &chunk_id).unwrap();
        assert!(deleted, "should return true for successful delete");

        // Verify it's gone.
        let results = index.search(&tenant, "deletable", 10).unwrap();
        assert!(results.is_empty(), "should not find after delete");
    }

    #[test]
    fn test_multiple_sentences() {
        let index = Bm25Index::new().unwrap();
        let tenant = create_test_tenant();
        let chunk_id = ChunkId::new();

        let sentences = vec![
            "First sentence about apples".to_string(),
            "Second sentence about oranges".to_string(),
            "Third sentence about bananas".to_string(),
        ];

        index.insert(&tenant, &chunk_id, &sentences).unwrap();

        // Search for oranges (sentence index 1)
        let results = index.search(&tenant, "oranges", 10).unwrap();
        assert!(!results.is_empty());
        assert_eq!(
            results[0].sentence_idx, 1,
            "should match sentence at index 1"
        );
    }

    #[test]
    fn test_multi_sentence_chunk_collapses_to_one() {
        let index = Bm25Index::new().unwrap();
        let tenant = create_test_tenant();
        let multi = ChunkId::new();
        let single = ChunkId::new();

        // `multi` matches the query on all three sentences; without the
        // per-chunk collapse each would take its own slot and the chunk would
        // be counted three times in downstream RRF fusion. `single` is a
        // distinct chunk with one matching sentence that must survive collapse.
        index
            .insert(
                &tenant,
                &multi,
                &[
                    "oranges are great".to_string(),
                    "I really love oranges".to_string(),
                    "more oranges please".to_string(),
                ],
            )
            .unwrap();
        index
            .insert(&tenant, &single, &["oranges once".to_string()])
            .unwrap();

        let results = index.search(&tenant, "oranges", 10).unwrap();
        assert_eq!(
            results.iter().filter(|r| r.chunk_id == multi).count(),
            1,
            "a multi-sentence chunk must collapse to a single result"
        );
        assert_eq!(
            results.iter().filter(|r| r.chunk_id == single).count(),
            1,
            "a distinct single-sentence chunk must not be collapsed away"
        );
        assert_eq!(results.len(), 2, "exactly the two distinct chunks survive");
    }

    #[test]
    fn test_code_identifiers() {
        let index = Bm25Index::new().unwrap();
        let tenant = create_test_tenant();
        let chunk_id = ChunkId::new();

        let sentences = vec!["snake_case_function and camelCaseMethod examples".to_string()];

        index.insert(&tenant, &chunk_id, &sentences).unwrap();

        // Snake case components should be searchable
        let results = index.search(&tenant, "snake", 10).unwrap();
        assert!(!results.is_empty(), "should find 'snake' from snake_case");

        let results = index.search(&tenant, "case", 10).unwrap();
        assert!(!results.is_empty(), "should find 'case' from snake_case");

        // Camel case components should be searchable
        let results = index.search(&tenant, "camel", 10).unwrap();
        assert!(!results.is_empty(), "should find 'camel' from camelCase");

        let results = index.search(&tenant, "method", 10).unwrap();
        assert!(
            !results.is_empty(),
            "should find 'method' from camelCaseMethod"
        );
    }

    #[test]
    fn test_doc_count() {
        let index = Bm25Index::new().unwrap();
        let tenant_a = TenantId::new("tenant_a").unwrap();
        let tenant_b = TenantId::new("tenant_b").unwrap();

        // Insert 3 sentences for tenant_a
        index
            .insert(
                &tenant_a,
                &ChunkId::new(),
                &["sentence 1".to_string(), "sentence 2".to_string()],
            )
            .unwrap();

        // Insert 1 sentence for tenant_b
        index
            .insert(&tenant_b, &ChunkId::new(), &["other".to_string()])
            .unwrap();

        // Check counts
        assert_eq!(index.doc_count(&tenant_a).unwrap(), 2);
        assert_eq!(index.doc_count(&tenant_b).unwrap(), 1);
    }

    #[test]
    fn test_empty_query() {
        let index = Bm25Index::new().unwrap();
        let tenant = create_test_tenant();

        // Empty query should not crash
        let results = index.search(&tenant, "", 10);
        // May return error or empty results, but should not panic
        assert!(results.is_ok() || results.is_err());
    }

    #[test]
    fn test_special_characters() {
        let index = Bm25Index::new().unwrap();
        let tenant = create_test_tenant();
        let chunk_id = ChunkId::new();

        let sentences = vec![
            "Error: SQLITE_BUSY at line 42".to_string(),
            "fn main() -> Result<(), Error>".to_string(),
        ];

        index.insert(&tenant, &chunk_id, &sentences).unwrap();

        // Should find content with special chars
        let results = index.search(&tenant, "SQLITE", 10).unwrap();
        assert!(!results.is_empty(), "should find SQLITE");

        let results = index.search(&tenant, "Error", 10).unwrap();
        assert!(!results.is_empty(), "should find Error");
    }

    #[test]
    fn test_natural_language_query_with_punctuation() {
        let index = Bm25Index::new().unwrap();
        let tenant = create_test_tenant();
        let chunk_id = ChunkId::new();

        let sentences = vec![
            "Verify user identity with OAuth access tokens".to_string(),
            "Identity verification checks token signatures".to_string(),
        ];
        index.insert(&tenant, &chunk_id, &sentences).unwrap();

        let results = index.search(&tenant, "How do I verify a user's identity?", 10);
        assert!(
            results.is_ok(),
            "punctuated natural-language query should not error"
        );
    }

    #[test]
    fn test_unbalanced_quote_query_does_not_error() {
        let index = Bm25Index::new().unwrap();
        let tenant = create_test_tenant();
        let chunk_id = ChunkId::new();
        index
            .insert(
                &tenant,
                &chunk_id,
                &["identity verification flow".to_string()],
            )
            .unwrap();

        let results = index.search(&tenant, "\"identity verification", 10);
        assert!(results.is_ok(), "unbalanced quote query should not error");
    }

    #[test]
    fn test_benchmark_choice_query_with_brackets_does_not_error() {
        let index = Bm25Index::new().unwrap();
        let tenant = create_test_tenant();
        let chunk_id = ChunkId::new();
        index
            .insert(
                &tenant,
                &chunk_id,
                &[
                    "Debbie sat with Stuart and Brent Tarleton on the porch of Tara.".to_string(),
                    "Debbie gazed out the window, eager to see her friend arrive.".to_string(),
                ],
            )
            .unwrap();

        let query = "Search Archival Memory, complete the task below:\n\
These are the events that have already occurred:\n\
1. Debbie sat with Stuart and Brent Tarleton on the porch of Tara.\n\n\
Below is a list of possible subsequent events:\n\
['Debbie gazed out the window, eager to see her friend arrive.', \
\"Debbie leaned against the fence, excitedly watching for her neighbor's dog.\"]";

        let results = index.search(&tenant, query, 10);
        assert!(
            results.is_ok(),
            "benchmark multiple-choice query should not error"
        );
        assert!(
            !results.unwrap().is_empty(),
            "plain-token fallback should still retrieve matches"
        );
    }

    /// Regression test for the "Index already exists" silent-failure bug:
    /// `Bm25Index::with_path` used to call `Index::create_in_dir`
    /// unconditionally, so restarting a daemon that had persisted a sparse
    /// index always failed and silently disabled hybrid search.
    #[test]
    fn test_persistent_index_reopens_without_error() {
        let tmp = tempfile::TempDir::new().unwrap();
        let path = tmp.path().join("bm25");

        let tenant = create_test_tenant();
        let chunk_id = ChunkId::new();

        {
            let index = Bm25Index::with_path(Some(path.clone())).unwrap();
            index
                .insert(
                    &tenant,
                    &chunk_id,
                    &["persistent bm25 reopen sentinel".to_string()],
                )
                .unwrap();
            index.commit().unwrap();
            // drop the index; writer lock released
        }

        // Reopen the same directory. Before the fix this call returned
        // "Index already exists" and the caller disabled hybrid search.
        //
        // The writer lock can still read as busy for an instant: any test in
        // this binary that spawns a process forks the whole descriptor table,
        // so a concurrently running child holds an inherited copy of this
        // lock until it reaches its own `exec`. Retry briefly so a transient
        // holder is not mistaken for the regression this test guards.
        let reopened = (0..200)
            .find_map(|_| match Bm25Index::with_path(Some(path.clone())) {
                Ok(index) => Some(index),
                Err(_) => {
                    std::thread::sleep(std::time::Duration::from_millis(10));
                    None
                }
            })
            .expect("reopening an existing bm25 directory must succeed");
        let results = reopened.search(&tenant, "sentinel", 10).unwrap();
        assert!(
            !results.is_empty(),
            "reopened index must retain previously indexed documents"
        );
    }
}