codemem-engine 0.19.0

Domain logic engine for Codemem: indexing, hooks, watching, scoring, recall, consolidation
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
use super::*;

// ── Tokenizer tests ─────────────────────────────────────────────────

#[test]
fn tokenize_camel_case() {
    let tokens = tokenize("processRequest");
    assert!(tokens.contains(&"process".to_string()));
    assert!(tokens.contains(&"request".to_string()));
}

#[test]
fn tokenize_pascal_case() {
    let tokens = tokenize("ProcessRequest");
    assert!(tokens.contains(&"process".to_string()));
    assert!(tokens.contains(&"request".to_string()));
}

#[test]
fn tokenize_snake_case() {
    let tokens = tokenize("process_request");
    assert!(tokens.contains(&"process".to_string()));
    assert!(tokens.contains(&"request".to_string()));
}

#[test]
fn tokenize_mixed_case_acronym() {
    let tokens = tokenize("getHTTPResponse");
    assert!(tokens.contains(&"get".to_string()));
    assert!(tokens.contains(&"http".to_string()));
    assert!(tokens.contains(&"response".to_string()));
}

#[test]
fn tokenize_filters_short_tokens() {
    let tokens = tokenize("a b cd ef");
    // "a" and "b" should be filtered (< 2 chars)
    assert!(!tokens.contains(&"a".to_string()));
    assert!(!tokens.contains(&"b".to_string()));
    assert!(tokens.contains(&"cd".to_string()));
    assert!(tokens.contains(&"ef".to_string()));
}

#[test]
fn tokenize_lowercases() {
    let tokens = tokenize("HELLO World");
    assert!(tokens.contains(&"hello".to_string()));
    assert!(tokens.contains(&"world".to_string()));
}

#[test]
fn tokenize_punctuation_splitting() {
    let tokens = tokenize("foo.bar::baz-qux");
    assert!(tokens.contains(&"foo".to_string()));
    assert!(tokens.contains(&"bar".to_string()));
    assert!(tokens.contains(&"baz".to_string()));
    assert!(tokens.contains(&"qux".to_string()));
}

#[test]
fn tokenize_digit_boundaries() {
    let tokens = tokenize("item2count");
    assert!(tokens.contains(&"item".to_string()));
    assert!(tokens.contains(&"count".to_string()));
}

#[test]
fn tokenize_empty_string() {
    let tokens = tokenize("");
    assert!(tokens.is_empty());
}

#[test]
fn tokenize_code_content() {
    let tokens = tokenize("fn computeScore(memory: &MemoryNode) -> f64");
    assert!(tokens.contains(&"fn".to_string()));
    assert!(tokens.contains(&"compute".to_string()));
    assert!(tokens.contains(&"score".to_string()));
    assert!(tokens.contains(&"memory".to_string()));
    assert!(tokens.contains(&"node".to_string()));
    // "f64" splits at digit boundary into "f" (filtered: <2 chars) and "64"
    assert!(tokens.contains(&"64".to_string()));
}

// ── BM25 scoring tests ──────────────────────────────────────────────

#[test]
fn bm25_relevant_doc_scores_higher() {
    let docs = vec![
        (
            "d1".to_string(),
            "rust ownership and borrowing rules".to_string(),
        ),
        (
            "d2".to_string(),
            "python garbage collection internals".to_string(),
        ),
    ];
    let index = Bm25Index::build(&docs);

    let score_d1 = index.score("rust ownership", "d1");
    let score_d2 = index.score("rust ownership", "d2");

    assert!(
        score_d1 > score_d2,
        "relevant doc should score higher: d1={score_d1}, d2={score_d2}"
    );
}

#[test]
fn bm25_idf_rare_terms_score_higher() {
    // "quantum" appears in 1 doc, "the" appears in all 3
    let docs = vec![
        ("d1".to_string(), "the quick brown fox".to_string()),
        ("d2".to_string(), "the lazy dog jumps".to_string()),
        (
            "d3".to_string(),
            "the quantum computing revolution".to_string(),
        ),
    ];
    let index = Bm25Index::build(&docs);

    let score_common = index.score("the", "d1");
    let score_rare = index.score("quantum", "d3");

    assert!(
        score_rare > score_common,
        "rare term should score higher: rare={score_rare}, common={score_common}"
    );
}

#[test]
fn bm25_empty_query_returns_zero() {
    let docs = vec![("d1".to_string(), "some content here".to_string())];
    let index = Bm25Index::build(&docs);

    assert_eq!(index.score("", "d1"), 0.0);
}

#[test]
fn bm25_empty_index_returns_zero() {
    let index = Bm25Index::new();
    assert_eq!(index.score("test query", "nonexistent"), 0.0);
}

#[test]
fn bm25_unknown_doc_returns_zero() {
    let docs = vec![("d1".to_string(), "some content".to_string())];
    let index = Bm25Index::build(&docs);
    assert_eq!(index.score("content", "nonexistent"), 0.0);
}

#[test]
fn bm25_no_matching_terms_returns_zero() {
    let docs = vec![("d1".to_string(), "alpha beta gamma".to_string())];
    let index = Bm25Index::build(&docs);
    assert_eq!(index.score("delta epsilon", "d1"), 0.0);
}

#[test]
fn bm25_score_in_zero_one_range() {
    let docs = vec![
        (
            "d1".to_string(),
            "rust memory safety and ownership".to_string(),
        ),
        ("d2".to_string(), "python dynamic typing system".to_string()),
    ];
    let index = Bm25Index::build(&docs);

    let score = index.score("rust memory", "d1");
    assert!(score >= 0.0, "score should be >= 0: {score}");
    assert!(score <= 1.0, "score should be <= 1: {score}");
}

#[test]
fn bm25_incremental_add() {
    let mut index = Bm25Index::new();
    index.add_document("d1", "rust programming language");
    assert_eq!(index.doc_count, 1);

    index.add_document("d2", "python programming language");
    assert_eq!(index.doc_count, 2);

    // "rust" is in 1 of 2 docs => should have decent IDF
    let score = index.score("rust", "d1");
    assert!(score > 0.0);
}

#[test]
fn bm25_incremental_remove() {
    let mut index = Bm25Index::new();
    index.add_document("d1", "rust programming");
    index.add_document("d2", "python programming");
    assert_eq!(index.doc_count, 2);

    index.remove_document("d1");
    assert_eq!(index.doc_count, 1);

    // d1 no longer exists
    assert_eq!(index.score("rust", "d1"), 0.0);

    // d2 still works
    let score = index.score("python", "d2");
    assert!(score > 0.0);
}

#[test]
fn bm25_remove_nonexistent_is_noop() {
    let mut index = Bm25Index::new();
    index.add_document("d1", "test content");
    index.remove_document("nonexistent");
    assert_eq!(index.doc_count, 1);
}

#[test]
fn bm25_replace_document() {
    let mut index = Bm25Index::new();
    index.add_document("d1", "old content about rust");
    index.add_document("d1", "new content about python");
    assert_eq!(index.doc_count, 1);

    // Should match the new content, not old
    let score_python = index.score("python", "d1");
    let score_rust = index.score("rust", "d1");
    assert!(score_python > 0.0);
    assert_eq!(score_rust, 0.0);
}

#[test]
fn bm25_build_from_documents() {
    let docs = vec![
        ("d1".to_string(), "hello world".to_string()),
        ("d2".to_string(), "goodbye world".to_string()),
    ];
    let index = Bm25Index::build(&docs);
    assert_eq!(index.doc_count, 2);
}

#[test]
fn bm25_score_text_works_without_indexing_document() {
    let docs = vec![
        ("d1".to_string(), "rust safety".to_string()),
        ("d2".to_string(), "python typing".to_string()),
    ];
    let index = Bm25Index::build(&docs);

    // Score arbitrary text that's not in the index
    let score = index.score_text("rust safety", "rust ownership and safety features");
    assert!(score > 0.0);
}

#[test]
fn bm25_code_aware_scoring() {
    // camelCase and snake_case should split and match
    let docs = vec![
        (
            "d1".to_string(),
            "processRequest handles incoming data".to_string(),
        ),
        (
            "d2".to_string(),
            "unrelated database migration code".to_string(),
        ),
    ];
    let index = Bm25Index::build(&docs);

    // Query with snake_case should match camelCase doc
    let score_d1 = index.score("process_request", "d1");
    let score_d2 = index.score("process_request", "d2");
    assert!(
        score_d1 > score_d2,
        "code-aware match should work across naming conventions: d1={score_d1}, d2={score_d2}"
    );
}

#[test]
fn bm25_term_frequency_matters() {
    let docs = vec![
        ("d1".to_string(), "rust rust rust is great".to_string()),
        ("d2".to_string(), "rust is a language".to_string()),
    ];
    let index = Bm25Index::build(&docs);

    let score_d1 = index.score("rust", "d1");
    let score_d2 = index.score("rust", "d2");

    // d1 mentions "rust" 3 times, should score higher (though BM25 saturates)
    assert!(
        score_d1 > score_d2,
        "higher tf should give higher score: d1={score_d1}, d2={score_d2}"
    );
}

#[test]
fn bm25_multiple_query_terms() {
    let docs = vec![
        ("d1".to_string(), "rust ownership borrowing".to_string()),
        ("d2".to_string(), "rust generic types".to_string()),
        ("d3".to_string(), "python duck typing".to_string()),
    ];
    let index = Bm25Index::build(&docs);

    // d1 matches both "rust" and "ownership"
    let score_d1 = index.score("rust ownership", "d1");
    // d2 matches only "rust"
    let score_d2 = index.score("rust ownership", "d2");
    // d3 matches neither
    let score_d3 = index.score("rust ownership", "d3");

    assert!(
        score_d1 > score_d2,
        "more matching terms should score higher"
    );
    assert!(score_d2 > score_d3, "some match better than no match");
}

// ── Split function unit tests ───────────────────────────────────────

#[test]
fn split_camel_case_basic() {
    let parts = split_camel_case("processRequest");
    assert_eq!(parts, vec!["process", "Request"]);
}

#[test]
fn split_camel_case_pascal() {
    let parts = split_camel_case("ProcessRequest");
    assert_eq!(parts, vec!["Process", "Request"]);
}

#[test]
fn split_camel_case_acronym() {
    let parts = split_camel_case("HTMLParser");
    assert_eq!(parts, vec!["HTML", "Parser"]);
}

#[test]
fn split_camel_case_mid_acronym() {
    let parts = split_camel_case("getHTTPResponse");
    assert_eq!(parts, vec!["get", "HTTP", "Response"]);
}

#[test]
fn split_camel_case_all_lower() {
    let parts = split_camel_case("lowercase");
    assert_eq!(parts, vec!["lowercase"]);
}

#[test]
fn split_camel_case_all_upper() {
    let parts = split_camel_case("ALLCAPS");
    assert_eq!(parts, vec!["ALLCAPS"]);
}

#[test]
fn split_camel_case_empty() {
    let parts = split_camel_case("");
    assert!(parts.is_empty());
}

#[test]
fn split_on_punctuation_basic() {
    let parts = split_on_punctuation("foo.bar");
    assert_eq!(parts, vec!["foo", "bar"]);
}

#[test]
fn split_on_punctuation_multiple() {
    let parts = split_on_punctuation("a::b->c.d");
    assert_eq!(parts, vec!["a", "b", "c", "d"]);
}

// ── Test #1: BM25 tokenization consistency ──────────────────────────
// score() tokenizes internally; score_with_tokens_str() uses pre-tokenized input.
// They must produce identical results.

#[test]
fn score_with_tokens_str_matches_score() {
    let mut index = Bm25Index::new();
    index.add_document("d1", "processRequest handles incoming data");
    index.add_document("d2", "unrelated database migration code");

    let query = "processRequest";
    let tokens = tokenize(query);
    let token_refs: Vec<&str> = tokens.iter().map(|s| s.as_str()).collect();

    let score_direct = index.score(query, "d1");
    let score_tokens = index.score_with_tokens_str(&token_refs, "d1");

    assert!(
        (score_direct - score_tokens).abs() < 1e-10,
        "score() and score_with_tokens_str() must match: direct={score_direct}, tokens={score_tokens}"
    );
}

#[test]
fn score_text_with_tokens_str_matches_score_text() {
    let mut index = Bm25Index::new();
    // Need at least one doc for IDF stats
    index.add_document("d1", "some background document for statistics");

    let query = "parseFunction";
    let text = "parseFunction extracts AST nodes from source code";

    let tokens = tokenize(query);
    let token_refs: Vec<&str> = tokens.iter().map(|s| s.as_str()).collect();

    let score_direct = index.score_text(query, text);
    let score_tokens = index.score_text_with_tokens_str(&token_refs, text);

    assert!(
        (score_direct - score_tokens).abs() < 1e-10,
        "score_text() and score_text_with_tokens_str() must match: direct={score_direct}, tokens={score_tokens}"
    );
}

// ── BM25 serialization round-trip tests ─────────────────────────────

#[test]
fn bm25_serialize_roundtrip_scores_match() {
    let docs: Vec<(String, String)> = (0..12)
        .map(|i| {
            (
                format!("doc{i}"),
                format!(
                    "document number {i} about rust programming language features and ownership"
                ),
            )
        })
        .collect();
    let original = Bm25Index::build(&docs);

    // Collect scores before serialization
    let query = "rust ownership";
    let mut original_scores: Vec<(String, f64)> = docs
        .iter()
        .map(|(id, _)| (id.clone(), original.score(query, id)))
        .collect();
    original_scores.sort_by(|a, b| a.0.cmp(&b.0));

    // Serialize and deserialize
    let bytes = original.serialize();
    assert!(!bytes.is_empty(), "serialized bytes should not be empty");

    let restored = Bm25Index::deserialize(&bytes).expect("deserialization should succeed");

    // Verify all scores match
    let mut restored_scores: Vec<(String, f64)> = docs
        .iter()
        .map(|(id, _)| (id.clone(), restored.score(query, id)))
        .collect();
    restored_scores.sort_by(|a, b| a.0.cmp(&b.0));

    assert_eq!(original_scores.len(), restored_scores.len());
    for (orig, rest) in original_scores.iter().zip(restored_scores.iter()) {
        assert_eq!(orig.0, rest.0, "doc IDs should match");
        assert!(
            (orig.1 - rest.1).abs() < 1e-10,
            "scores should match after round-trip for {}: original={}, restored={}",
            orig.0,
            orig.1,
            rest.1
        );
    }
}

#[test]
fn bm25_serialize_roundtrip_preserves_doc_count() {
    let docs: Vec<(String, String)> = (0..10)
        .map(|i| (format!("d{i}"), format!("content for document {i} xyz")))
        .collect();
    let original = Bm25Index::build(&docs);
    assert_eq!(original.doc_count, 10);

    let bytes = original.serialize();
    let restored = Bm25Index::deserialize(&bytes).unwrap();
    assert_eq!(
        restored.doc_count, 10,
        "doc_count should be preserved through serialization"
    );
}

#[test]
fn bm25_empty_index_serialization_roundtrip() {
    let original = Bm25Index::new();
    assert_eq!(original.doc_count, 0);

    let bytes = original.serialize();
    let restored = Bm25Index::deserialize(&bytes).unwrap();
    assert_eq!(restored.doc_count, 0, "empty index should remain empty");
    assert_eq!(
        restored.score("test", "nonexistent"),
        0.0,
        "empty restored index should return 0 for any query"
    );
}

#[test]
fn bm25_roundtrip_with_removed_documents() {
    let mut index = Bm25Index::new();
    index.add_document("d1", "rust programming language features");
    index.add_document("d2", "python dynamic typing system");
    index.add_document("d3", "javascript async await promises");
    index.remove_document("d2");

    assert_eq!(index.doc_count, 2);

    let bytes = index.serialize();
    let restored = Bm25Index::deserialize(&bytes).unwrap();

    assert_eq!(restored.doc_count, 2, "doc_count should reflect removals");
    assert_eq!(
        restored.score("python", "d2"),
        0.0,
        "removed document should not be scoreable after round-trip"
    );
    assert!(
        restored.score("rust", "d1") > 0.0,
        "remaining document should still score after round-trip"
    );
    assert!(
        restored.score("javascript", "d3") > 0.0,
        "remaining document should still score after round-trip"
    );
}

#[test]
fn bm25_add_document_after_roundtrip_works() {
    let mut index = Bm25Index::new();
    index.add_document("d1", "original document about algorithms");
    index.add_document("d2", "second document about data structures");

    let bytes = index.serialize();
    let mut restored = Bm25Index::deserialize(&bytes).unwrap();

    // Add a new document to the restored index
    restored.add_document("d3", "new document about algorithms and optimization");
    assert_eq!(restored.doc_count, 3);

    // The new document should be scoreable
    let score = restored.score("algorithms optimization", "d3");
    assert!(
        score > 0.0,
        "newly added document after round-trip should be scoreable"
    );

    // Original documents should still work
    let score_d1 = restored.score("algorithms", "d1");
    assert!(
        score_d1 > 0.0,
        "original document should still score after adding new doc"
    );
}

#[test]
fn bm25_roundtrip_preserves_multi_term_scoring() {
    // Build an index with varied content to ensure multi-term scoring is preserved
    let mut index = Bm25Index::new();
    index.add_document("d1", "rust ownership borrowing lifetimes memory safety");
    index.add_document("d2", "python garbage collection reference counting cycles");
    index.add_document("d3", "javascript async await promises event loop");

    // Multi-term query so normalization doesn't flatten differences
    let query = "rust ownership memory";
    let score_d1_orig = index.score(query, "d1");
    let score_d2_orig = index.score(query, "d2");
    let score_d3_orig = index.score(query, "d3");

    let bytes = index.serialize();
    let restored = Bm25Index::deserialize(&bytes).unwrap();

    let score_d1_rest = restored.score(query, "d1");
    let score_d2_rest = restored.score(query, "d2");
    let score_d3_rest = restored.score(query, "d3");

    // Scores should be identical after round-trip
    assert!(
        (score_d1_orig - score_d1_rest).abs() < 1e-10,
        "d1 score should be preserved: {} vs {}",
        score_d1_orig,
        score_d1_rest
    );
    assert!(
        (score_d2_orig - score_d2_rest).abs() < 1e-10,
        "d2 score should be preserved"
    );
    assert!(
        (score_d3_orig - score_d3_rest).abs() < 1e-10,
        "d3 score should be preserved"
    );

    // Ranking should be preserved: d1 (matching) > d2 (no match) and d3 (no match)
    assert!(
        score_d1_rest > score_d2_rest,
        "ranking should be preserved: d1 ({}) > d2 ({})",
        score_d1_rest,
        score_d2_rest
    );
}

#[test]
fn bm25_deserialize_corrupt_data_returns_error() {
    let result = Bm25Index::deserialize(b"not valid json at all");
    assert!(result.is_err(), "corrupt data should fail deserialization");
    match result {
        Err(err) => {
            assert!(
                err.contains("deserialization failed"),
                "error should mention deserialization: {err}"
            );
        }
        Ok(_) => panic!("should have returned error"),
    }
}

#[test]
fn bm25_needs_save_after_roundtrip() {
    let mut index = Bm25Index::new();
    assert!(!index.needs_save(), "empty index should not need save");

    index.add_document("d1", "some content here");
    assert!(index.needs_save(), "index with docs should need save");

    let bytes = index.serialize();
    let restored = Bm25Index::deserialize(&bytes).unwrap();
    assert!(
        restored.needs_save(),
        "restored index with docs should still report needs_save"
    );
}

// ── BM25 eviction tests ──────────────────────────────────────────────

#[test]
fn bm25_eviction_at_capacity() {
    let mut index = Bm25Index::new();
    // Override max_documents to a small value for testing
    index.max_documents = 3;

    index.add_document("d1", "first document about rust");
    index.add_document("d2", "second document about python");
    index.add_document("d3", "third document about java");
    assert_eq!(index.doc_count, 3);

    // Adding a 4th doc should evict d1 (oldest)
    index.add_document("d4", "fourth document about golang");
    assert_eq!(index.doc_count, 3, "should stay at max capacity");

    // d1 was evicted
    assert_eq!(
        index.score("rust", "d1"),
        0.0,
        "evicted doc should return 0"
    );
    // d2, d3, d4 should still be scoreable
    assert!(index.score("python", "d2") > 0.0);
    assert!(index.score("java", "d3") > 0.0);
    assert!(index.score("golang", "d4") > 0.0);
}

#[test]
fn bm25_eviction_fifo_order() {
    let mut index = Bm25Index::new();
    index.max_documents = 2;

    index.add_document("d1", "alpha");
    index.add_document("d2", "beta");
    // Evicts d1
    index.add_document("d3", "gamma");
    assert_eq!(
        index.score("alpha", "d1"),
        0.0,
        "d1 should be evicted first"
    );
    assert!(index.score("beta", "d2") > 0.0);

    // Evicts d2
    index.add_document("d4", "delta");
    assert_eq!(
        index.score("beta", "d2"),
        0.0,
        "d2 should be evicted second"
    );
    assert!(index.score("gamma", "d3") > 0.0);
    assert!(index.score("delta", "d4") > 0.0);
}

#[test]
fn bm25_eviction_stats_remain_consistent() {
    let mut index = Bm25Index::new();
    index.max_documents = 2;

    index.add_document("d1", "word1 word2 word3");
    index.add_document("d2", "word4 word5");
    index.add_document("d3", "word6"); // evicts d1

    assert_eq!(index.doc_count, 2);
    // avg_doc_len should reflect only d2 (2 tokens) and d3 (1 token) = 1.5
    // (after tokenization: "word4"/"word5" = 2 tokens, "word6" = 1 token)
    assert!(
        (index.avg_doc_len - 1.5).abs() < 1e-10,
        "avg_doc_len should be recalculated after eviction: {}",
        index.avg_doc_len
    );
}

#[test]
fn bm25_eviction_with_replacement_does_not_double_evict() {
    let mut index = Bm25Index::new();
    index.max_documents = 3;

    index.add_document("d1", "alpha");
    index.add_document("d2", "beta");
    index.add_document("d3", "gamma");

    // Replacing d2 should NOT trigger eviction (same ID, removes then re-adds)
    index.add_document("d2", "beta updated content");
    assert_eq!(
        index.doc_count, 3,
        "replacement should not change doc_count"
    );

    // All docs should still be present
    assert!(
        index.score("alpha", "d1") > 0.0,
        "d1 should survive replacement of d2"
    );
    assert!(index.score("beta", "d2") > 0.0);
    assert!(index.score("gamma", "d3") > 0.0);
}

#[test]
fn bm25_score_text_works_after_roundtrip() {
    let mut index = Bm25Index::new();
    index.add_document("d1", "rust ownership and borrowing semantics");
    index.add_document("d2", "python garbage collection reference counting");

    let text = "rust ownership memory safety and lifetime rules";
    let score_orig = index.score_text("rust ownership", text);

    let bytes = index.serialize();
    let restored = Bm25Index::deserialize(&bytes).unwrap();

    let score_rest = restored.score_text("rust ownership", text);
    assert!(
        (score_orig - score_rest).abs() < 1e-10,
        "score_text should produce same results after round-trip: orig={}, rest={}",
        score_orig,
        score_rest
    );
}