1use serde::{Deserialize, Serialize};
13use wm_core::{CoreError, Galaxy, Result};
14
15use crate::memory::Memory;
16use crate::search::{SearchEngine, printable_ratio, sanitize_content_for_index};
17use crate::store::MemoryStore;
18
19pub const REINDEX_BATCH: usize = 2_000;
22
23#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
25pub struct GalaxyRebuildStats {
26 pub galaxy: String,
28 pub scanned: usize,
30 pub indexed: usize,
32 pub skipped: usize,
34 pub deleted: usize,
38}
39
40#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
42pub struct IndexRebuildReport {
43 pub scanned: usize,
45 pub indexed: usize,
47 pub skipped: usize,
49 pub deleted: usize,
51 pub galaxies: Vec<GalaxyRebuildStats>,
53}
54
55#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
57pub struct GalaxyConsistency {
58 pub galaxy: String,
60 pub lmdb_count: usize,
62 pub tantivy_count: usize,
64 pub drift: bool,
66}
67
68#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
70pub struct ConsistencyReport {
71 pub galaxies: Vec<GalaxyConsistency>,
73 pub total_lmdb: usize,
75 pub total_tantivy: usize,
77 pub has_drift: bool,
79}
80
81#[must_use]
93pub fn check_consistency(store: &MemoryStore, search: &SearchEngine) -> ConsistencyReport {
94 let mut report = ConsistencyReport::default();
95 for galaxy in Galaxy::memory_galaxies() {
96 let lmdb_count = store.count(galaxy).unwrap_or(0);
97 let tantivy_count = search.count_docs_in_galaxy(galaxy.db_name()).unwrap_or(0);
98 let drift = lmdb_count != tantivy_count;
99 report.total_lmdb += lmdb_count;
100 report.total_tantivy += tantivy_count;
101 if drift {
102 report.has_drift = true;
103 }
104 report.galaxies.push(GalaxyConsistency {
105 galaxy: galaxy.db_name().to_string(),
106 lmdb_count,
107 tantivy_count,
108 drift,
109 });
110 }
111 report
112}
113
114#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
124pub struct GalaxyDriftClass {
125 pub galaxy: String,
127 pub lmdb_count: usize,
129 pub tantivy_count: usize,
131 pub skip_reserve: usize,
135 pub healable_gap: i64,
139}
140
141#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
143pub struct DriftClassification {
144 pub galaxies: Vec<GalaxyDriftClass>,
146 pub skip_reserve_total: usize,
148 pub healable_total: usize,
150}
151
152#[must_use]
160pub fn classify_drift(store: &MemoryStore, search: &SearchEngine) -> DriftClassification {
161 let mut out = DriftClassification::default();
162 for galaxy in Galaxy::memory_galaxies() {
163 let lmdb_count = store.count(galaxy).unwrap_or(0);
164 let tantivy_count = search.count_docs_in_galaxy(galaxy.db_name()).unwrap_or(0);
165 let mut skip_reserve = 0usize;
166 if lmdb_count > tantivy_count {
167 for mem in store.scan(galaxy, lmdb_count).unwrap_or_default() {
168 if sanitize_content_for_index(&mem.content).is_none() {
169 skip_reserve += 1;
170 }
171 }
172 }
173 let indexable = usize::try_into(lmdb_count - skip_reserve).unwrap_or(i64::MAX);
174 let indexed = usize::try_into(tantivy_count).unwrap_or(i64::MAX);
175 let healable_gap = indexable - indexed;
176 out.skip_reserve_total += skip_reserve;
177 out.healable_total += healable_gap.unsigned_abs() as usize;
178 out.galaxies.push(GalaxyDriftClass {
179 galaxy: galaxy.db_name().to_string(),
180 lmdb_count,
181 tantivy_count,
182 skip_reserve,
183 healable_gap,
184 });
185 }
186 out
187}
188
189pub fn rebuild_index(
200 store: &MemoryStore,
201 search: &SearchEngine,
202 galaxy_filter: &[String],
203) -> Result<IndexRebuildReport> {
204 let mut snapshots = Vec::new();
208 for galaxy in Galaxy::memory_galaxies() {
209 if galaxy_filter.is_empty() || galaxy_filter.iter().any(|g| g == galaxy.db_name()) {
210 snapshots.push((galaxy, store.scan_all_strict(galaxy)?));
211 }
212 }
213 if galaxy_filter.iter().any(|name| {
214 !Galaxy::memory_galaxies()
215 .iter()
216 .any(|g| g.db_name() == name)
217 }) {
218 return Err(CoreError::Memory(
219 "reindex filter must name a memory galaxy".into(),
220 ));
221 }
222 let mut report = IndexRebuildReport::default();
223 {
224 let mut writer = search.writer()?;
225 if galaxy_filter.is_empty() {
226 writer
227 .as_mut()
228 .ok_or_else(|| {
229 CoreError::Memory("Tantivy writer unavailable: index opened read-only".into())
230 })?
231 .delete_all_documents()
232 .map_err(|e| CoreError::Memory(format!("Tantivy delete_all_documents: {e}")))?;
233 } else {
234 for galaxy in Galaxy::all() {
238 if galaxy_filter.iter().any(|g| g == galaxy.db_name()) {
239 search.delete_by_galaxy(&mut writer, galaxy.db_name())?;
240 }
241 }
242 }
243
244 for (galaxy, memories) in snapshots {
245 let mut stats = GalaxyRebuildStats {
246 galaxy: galaxy.db_name().to_string(),
247 ..GalaxyRebuildStats::default()
248 };
249 for mem in &memories {
250 stats.scanned += 1;
251 if index_memory(search, &mut writer, galaxy, mem)?.is_some() {
252 stats.indexed += 1;
253 } else {
254 stats.skipped += 1;
255 }
256 }
257 report.scanned += stats.scanned;
258 report.indexed += stats.indexed;
259 report.skipped += stats.skipped;
260 report.galaxies.push(stats);
261 }
262
263 search.commit(&mut writer)?;
264 drop(writer);
265 }
266 Ok(report)
267}
268
269fn index_memory(
272 search: &SearchEngine,
273 writer: &mut Option<tantivy::IndexWriter>,
274 galaxy: Galaxy,
275 mem: &Memory,
276) -> Result<Option<()>> {
277 let Some(content) = sanitize_content_for_index(&mem.content) else {
278 return Ok(None);
279 };
280 let timestamp = mem.metadata.created_at.timestamp();
281 let id = mem.metadata.id.to_string();
282 search.add_document(
283 writer,
284 &id,
285 galaxy.db_name(),
286 &content,
287 &mem.metadata.tags,
288 timestamp,
289 )?;
290 Ok(Some(()))
291}
292
293pub fn heal_index_drift(
319 store: &MemoryStore,
320 search: &SearchEngine,
321) -> Result<Option<IndexRebuildReport>> {
322 let class = classify_drift(store, search);
327 let drifted: Vec<String> = class
328 .galaxies
329 .iter()
330 .filter(|g| g.healable_gap != 0)
331 .map(|g| g.galaxy.clone())
332 .collect();
333 if drifted.is_empty() {
334 return Ok(None);
335 }
336
337 let mut report = IndexRebuildReport::default();
338 let mut writer = search.writer()?;
339 for name in &drifted {
340 let Some(galaxy) = Galaxy::from_db_name(name) else {
341 return Err(CoreError::Memory(format!(
342 "drift classification named a non-memory galaxy: {name}"
343 )));
344 };
345 let mut stats = GalaxyRebuildStats {
346 galaxy: name.clone(),
347 ..GalaxyRebuildStats::default()
348 };
349
350 let indexed_ids = search.indexed_ids_in_galaxy(name)?;
351 let mut lmdb_ids: std::collections::HashSet<String> =
352 std::collections::HashSet::with_capacity(indexed_ids.len());
353 for mem in store.scan_all(galaxy)? {
354 let id = mem.metadata.id.to_string();
355 lmdb_ids.insert(id.clone());
356 if !indexed_ids.contains(&id) {
357 stats.scanned += 1;
358 if index_memory(search, &mut writer, galaxy, &mem)?.is_some() {
359 stats.indexed += 1;
360 } else {
361 stats.skipped += 1;
366 }
367 }
368 }
369 for id in &indexed_ids {
372 if !lmdb_ids.contains(id) {
373 search.delete_document(&mut writer, id)?;
374 stats.deleted += 1;
375 }
376 }
377
378 report.scanned += stats.scanned;
379 report.indexed += stats.indexed;
380 report.skipped += stats.skipped;
381 report.deleted += stats.deleted;
382 report.galaxies.push(stats);
383 }
384
385 search.commit(&mut writer)?;
386 drop(writer);
387 Ok(Some(report))
388}
389
390#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
394pub struct GalaxyContentRepairStats {
395 pub galaxy: String,
397 pub scanned: usize,
399 pub repaired: usize,
401 pub unrepairable: usize,
404 pub already_clean: usize,
406}
407
408#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
410pub struct ContentRepairReport {
411 pub scanned: usize,
413 pub repaired: usize,
415 pub unrepairable: usize,
417 pub already_clean: usize,
419 pub galaxies: Vec<GalaxyContentRepairStats>,
421}
422
423fn clean_for_repair(content: &str) -> String {
427 content
428 .chars()
429 .map(|c| {
430 if c.is_control() && c != '\n' && c != '\t' && c != '\r' {
431 ' '
432 } else {
433 c
434 }
435 })
436 .collect()
437}
438
439pub fn repair_content(
463 store: &MemoryStore,
464 search: &SearchEngine,
465 galaxies: &[Galaxy],
466) -> Result<ContentRepairReport> {
467 let mut report = ContentRepairReport::default();
468 let mut writer = search.writer()?;
469 for galaxy in galaxies {
470 let mut stats = GalaxyContentRepairStats {
471 galaxy: galaxy.db_name().to_string(),
472 ..Default::default()
473 };
474 for mem in store.scan_all(*galaxy)? {
475 stats.scanned += 1;
476 if sanitize_content_for_index(&mem.content).is_some() {
477 stats.already_clean += 1;
478 continue;
479 }
480 let total = mem.content.chars().count();
484 let cleaned = clean_for_repair(&mem.content);
485 if total == 0
486 || printable_ratio(&mem.content) < 0.5
487 || sanitize_content_for_index(&cleaned).is_none()
488 {
489 stats.unrepairable += 1;
490 continue;
491 }
492 let mut repaired_mem = mem;
493 let old_hash = repaired_mem.metadata.content_hash.clone();
494 repaired_mem.content = cleaned;
495 repaired_mem.metadata.content_hash = crate::content_hash(&repaired_mem.content);
496 repaired_mem.metadata.revision_count =
497 repaired_mem.metadata.revision_count.saturating_add(1);
498 store.put(*galaxy, &repaired_mem)?;
499 store.record_revision(
503 *galaxy,
504 repaired_mem.metadata.id,
505 &old_hash,
506 &repaired_mem.metadata.content_hash,
507 crate::revision::RevisionActor {
508 session: None,
509 user: Some("wm-repair-content".to_string()),
510 compartment: None,
511 },
512 )?;
513 let id_str = repaired_mem.metadata.id.to_string();
514 search.delete_document(&mut writer, &id_str)?;
517 search.add_document(
518 &mut writer,
519 &id_str,
520 galaxy.db_name(),
521 &repaired_mem.content,
522 &repaired_mem.metadata.tags,
523 repaired_mem.metadata.created_at.timestamp(),
524 )?;
525 stats.repaired += 1;
526 }
527 report.scanned += stats.scanned;
528 report.repaired += stats.repaired;
529 report.unrepairable += stats.unrepairable;
530 report.already_clean += stats.already_clean;
531 report.galaxies.push(stats);
532 }
533 search.commit(&mut writer)?;
534 Ok(report)
535}
536
537#[must_use]
540pub fn tantivy_path_for(store_path: &std::path::Path) -> std::path::PathBuf {
541 store_path.join("tantivy")
542}
543
544#[must_use]
546pub fn missing_index_error(store_path: &std::path::Path) -> CoreError {
547 CoreError::Memory(format!(
548 "Tantivy index not found at {} — run 'wm serve' once to create it",
549 tantivy_path_for(store_path).display()
550 ))
551}
552
553pub fn quarantine_and_recreate(tantivy_path: &std::path::Path) -> Result<std::path::PathBuf> {
564 let quarantine = quarantine_index(tantivy_path)?;
565 std::fs::create_dir_all(tantivy_path).map_err(|e| {
566 CoreError::Memory(format!(
567 "Index quarantine — recreate {}: {e} (the old index is at {})",
568 tantivy_path.display(),
569 quarantine.display()
570 ))
571 })?;
572 Ok(quarantine)
573}
574
575pub fn quarantine_index(tantivy_path: &std::path::Path) -> Result<std::path::PathBuf> {
581 let ts = std::time::SystemTime::now()
582 .duration_since(std::time::UNIX_EPOCH)
583 .map_or(0, |d| d.as_millis());
584 let file_name = tantivy_path
585 .file_name()
586 .and_then(|n| n.to_str())
587 .unwrap_or("tantivy");
588 let quarantine = tantivy_path.with_file_name(format!("{file_name}.corrupt.{ts}"));
589 std::fs::rename(tantivy_path, &quarantine).map_err(|e| {
590 CoreError::Memory(format!(
591 "Index quarantine — rename {} to {}: {e}",
592 tantivy_path.display(),
593 quarantine.display()
594 ))
595 })?;
596 Ok(quarantine)
597}
598
599pub fn open_or_quarantine(
613 tantivy_path: &std::path::Path,
614) -> Result<(SearchEngine, Option<std::path::PathBuf>)> {
615 match SearchEngine::open(tantivy_path) {
616 Ok(engine) => Ok((engine, None)),
617 Err(error) => {
618 if error.to_string().contains("LockBusy") {
619 return Err(error);
620 }
621 let quarantine = quarantine_and_recreate(tantivy_path)?;
622 let engine = SearchEngine::open(tantivy_path).map_err(|e| {
623 CoreError::Memory(format!(
624 "Index at {} could not be opened ({error}); the old index was moved to {} \
625 but creating a fresh index failed: {e}",
626 tantivy_path.display(),
627 quarantine.display()
628 ))
629 })?;
630 Ok((engine, Some(quarantine)))
631 }
632 }
633}
634
635#[cfg(test)]
636mod tests {
637 use super::*;
638 use crate::Memory;
639 use tempfile::tempdir;
640
641 fn setup() -> (tempfile::TempDir, MemoryStore, SearchEngine) {
642 let tmp = tempdir().unwrap();
643 let store = MemoryStore::open_default(tmp.path()).unwrap();
644 let tantivy_dir = tmp.path().join("tantivy");
645 std::fs::create_dir_all(&tantivy_dir).unwrap();
646 let search = SearchEngine::open(&tantivy_dir).unwrap();
647 (tmp, store, search)
648 }
649
650 fn put_and_index(store: &MemoryStore, search: &SearchEngine, galaxy: Galaxy, content: &str) {
651 let mem = Memory::new(galaxy, content.to_string());
652 let id = mem.metadata.id;
653 store.put(galaxy, &mem).unwrap();
654 let mut writer = search.writer().unwrap();
655 search
656 .add_document(
657 &mut writer,
658 &id.to_string(),
659 galaxy.db_name(),
660 content,
661 &mem.metadata.tags,
662 mem.metadata.created_at.timestamp(),
663 )
664 .unwrap();
665 search.commit(&mut writer).unwrap();
666 }
667
668 #[test]
669 fn rebuild_repopulates_index_from_lmdb() {
670 let (_tmp, store, search) = setup();
671 put_and_index(&store, &search, Galaxy::Codex, "rust memory one");
672 put_and_index(&store, &search, Galaxy::Codex, "python memory two");
673 put_and_index(&store, &search, Galaxy::Research, "research notes");
674
675 {
678 let mut writer = search.writer().unwrap();
679 search
680 .add_document(
681 &mut writer,
682 "99999999-9999-9999-9999-999999999999",
683 "codex",
684 "stale ghost document",
685 &[],
686 1000,
687 )
688 .unwrap();
689 search.commit(&mut writer).unwrap();
690 }
691 let ghost = search.search("ghost", 10).unwrap();
692 assert_eq!(ghost.len(), 1);
693
694 let report = rebuild_index(&store, &search, &[]).unwrap();
695 assert_eq!(report.indexed, 3);
696 assert_eq!(report.scanned, 3);
697 assert_eq!(report.galaxies.len(), Galaxy::memory_galaxies().len());
698
699 let ghost = search.search("ghost", 10).unwrap();
700 assert!(ghost.is_empty(), "stale index entry must be purged");
701
702 let rust = search.search("rust memory one", 10).unwrap();
703 assert_eq!(rust.len(), 1);
704 assert_eq!(rust[0].content, "rust memory one");
705 }
706
707 #[test]
708 fn rebuild_refuses_undecodable_sources_before_touching_index() {
709 let (_tmp, store, search) = setup();
710 put_and_index(
711 &store,
712 &search,
713 Galaxy::Codex,
714 "preserved searchable evidence",
715 );
716 let id = uuid::Uuid::new_v4();
717 store
718 .put_raw(Galaxy::Sessions, id.as_bytes(), b"invalid messagepack")
719 .unwrap();
720 let before = search.count_docs_in_galaxy("codex").unwrap();
721 assert!(rebuild_index(&store, &search, &[]).is_err());
722 let mut writer = search.writer().unwrap();
724 search.commit(&mut writer).unwrap();
725 assert_eq!(search.count_docs_in_galaxy("codex").unwrap(), before);
726 assert_eq!(search.search("preserved", 10).unwrap().len(), 1);
727 }
728
729 #[test]
730 fn rebuild_skips_binary_garbage() {
731 let (_tmp, store, search) = setup();
732 put_and_index(&store, &search, Galaxy::Codex, "clean text entry");
733 let mem = Memory::new(Galaxy::Codex, "\u{00}\u{01}\u{02}raw bytes".to_string());
734 store.put(Galaxy::Codex, &mem).unwrap();
735
736 let report = rebuild_index(&store, &search, &[]).unwrap();
737 assert_eq!(report.indexed, 1, "garbage content must be skipped");
738 assert_eq!(report.skipped, 1);
739
740 let results = search.search("raw", 10).unwrap();
741 assert!(results.is_empty());
742 }
743
744 #[test]
745 fn rebuild_respects_galaxy_filter() {
746 let (_tmp, store, search) = setup();
747 put_and_index(&store, &search, Galaxy::Codex, "codex memory");
748 put_and_index(&store, &search, Galaxy::Research, "research memory");
749
750 let report = rebuild_index(&store, &search, &["codex".to_string()]).unwrap();
751 assert_eq!(report.indexed, 1);
752 assert_eq!(report.galaxies.len(), 1);
753 assert_eq!(report.galaxies[0].galaxy, "codex");
754
755 let codex = search
760 .search_in_galaxy("codex memory", Some(Galaxy::Codex), 10)
761 .unwrap();
762 assert_eq!(codex.len(), 1);
763 let research = search
764 .search_in_galaxy("research memory", Some(Galaxy::Research), 10)
765 .unwrap();
766 assert_eq!(
767 research.len(),
768 1,
769 "filtered rebuild must preserve documents in unselected galaxies"
770 );
771 }
772
773 #[test]
774 fn consistency_check_no_drift_when_indexed() {
775 let (_tmp, store, search) = setup();
776 put_and_index(&store, &search, Galaxy::Codex, "hello world");
777 put_and_index(&store, &search, Galaxy::Codex, "another memory");
778
779 let report = check_consistency(&store, &search);
780 assert!(!report.has_drift, "no drift expected when all indexed");
781 let codex = report
782 .galaxies
783 .iter()
784 .find(|g| g.galaxy == "codex")
785 .unwrap();
786 assert_eq!(codex.lmdb_count, 2);
787 assert_eq!(codex.tantivy_count, 2);
788 }
789
790 #[test]
791 fn consistency_check_detects_drift() {
792 let (_tmp, store, search) = setup();
793 let mem = Memory::new(Galaxy::Codex, "unindexed".to_string());
795 store.put(Galaxy::Codex, &mem).unwrap();
796
797 let report = check_consistency(&store, &search);
798 assert!(
799 report.has_drift,
800 "drift expected when LMDB has unindexed memory"
801 );
802 let codex = report
803 .galaxies
804 .iter()
805 .find(|g| g.galaxy == "codex")
806 .unwrap();
807 assert_eq!(codex.lmdb_count, 1);
808 assert_eq!(codex.tantivy_count, 0);
809 }
810
811 #[test]
812 fn heal_repairs_only_drifted_galaxies() {
813 let (_tmp, store, search) = setup();
814
815 store
817 .put(
818 Galaxy::Sessions,
819 &Memory::new(Galaxy::Sessions, "session needle".into()),
820 )
821 .unwrap();
822 store
823 .put(
824 Galaxy::Research,
825 &Memory::new(Galaxy::Research, "research needle".into()),
826 )
827 .unwrap();
828 put_and_index(&store, &search, Galaxy::Codex, "healthy codex entry");
830
831 let report = heal_index_drift(&store, &search)
832 .unwrap()
833 .expect("drift expected before heal");
834 let healed: Vec<_> = report.galaxies.iter().map(|g| g.galaxy.as_str()).collect();
835 assert!(healed.contains(&"sessions"));
836 assert!(healed.contains(&"research"));
837 assert!(
838 !healed.contains(&"codex"),
839 "healthy galaxy must be untouched"
840 );
841 assert_eq!(report.indexed, 2);
842
843 assert!(
844 heal_index_drift(&store, &search).unwrap().is_none(),
845 "second heal must be a no-op once consistent"
846 );
847 assert_eq!(
848 search
849 .search_in_galaxy("session needle", Some(Galaxy::Sessions), 10)
850 .unwrap()
851 .len(),
852 1
853 );
854 assert_eq!(
855 search
856 .search_in_galaxy("healthy codex", Some(Galaxy::Codex), 10)
857 .unwrap()
858 .len(),
859 1
860 );
861 }
862
863 #[test]
864 fn heal_noop_when_consistent() {
865 let (_tmp, store, search) = setup();
866 put_and_index(&store, &search, Galaxy::Codex, "indexed entry");
867 put_and_index(&store, &search, Galaxy::Dreams, "dream entry");
868
869 assert!(heal_index_drift(&store, &search).unwrap().is_none());
870 }
871
872 #[test]
873 fn index_health_tracks_successes() {
874 let (_tmp, store, search) = setup();
875 put_and_index(&store, &search, Galaxy::Codex, "test content");
876
877 let health = search.health().snapshot();
878 let successes = health
879 .get("successes")
880 .and_then(serde_json::Value::as_u64)
881 .unwrap_or(0);
882 assert!(successes > 0, "expected at least one success");
883 let failures = health
884 .get("failures")
885 .and_then(serde_json::Value::as_u64)
886 .unwrap_or(0);
887 assert_eq!(failures, 0);
888 assert_eq!(
889 health.get("degraded").and_then(serde_json::Value::as_bool),
890 Some(false)
891 );
892 }
893
894 #[test]
895 fn consistency_check_ignores_non_memory_galaxies() {
896 let (_tmp, store, search) = setup();
897 put_and_index(&store, &search, Galaxy::Codex, "indexed memory");
898
899 store.put_raw(Galaxy::Karma, b"key1", b"value1").unwrap();
902
903 let report = check_consistency(&store, &search);
904 assert!(
905 !report.has_drift,
906 "karma entries should not cause drift — non-memory galaxies are excluded"
907 );
908 let galaxy_names: Vec<_> = report.galaxies.iter().map(|g| g.galaxy.as_str()).collect();
910 assert!(
911 !galaxy_names.contains(&"karma"),
912 "karma should not appear in consistency report"
913 );
914 assert!(
915 !galaxy_names.contains(&"dharma"),
916 "dharma should not appear in consistency report"
917 );
918 }
919 #[test]
922 fn classify_separates_skip_reserve_from_healable_drift() {
923 let (tmp, store, search) = setup();
924 put_and_index(&store, &search, Galaxy::Codex, "clean doc one");
926 put_and_index(&store, &search, Galaxy::Codex, "clean doc two");
927 store
928 .put(
929 Galaxy::Codex,
930 &Memory::new(Galaxy::Codex, "bad \u{1}\u{2} doc".into()),
931 )
932 .unwrap();
933 search.commit(&mut search.writer().unwrap()).unwrap();
934
935 let class = classify_drift(&store, &search);
936 let codex = class.galaxies.iter().find(|g| g.galaxy == "codex").unwrap();
937 assert_eq!(codex.lmdb_count, 3);
938 assert_eq!(codex.tantivy_count, 2);
939 assert_eq!(codex.skip_reserve, 1);
940 assert_eq!(codex.healable_gap, 0, "skip reserve fully explains the gap");
941 assert_eq!(class.healable_total, 0);
942 drop(tmp);
943 }
944
945 #[test]
946 fn classify_flags_missing_indexable_docs_as_healable() {
947 let (tmp, store, search) = setup();
948 put_and_index(&store, &search, Galaxy::Codex, "indexed doc");
949 store
951 .put(
952 Galaxy::Codex,
953 &Memory::new(Galaxy::Codex, "unindexed clean doc".into()),
954 )
955 .unwrap();
956 search.commit(&mut search.writer().unwrap()).unwrap();
957
958 let class = classify_drift(&store, &search);
959 let codex = class.galaxies.iter().find(|g| g.galaxy == "codex").unwrap();
960 assert_eq!(codex.skip_reserve, 0);
961 assert_eq!(codex.healable_gap, 1);
962 assert_eq!(class.healable_total, 1);
963 drop(tmp);
964 }
965
966 #[test]
967 fn heal_ignores_pure_skip_reserve_and_heals_real_gaps() {
968 let (tmp, store, search) = setup();
969 put_and_index(&store, &search, Galaxy::Codex, "clean doc");
970 store
973 .put(
974 Galaxy::Codex,
975 &Memory::new(Galaxy::Codex, "gate\u{0} fails".into()),
976 )
977 .unwrap();
978 search.commit(&mut search.writer().unwrap()).unwrap();
979 let healed = heal_index_drift(&store, &search).unwrap();
980 assert!(
981 healed.is_none(),
982 "skip-reserve-only drift must not trigger a rebuild"
983 );
984
985 store
987 .put(
988 Galaxy::Codex,
989 &Memory::new(Galaxy::Codex, "genuinely missing doc".into()),
990 )
991 .unwrap();
992 let healed = heal_index_drift(&store, &search).unwrap();
993 assert!(healed.is_some(), "healable drift must trigger a heal");
994 let healed = healed.unwrap();
999 assert_eq!(healed.indexed, 1);
1000 assert_eq!(healed.skipped, 1);
1001 assert_eq!(healed.deleted, 0);
1002 drop(tmp);
1003 }
1004
1005 #[test]
1006 fn heal_indexes_only_the_missing_delta() {
1007 let (_tmp, store, search) = setup();
1008 let a = Memory::new(Galaxy::Sessions, "alpha missing doc".into());
1010 let b = Memory::new(Galaxy::Sessions, "beta missing doc".into());
1011 store.put(Galaxy::Sessions, &a).unwrap();
1012 store.put(Galaxy::Sessions, &b).unwrap();
1013
1014 let report = heal_index_drift(&store, &search).unwrap().unwrap();
1016 assert_eq!(report.indexed, 2);
1017 assert_eq!(report.deleted, 0);
1018 assert_eq!(
1019 search
1020 .search_in_galaxy("alpha", Some(Galaxy::Sessions), 10)
1021 .unwrap()
1022 .len(),
1023 1
1024 );
1025
1026 store
1028 .put(
1029 Galaxy::Sessions,
1030 &Memory::new(Galaxy::Sessions, "gamma missing doc".into()),
1031 )
1032 .unwrap();
1033 let report = heal_index_drift(&store, &search).unwrap().unwrap();
1034 assert_eq!(report.indexed, 1, "only the delta is indexed");
1035 assert_eq!(
1036 search
1037 .search_in_galaxy("gamma", Some(Galaxy::Sessions), 10)
1038 .unwrap()
1039 .len(),
1040 1
1041 );
1042 assert_eq!(
1044 search
1045 .search_in_galaxy("alpha", Some(Galaxy::Sessions), 10)
1046 .unwrap()
1047 .len(),
1048 1
1049 );
1050 }
1051
1052 #[test]
1053 fn heal_deletes_orphan_index_docs() {
1054 let (_tmp, store, search) = setup();
1055 put_and_index(&store, &search, Galaxy::Codex, "legit doc");
1056 let orphan = Memory::new(Galaxy::Codex, "orphan doc".into());
1062 let orphan_id = orphan.metadata.id;
1063 store.put(Galaxy::Codex, &orphan).unwrap();
1064 {
1065 let mut writer = search.writer().unwrap();
1066 search
1067 .add_document(
1068 &mut writer,
1069 &orphan_id.to_string(),
1070 "codex",
1071 "orphan doc",
1072 &orphan.metadata.tags,
1073 orphan.metadata.created_at.timestamp(),
1074 )
1075 .unwrap();
1076 search.commit(&mut writer).unwrap();
1077 }
1078 store
1079 .delete_raw(Galaxy::Codex, orphan_id.as_bytes())
1080 .unwrap();
1081 assert_eq!(search.count_docs_in_galaxy("codex").unwrap(), 2);
1082
1083 let report = heal_index_drift(&store, &search).unwrap().unwrap();
1084 assert_eq!(report.deleted, 1, "the orphan must be deleted");
1085 assert_eq!(report.indexed, 0);
1086 assert_eq!(search.count_docs_in_galaxy("codex").unwrap(), 1);
1087 let mut gone = false;
1091 for _ in 0..40 {
1092 if search.search("orphan", 10).unwrap().is_empty() {
1095 gone = true;
1096 break;
1097 }
1098 std::thread::sleep(std::time::Duration::from_millis(50));
1099 }
1100 assert!(gone, "orphan doc must be gone from search");
1101 assert!(heal_index_drift(&store, &search).unwrap().is_none());
1102 }
1103
1104 #[test]
1105 fn repair_rewrites_in_place_and_indexes_clean_content() {
1106 let (tmp, store, search) = setup();
1107 let mut repairable = Memory::new(
1110 Galaxy::Codex,
1111 "kumquat\u{0} ratchet \u{1} repair end".into(),
1112 );
1113 let mut binary = Memory::new(Galaxy::Codex, "\u{1}\u{2}\u{3}\u{4}\u{5}\u{6}".into());
1115 let mut clean = Memory::new(Galaxy::Codex, "perfectly fine prose".into());
1117 let (id_r, id_b, id_c) = (
1118 repairable.metadata.id,
1119 binary.metadata.id,
1120 clean.metadata.id,
1121 );
1122 for m in [&mut repairable, &mut binary, &mut clean] {
1123 store.put(Galaxy::Codex, m).unwrap();
1124 }
1125
1126 let report = repair_content(&store, &search, &[Galaxy::Codex]).unwrap();
1127 assert_eq!(report.scanned, 3);
1128 assert_eq!(report.repaired, 1, "{report:?}");
1129 assert_eq!(report.unrepairable, 1, "{report:?}");
1130 assert_eq!(report.already_clean, 1);
1131
1132 let row = store.get(Galaxy::Codex, id_r).unwrap().unwrap();
1135 assert_eq!(row.content, "kumquat ratchet repair end");
1136 assert_eq!(row.metadata.content_hash, crate::content_hash(&row.content));
1137 assert!(sanitize_content_for_index(&row.content).is_some());
1138 assert_eq!(row.metadata.revision_count, 1);
1139
1140 let chain = store.revisions(Galaxy::Codex, id_r).unwrap();
1143 assert_eq!(chain.len(), 1);
1144 assert_eq!(
1145 chain[0].old_hash,
1146 crate::content_hash("kumquat\u{0} ratchet \u{1} repair end")
1147 );
1148 assert_eq!(chain[0].new_hash, row.metadata.content_hash);
1149 assert_eq!(chain[0].actor_user.as_deref(), Some("wm-repair-content"));
1150 assert_eq!(chain[0].actor_session, None);
1151 let verdict = store
1152 .verify_revision_chain(Galaxy::Codex, id_r, &row.metadata.content_hash)
1153 .unwrap();
1154 assert!(verdict.valid, "{:?}", verdict.breaks);
1155
1156 assert!(store.revisions(Galaxy::Codex, id_b).unwrap().is_empty());
1158 assert!(store.revisions(Galaxy::Codex, id_c).unwrap().is_empty());
1159
1160 let untouched = store.get(Galaxy::Codex, id_b).unwrap().unwrap();
1162 assert_eq!(untouched.content, "\u{1}\u{2}\u{3}\u{4}\u{5}\u{6}");
1163
1164 let kept = store.get(Galaxy::Codex, id_c).unwrap().unwrap();
1166 assert_eq!(kept.content, "perfectly fine prose");
1167
1168 let hits = search.search("kumquat ratchet repair", 10).unwrap();
1170 assert!(
1171 hits.iter().any(|h| h.memory_id == id_r.to_string()),
1172 "repaired doc must be indexed: {hits:?}"
1173 );
1174
1175 let again = repair_content(&store, &search, &[Galaxy::Codex]).unwrap();
1177 assert_eq!(again.repaired, 0);
1178 assert_eq!(again.already_clean, 2);
1179 assert_eq!(
1180 store.revisions(Galaxy::Codex, id_r).unwrap().len(),
1181 1,
1182 "idempotent re-run must not append"
1183 );
1184 drop(tmp);
1185 }
1186
1187 #[test]
1188 fn open_or_quarantine_recovers_an_unopenable_index() {
1189 let tmp = tempdir().unwrap();
1190 let index_dir = tmp.path().join("tantivy");
1191 std::fs::create_dir_all(&index_dir).unwrap();
1192 drop(SearchEngine::open(&index_dir).unwrap());
1193
1194 std::fs::write(index_dir.join("meta.json"), b"{ not json").unwrap();
1196
1197 let (engine, quarantine) = open_or_quarantine(&index_dir).unwrap();
1198 let quarantine = quarantine.expect("an unopenable index must be quarantined");
1199 assert!(quarantine.join("meta.json").exists(), "{quarantine:?}");
1200 assert!(
1201 quarantine
1202 .file_name()
1203 .unwrap()
1204 .to_string_lossy()
1205 .contains(".corrupt."),
1206 "quarantine keeps the old index beside the fresh one: {quarantine:?}"
1207 );
1208 assert_eq!(engine.count_docs_in_galaxy("codex").unwrap(), 0);
1210 drop(engine);
1211 assert!(index_dir.exists(), "a fresh index directory is created");
1212 }
1213}