memory-indexer 0.1.0

An in-memory full-text fuzzy search indexer.
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
mod base;
mod index;
mod ngram;
mod pipeline;
mod search;
mod tokenizer;
mod types;

pub use types::{
    DocData, InMemoryIndex, PositionEncoding, SNAPSHOT_VERSION, SearchHit, SearchMode,
    SnapshotData, TermDomain,
};

pub use tokenizer::dictionary::{
    DictionaryConfig, DictionaryLanguage, DictionarySegmenter, ScriptDictionary,
    train_dictionary_config,
};

#[cfg(test)]
mod tests {
    use super::types::{DomainLengths, MatchedTerm, TermFrequency};
    use super::*;
    use std::collections::{HashMap, HashSet};
    use tempfile::tempdir;

    const INDEX: &str = "test-index";
    const DOC_CN: &str = "doc-cn";
    const DOC_EN: &str = "doc-en";
    const DOC_JP: &str = "doc-jp";

    fn assert_contains_doc(results: &[(String, f64)], doc_id: &str) {
        assert!(
            results.iter().any(|(id, _)| id == doc_id),
            "expected results to contain doc {doc_id}, got {:?}",
            results
        );
    }

    fn domain_term_dict<'a>(
        index: &'a InMemoryIndex,
        domain: TermDomain,
    ) -> Option<&'a std::collections::HashSet<String>> {
        index
            .domains
            .get(INDEX)
            .and_then(|domains| domains.get(&domain))
            .map(|d| &d.term_dict)
    }

    fn domain_ngram_index<'a>(
        index: &'a InMemoryIndex,
        domain: TermDomain,
    ) -> Option<&'a std::collections::HashMap<String, Vec<String>>> {
        index
            .domains
            .get(INDEX)
            .and_then(|domains| domains.get(&domain))
            .map(|d| &d.ngram_index)
    }

    #[test]
    fn chinese_full_pinyin_search() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_CN, "你好世界", true);

        let hits = index.search(INDEX, "nihao");
        assert_contains_doc(&hits, DOC_CN);
    }

    #[test]
    fn chinese_initials_search() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_CN, "你好世界", true);

        let hits = index.search(INDEX, "nh");
        assert_contains_doc(&hits, DOC_CN);
    }

    #[test]
    fn chinese_initials_prefix_search() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_CN, "你好世界", true);

        let hits = index.search(INDEX, "nhs");
        assert_contains_doc(&hits, DOC_CN);

        let exact = index.get_matches(INDEX, DOC_CN, "nhsj");
        let prefix = index.get_matches(INDEX, DOC_CN, "nhs");
        assert!(!exact.is_empty());
        assert!(!prefix.is_empty());
        assert!(
            prefix.iter().any(|p| exact.iter().any(|e| e.0 == p.0)),
            "prefix highlight should align to original start"
        );
    }

    #[test]
    fn chinese_full_pinyin_prefix_search() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_CN, "你好世界", true);

        let hits = index.search(INDEX, "nih");
        assert_contains_doc(&hits, DOC_CN);

        let exact = index.get_matches(INDEX, DOC_CN, "nihaoshijie");
        let prefix = index.get_matches(INDEX, DOC_CN, "nih");
        assert!(!exact.is_empty());
        assert!(!prefix.is_empty());
        assert!(
            prefix.iter().any(|p| exact.iter().any(|e| e.0 == p.0)),
            "prefix highlight should align to original start"
        );
    }

    #[test]
    fn pinyin_fuzzy_search() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_CN, "你好世界", true);

        let hits = index.search_hits(INDEX, "nihap");
        assert!(
            hits.iter()
                .any(|h| h.doc_id == DOC_CN && !h.matched_terms.is_empty()),
            "expected matched pinyin term in fuzzy hits: {:?}",
            hits.iter()
                .map(|h| (&h.doc_id, &h.matched_terms))
                .collect::<Vec<_>>()
        );

        let fuzzy_original = index.search_with_mode(INDEX, "nihap", SearchMode::Fuzzy);
        assert!(
            fuzzy_original.is_empty(),
            "expected SearchMode::Fuzzy to only search original domain, got {:?}",
            fuzzy_original
        );
    }

    #[test]
    fn original_aux_index_excludes_non_ascii_terms() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_CN, "你好世界", true);

        if let Some(term_dict) = domain_term_dict(&index, TermDomain::Original) {
            assert!(term_dict.contains("你好"));
            assert!(term_dict.contains("世界"));
        }
    }

    #[test]
    fn english_fuzzy_search() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_EN, "fuzzy search handles typos", true);

        let hits = index.search_hits(INDEX, "fuzze");
        assert!(hits.iter().any(|h| {
            h.doc_id == DOC_EN
                && h.matched_terms
                    .iter()
                    .any(|t| t.term == "fuzzy" && t.domain == TermDomain::Original)
        }));
    }

    #[test]
    fn english_query_splits_separators_and_lowercases() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_EN, "MEMORY-INDEXER", true);

        let hits = index.search_with_mode(INDEX, "memory-indexer", SearchMode::Exact);
        assert_contains_doc(&hits, DOC_EN);
    }

    #[test]
    fn fuzzy_search_allows_alphanumeric_terms() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_EN, "version2 stable", true);

        let hits = index.search_with_mode(INDEX, "versoin2", SearchMode::Fuzzy);
        assert_contains_doc(&hits, DOC_EN);
    }

    #[test]
    fn fuzzy_search_handles_separated_query_terms() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_EN, "memory-indexer", true);

        let hits = index.search_with_mode(INDEX, "memry-indexer", SearchMode::Fuzzy);
        assert_contains_doc(&hits, DOC_EN);
    }

    #[test]
    fn fuzzy_search_handles_short_terms() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_EN, "go go", true);

        let hits = index.search_with_mode(INDEX, "go", SearchMode::Fuzzy);
        assert_contains_doc(&hits, DOC_EN);
    }

    #[test]
    fn pinyin_highlight_uses_original_positions() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_CN, "你好世界", true);

        let direct = index.get_matches(INDEX, DOC_CN, "你好");
        assert!(
            !direct.is_empty(),
            "expected direct chinese match to have positions"
        );

        let pinyin = index.get_matches(INDEX, DOC_CN, "nihao");
        assert_eq!(pinyin, direct);
    }

    #[test]
    fn highlight_prefers_original_for_mixed_scripts() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_CN, "hello 世界", true);

        let hits = index.search_hits(INDEX, "hello shi");
        let Some(hit) = hits.iter().find(|h| h.doc_id == DOC_CN) else {
            panic!("expected hit for mixed script query");
        };
        let matches = index.get_matches_for_matched_terms(INDEX, DOC_CN, &hit.matched_terms);
        let content = index.get_doc(INDEX, DOC_CN).unwrap();
        let slices: Vec<String> = matches
            .iter()
            .map(|(s, e)| utf16_slice(&content, *s, *e))
            .collect();
        assert!(
            slices.iter().any(|s| s == "hello"),
            "expected original spans for mixed script matches, got {:?}",
            slices
        );
        if slices.iter().any(|s| s.chars().any(|c| !c.is_ascii())) {
            assert!(
                slices.iter().any(|s| s == "世界"),
                "expected CJK spans for mixed script matches, got {:?}",
                slices
            );
        }
    }

    #[test]
    fn pinyin_prefix_highlight_uses_original_spans() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_CN, "你好世界", true);

        let hits = index.search_hits(INDEX, "nih");
        let Some(hit) = hits.iter().find(|h| h.doc_id == DOC_CN) else {
            panic!("expected prefix pinyin hit");
        };
        let matches = index.get_matches_for_matched_terms(INDEX, DOC_CN, &hit.matched_terms);
        let direct = index.get_matches(INDEX, DOC_CN, "你好");
        assert_eq!(
            matches, direct,
            "prefix highlight should map back to original spans"
        );
    }

    #[test]
    fn pinyin_highlight_handles_trailing_ascii() {
        let mut index = InMemoryIndex::with_position_encoding(PositionEncoding::Utf16);
        index.add_doc(
            INDEX,
            DOC_CN,
            "美光将在全球内存供应短缺之际退出消费级内存业务",
            true,
        );

        let hits = index.search_hits(INDEX, "neicun");
        let hit = hits
            .iter()
            .find(|h| h.doc_id == DOC_CN)
            .unwrap_or_else(|| panic!("expected hit for neicun, got {:?}", hits));
        let matches = index.get_matches_for_matched_terms(INDEX, DOC_CN, &hit.matched_terms);
        assert!(
            !matches.is_empty(),
            "expected highlight spans for pinyin match, got none"
        );
        let content = index.get_doc(INDEX, DOC_CN).unwrap();
        let slices: Vec<String> = matches
            .iter()
            .map(|(s, e)| utf16_slice(&content, *s, *e))
            .collect();
        assert!(
            slices.iter().all(|s| s == "内存"),
            "expected highlights to stay on original term, got {:?}",
            slices
        );
    }

    fn utf16_slice(content: &str, start: u32, end: u32) -> String {
        let mut utf16_pos = 0u32;
        let mut start_byte = 0usize;
        let mut end_byte = content.len();
        for (idx, ch) in content.char_indices() {
            if utf16_pos == start {
                start_byte = idx;
            }
            utf16_pos += ch.len_utf16() as u32;
            if utf16_pos == end {
                end_byte = idx + ch.len_utf8();
                break;
            }
        }
        content[start_byte..end_byte].to_string()
    }

    #[test]
    fn exact_search_prefers_original_terms() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_EN, "nihao greeting", true);
        index.add_doc(INDEX, DOC_CN, "你好世界", true);

        let exact_hits = index.search_with_mode(INDEX, "nihao", SearchMode::Exact);
        assert_contains_doc(&exact_hits, DOC_EN);
        assert!(
            exact_hits.iter().all(|(id, _)| id == DOC_EN),
            "expected exact search to ignore pinyin matches, got {:?}",
            exact_hits
        );

        let auto_hits = index.search(INDEX, "nihao");
        assert_contains_doc(&auto_hits, DOC_EN);
        assert!(
            auto_hits.iter().all(|(id, _)| id != DOC_CN),
            "auto search should stop at exact matches"
        );

        let pinyin_hits = index.search_with_mode(INDEX, "nihao", SearchMode::Pinyin);
        assert_contains_doc(&pinyin_hits, DOC_CN);
    }

    #[test]
    fn japanese_ngram_search() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_JP, "こんにちは世界", true);

        let hits = index.search(INDEX, "こん");
        assert_contains_doc(&hits, DOC_JP);

        let matches = index.get_matches(INDEX, DOC_JP, "こん");
        assert!(
            !matches.is_empty(),
            "expected offsets for japanese ngram matches"
        );
    }

    #[test]
    fn kanji_adjacent_to_kana_skips_pinyin() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_JP, "東京へようこそ", true);

        let hits = index.search_with_mode(INDEX, "dongjing", SearchMode::Pinyin);
        assert!(
            hits.is_empty(),
            "kanji near kana should not derive pinyin, got {:?}",
            hits
        );
    }

    #[test]
    fn exact_search_applies_minimum_should_match() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, "doc-2-terms", "apple banana", true);
        index.add_doc(INDEX, "doc-3-terms", "apple banana cherry", true);
        index.add_doc(INDEX, "doc-1-term", "apple", true);

        let hits = index.search_with_mode(INDEX, "apple banana cherry", SearchMode::Exact);

        assert_contains_doc(&hits, "doc-2-terms");
        assert_contains_doc(&hits, "doc-3-terms");
        assert!(
            !hits.iter().any(|(id, _)| id == "doc-1-term"),
            "docs below minimum_should_match should be filtered out"
        );

        let score_two = hits
            .iter()
            .find(|(id, _)| id == "doc-2-terms")
            .map(|(_, s)| *s)
            .unwrap();
        let score_three = hits
            .iter()
            .find(|(id, _)| id == "doc-3-terms")
            .map(|(_, s)| *s)
            .unwrap();
        assert!(
            score_three > score_two,
            "more matched terms should score higher: {} vs {}",
            score_three,
            score_two
        );
    }

    #[test]
    fn pinyin_polyphonic_variants_for_short_tokens() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_CN, "重庆火锅", true);

        let hits_zhong = index.search_with_mode_hits(INDEX, "zhongqing", SearchMode::Pinyin);
        assert!(
            hits_zhong.iter().any(|h| h.doc_id == DOC_CN),
            "expected zhongqing variant to hit"
        );

        let hits_chong = index.search_with_mode_hits(INDEX, "chongqing", SearchMode::Pinyin);
        assert!(
            hits_chong.iter().any(|h| h.doc_id == DOC_CN),
            "expected chongqing variant to hit"
        );

        let matched_terms: Vec<MatchedTerm> = hits_zhong
            .into_iter()
            .find(|h| h.doc_id == DOC_CN)
            .map(|h| h.matched_terms)
            .unwrap_or_default();
        assert!(
            matched_terms
                .iter()
                .any(|t| t.term.contains("zhongqing") || t.term.contains("chongqing")),
            "expected polyphonic pinyin variants in matched_terms, got {:?}",
            matched_terms
        );
    }

    #[test]
    fn removing_doc_cleans_aux_indices() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_EN, "token removal check", true);

        index.remove_doc(INDEX, DOC_EN);

        if let Some(term_dict) = domain_term_dict(&index, TermDomain::Original) {
            assert!(
                !term_dict.contains("token"),
                "term_dict should drop removed terms"
            );
        }

        if let Some(ngram_index) = domain_ngram_index(&index, TermDomain::Original) {
            let still_contains = ngram_index
                .values()
                .any(|terms| terms.iter().any(|term| term == "token"));
            assert!(!still_contains, "ngrams should remove term entries");
        }
    }

    #[test]
    fn get_matches_for_terms_uses_matched_terms() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_EN, "memoryIndexer", true);

        let hits = index.search_hits(INDEX, "memryindexer");
        let Some(hit) = hits.iter().find(|h| h.doc_id == DOC_EN) else {
            panic!("expected hit for doc");
        };
        assert!(
            hit.matched_terms
                .iter()
                .any(|t| t.term == "memoryindexer" && t.domain == TermDomain::Original),
            "expected matched term memoryIndexer, got {:?}",
            hit.matched_terms
        );

        let matches = index.get_matches_for_matched_terms(INDEX, DOC_EN, &hit.matched_terms);
        assert!(!matches.is_empty(), "expected matches from matched_terms");
    }

    #[test]
    fn snapshot_contains_aux_indices_per_domain() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_CN, "你好世界 memory-indexer", true);

        let snapshot = index
            .get_snapshot_data(INDEX)
            .expect("snapshot should exist");

        let domains = snapshot.domains;
        let original = domains
            .get(&TermDomain::Original)
            .expect("snapshot should contain original domain");
        assert!(
            !original.term_dict.is_empty(),
            "expected original aux index to be persisted"
        );
        let pinyin_full = domains
            .get(&TermDomain::PinyinFull)
            .expect("snapshot should contain pinyin full domain");
        assert!(
            !pinyin_full.term_dict.is_empty(),
            "expected full pinyin aux index to be persisted"
        );
        let pinyin_initials = domains
            .get(&TermDomain::PinyinInitials)
            .expect("snapshot should contain pinyin initials domain");
        assert!(
            !pinyin_initials.term_dict.is_empty(),
            "expected initials pinyin aux index to be persisted"
        );
        assert!(
            !pinyin_full.ngram_index.is_empty(),
            "expected pinyin ngram index to be persisted"
        );
    }

    #[test]
    fn fullwidth_pinyin_query_hits() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_CN, "你好世界", true);

        // Full-width ASCII should normalize to ASCII and derive pinyin.
        let hits = index.search_hits(INDEX, "NIHAO");
        assert!(
            hits.iter().any(|h| h.doc_id == DOC_CN),
            "expected full-width pinyin query to hit, got {:?}",
            hits.iter()
                .map(|h| (&h.doc_id, &h.matched_terms))
                .collect::<Vec<_>>()
        );
        let matched = hits.iter().find(|h| h.doc_id == DOC_CN).and_then(|h| {
            h.matched_terms
                .iter()
                .find(|t| t.domain == TermDomain::PinyinFull)
        });
        assert!(
            matched.is_some(),
            "expected matched pinyin full term, got {:?}",
            hits.iter()
                .find(|h| h.doc_id == DOC_CN)
                .map(|h| h.matched_terms.clone())
        );
    }

    #[test]
    fn short_pinyin_fuzzy_hits() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_CN, "你好", true);

        // Missing one character should still fuzzy match via pinyin domain.
        let hits = index.search_hits(INDEX, "niha");
        assert!(
            hits.iter().any(|h| h.doc_id == DOC_CN),
            "expected fuzzy pinyin hit for short query, got {:?}",
            hits.iter()
                .map(|h| (&h.doc_id, &h.matched_terms))
                .collect::<Vec<_>>()
        );
        let matched = hits.iter().find(|h| h.doc_id == DOC_CN).and_then(|h| {
            h.matched_terms.iter().find(|t| {
                matches!(
                    t.domain,
                    TermDomain::PinyinFull | TermDomain::PinyinFullPrefix
                )
            })
        });
        assert!(
            matched.is_some(),
            "expected matched pinyin term, got {:?}",
            hits.iter()
                .find(|h| h.doc_id == DOC_CN)
                .map(|h| h.matched_terms.clone())
        );
    }

    #[test]
    fn non_ascii_auto_fuzzy_fallback() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_CN, "北京大学", true);

        // Typo on the last character should still match via non-ASCII fuzzy fallback.
        let hits = index.search_hits(INDEX, "北景大学");
        assert!(
            hits.iter().any(|h| h.doc_id == DOC_CN),
            "expected non-ascii fuzzy fallback to hit, got {:?}",
            hits.iter()
                .map(|h| (&h.doc_id, &h.matched_terms))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn mixed_script_query_hits_all_tokens() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_CN, "hello 世界", true);

        let hits = index.search_hits(INDEX, "hello 世界");
        assert!(
            hits.iter().any(|h| h.doc_id == DOC_CN),
            "expected mixed-script query to hit doc, got {:?}",
            hits.iter()
                .map(|h| (&h.doc_id, &h.matched_terms))
                .collect::<Vec<_>>()
        );
        let matched = hits
            .iter()
            .find(|h| h.doc_id == DOC_CN)
            .map(|h| h.matched_terms.clone())
            .unwrap_or_default();
        assert!(
            matched
                .iter()
                .any(|t| t.term == "hello" && t.domain == TermDomain::Original),
            "expected matched original term hello, got {:?}",
            matched
        );
        assert!(
            matched.iter().any(|t| t.term == "世界"),
            "expected matched CJK term 世界, got {:?}",
            matched
        );
    }

    #[test]
    fn chinese_oov_fuzzy_recall() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_CN, "明博", true);

        // Typo on the second char should still recall via non-ASCII fuzzy fallback.
        let hits = index.search_hits(INDEX, "明搏");
        assert!(
            hits.iter().any(|h| h.doc_id == DOC_CN),
            "expected OOV chinese fuzzy to hit, got {:?}",
            hits.iter()
                .map(|h| (&h.doc_id, &h.matched_terms))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn load_snapshot_rebuilds_missing_aux_indices() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, DOC_CN, "你好世界", true);

        let mut snapshot = index
            .get_snapshot_data(INDEX)
            .expect("snapshot should exist");
        if let Some(full) = snapshot.domains.get_mut(&TermDomain::PinyinFull) {
            full.term_dict.clear();
            full.ngram_index.clear();
        }
        if let Some(initials) = snapshot.domains.get_mut(&TermDomain::PinyinInitials) {
            initials.term_dict.clear();
            initials.ngram_index.clear();
        }

        let mut restored = InMemoryIndex::default();
        restored.load_snapshot(INDEX, snapshot);

        let hits = restored.search_hits(INDEX, "nihap");
        assert!(
            hits.iter().any(|hit| hit.doc_id == DOC_CN),
            "expected rebuilt pinyin aux indices to allow fuzzy hits"
        );
        assert!(
            restored
                .domains
                .get(INDEX)
                .and_then(|domains| domains.get(&TermDomain::PinyinFull))
                .is_some_and(|d| !d.term_dict.is_empty()),
            "expected pinyin full dictionary to be rebuilt from doc data"
        );
        assert!(
            restored
                .domains
                .get(INDEX)
                .and_then(|domains| domains.get(&TermDomain::PinyinInitials))
                .is_some_and(|d| !d.term_dict.is_empty()),
            "expected pinyin initials dictionary to be rebuilt from doc data"
        );
    }

    #[test]
    fn fuzzy_msm_filters_insufficient_matches() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, "doc-long", "apple banana", true);
        index.add_doc(INDEX, "doc-short", "apple", true);

        let hits = index.search_with_mode_hits(INDEX, "applr banaan", SearchMode::Fuzzy);
        assert!(
            hits.iter().any(|h| h.doc_id == "doc-long"),
            "expected fuzzy msm to keep doc with both terms, got {:?}",
            hits
        );
        assert!(
            hits.iter().all(|h| h.doc_id != "doc-short"),
            "docs below min_should_match should be filtered out: {:?}",
            hits
        );
    }

    #[test]
    fn short_cjk_fuzzy_recall_uses_2gram() {
        let mut index = InMemoryIndex::default();
        index.add_doc(INDEX, "doc-short-cjk", "方案", true);

        let hits = index.search_hits(INDEX, "方桉");
        assert!(
            hits.iter().any(|h| h.doc_id == "doc-short-cjk"),
            "expected 2-gram fuzzy recall for short CJK tokens, got {:?}",
            hits
        );
    }

    #[test]
    fn snapshot_v2_rebuilds_derived_spans() {
        let mut term_pos: HashMap<String, Vec<(u32, u32)>> = HashMap::new();
        term_pos.insert("你好".to_string(), vec![(0, 6)]);
        term_pos.insert("nihao".to_string(), vec![(0, 6)]);

        let mut term_freqs: HashMap<String, TermFrequency> = HashMap::new();
        let mut freq_original = TermFrequency::default();
        freq_original.increment(TermDomain::Original);
        term_freqs.insert("你好".to_string(), freq_original);
        let mut freq_pinyin = TermFrequency::default();
        freq_pinyin.increment(TermDomain::PinyinFull);
        term_freqs.insert("nihao".to_string(), freq_pinyin);

        let mut docs = HashMap::new();
        docs.insert(
            DOC_CN.to_string(),
            DocData {
                content: "你好".to_string(),
                doc_len: 2,
                term_pos,
                term_freqs,
                domain_doc_len: DomainLengths::default(),
                derived_terms: HashMap::new(),
            },
        );

        let snapshot = SnapshotData {
            version: 2,
            docs,
            domains: HashMap::new(),
        };

        let mut index = InMemoryIndex::default();
        index.load_snapshot(INDEX, snapshot);

        let hits = index.search_hits(INDEX, "nihao");
        assert!(
            hits.iter().any(|h| h.doc_id == DOC_CN),
            "expected legacy snapshot to rebuild pinyin hits, got {:?}",
            hits
        );

        let matches = index.get_matches(INDEX, DOC_CN, "nihao");
        assert!(
            matches.iter().any(|(s, e)| (*s, *e) == (0, 2)),
            "expected derived spans converted to utf16, got {:?}",
            matches
        );
    }

    #[test]
    fn dictionary_load_and_fallback() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("dict.json");

        let mut entries = HashSet::new();
        entries.insert("こんにちは".to_string());
        let config = DictionaryConfig {
            japanese: Some(ScriptDictionary {
                version: Some("v1".to_string()),
                entries,
            }),
            hangul: None,
        };

        std::fs::write(&path, serde_json::to_vec(&config).unwrap()).unwrap();
        let loaded: DictionaryConfig =
            serde_json::from_slice(&std::fs::read(&path).unwrap()).expect("should deserialize");

        let mut index = InMemoryIndex::with_dictionary_config(loaded.clone());
        index.add_doc(INDEX, DOC_JP, "こんにちは世界", true);

        let hits = index.search_with_mode_hits(INDEX, "こんにちは", SearchMode::Exact);
        assert!(
            hits.iter().any(|h| h.doc_id == DOC_JP),
            "expected dictionary-backed search hit, got {:?}",
            hits
        );
        if let Some(dict) = domain_term_dict(&index, TermDomain::Original) {
            assert!(
                dict.contains("こんにちは"),
                "expected dictionary tokens to be indexed, got {:?}",
                dict
            );
        }

        let mut fallback_index = InMemoryIndex::default();
        fallback_index.add_doc(INDEX, DOC_JP, "こんにちは世界", true);
        let fallback_hits =
            fallback_index.search_with_mode_hits(INDEX, "こんにちは", SearchMode::Exact);
        assert!(
            fallback_hits.iter().any(|h| h.doc_id == DOC_JP),
            "expected fallback tokenization to still recall doc, got {:?}",
            fallback_hits
        );
    }
}