hakodb 0.21.1

Embedded & Cloud-native Document Engine
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
use crate::document::hako_doc::HakoDoc;
use crate::document::value::Value;
use hashbrown::HashMap;
use std::sync::Arc;

use super::composite::definition::CompositeIndexDefinition;
use super::composite::manager::CompositeIndexManager;
use super::inverted_index::InvertedIndex;
use super::traverse::BacklinkIndex;
use super::vector::{decode_f32s, validate_dim, HnswIndex, HnswParams, Metric, VectorDef};
use crate::index::composite::composite_index::CompositeIndex;
use crate::index::secondary_index::SecondaryIndex;

use crate::error::HakoError;

#[derive(Default)]
pub struct IndexManager {
    pub composite: CompositeIndexManager,
    pub secondary: HashMap<String, HashMap<String, SecondaryIndex>>,
    pub fts: HashMap<String, HashMap<String, InvertedIndex>>,
    /// Vector definitions per (collection, field). P0: definitions only
    /// (the exact scan needs dim/metric, no RAM structure); P1's HNSW
    /// hangs off this same registry.
    pub vector: HashMap<String, HashMap<String, VectorDef>>,
    /// P1 HNSW graphs, keyed identically to `vector`. Derived state:
    /// never snapshotted (rebuilt from docs on open/create); `complete`
    /// tells the executor whether ANN may run or exact must.
    pub hnsw: HashMap<String, HashMap<String, HnswIndex>>,
    /// Graph backlinks (issue #53, Phase A): reverse edges into tracked
    /// target collections. Derived like HNSW (hooks rebuild, never
    /// snapshotted); deletes clean both directions, overwrites dedupe +
    /// verify-at-query.
    pub traverse: BacklinkIndex,
}

/// WAL tails at snapshot time, per collection: (wal data_len, wal
/// file_len). Lets recovery tell a fresh snapshot from a stale one
/// (crash after the last snapshot) without trusting timestamps.
pub type WalTails = HashMap<String, (u64, u64)>;

impl IndexManager {
    /// Register an FTS field. Returns true when the index was newly
    /// created — false = already present, no-op. The #217 P2 idempotent
    /// boot contract: re-declaring on every boot must NOT wipe a
    /// populated inverted index.
    pub fn create_fts_index(&mut self, collection: &str, field: &str) -> bool {
        let m = self.fts.entry(collection.to_string()).or_default();
        if m.contains_key(field) {
            return false;
        }
        m.insert(field.to_string(), InvertedIndex::default());
        true
    }

    /// Register a vector definition (P0: no RAM structure — the exact scan
    /// only needs dim + metric; dim mismatch at query time is fail-closed).
    /// Re-registering overwrites (same overwrite rule as fts/secondary).
    /// Register a vector definition (P0: no RAM structure — the exact scan
    /// only needs dim + metric; dim mismatch at query time is fail-closed).
    ///
    /// #217 P2 idempotent contract: an identical def is a no-op (returns
    /// `Ok(false)`); a DIFFERENT def on the same field is an error
    /// (drop the index first) — a silent replacement would strand the
    /// populated HNSW graph behind a mismatched definition.
    pub fn create_vector_index(
        &mut self,
        collection: &str,
        field: &str,
        dim: u32,
        metric: Metric,
        params: HnswParams,
    ) -> crate::error::Result<bool> {
        validate_dim(dim)?;
        if let Some(existing) = self.vector.get(collection).and_then(|m| m.get(field)) {
            if existing.dim == dim
                && existing.metric == metric
                && existing.m == params.m
                && existing.ef_construction == params.ef_construction
                && existing.ef_search == params.ef_search
                && existing.binary_stage1 == params.binary_stage1
            {
                return Ok(false);
            }
            return Err(crate::error::HakoError::InvalidInput(format!(
                "vector index {collection}.{field} already exists with dim {} metric {:?} — \
                 drop it before declaring a different definition",
                existing.dim, existing.metric
            )));
        }
        self.vector
            .entry(collection.to_string())
            .or_default()
            .insert(
                field.to_string(),
                VectorDef {
                    dim,
                    metric,
                    m: params.m,
                    ef_construction: params.ef_construction,
                    ef_search: params.ef_search,
                    binary_stage1: params.binary_stage1,
                },
            );
        Ok(true)
    }

    /// Ensure an (empty, incomplete) HNSW graph for a registered def.
    /// Called at create/restore before any backfill fills it. The def
    /// carries the HNSW params (#141-1), so restore rebuilds graphs with
    /// the same shape they were created with.
    pub fn ensure_vector_graph(&mut self, collection: &str, field: &str) {
        let def = match self.vector.get(collection).and_then(|m| m.get(field)) {
            Some(d) => (
                d.dim as usize,
                d.metric,
                HnswParams {
                    m: d.m,
                    ef_construction: d.ef_construction,
                    ef_search: d.ef_search,
                    binary_stage1: d.binary_stage1,
                },
            ),
            None => return,
        };
        self.hnsw
            .entry(collection.to_string())
            .or_default()
            .entry(field.to_string())
            .or_insert_with(|| HnswIndex::new(def.0, def.1, def.2));
    }

    /// Upsert one doc's embedding into every HNSW graph of `collection`
    /// that indexes its field. Wrong-dim / non-binary values are ignored
    /// (fail-closed, same rule as the planner gate). Deletes need no
    /// hook: graph nodes are never removed, the executor filters
    /// candidates against storage liveness.
    pub fn index_vector(&mut self, collection: &str, doc_id: &str, doc: &HakoDoc) {
        if let Some(graphs) = self.hnsw.get_mut(collection) {
            for (field_name, graph) in graphs.iter_mut() {
                if let Some(Value::Binary(b)) = doc.get(field_name) {
                    if let Ok(v) = decode_f32s(b) {
                        graph.upsert(doc_id, v);
                    }
                }
            }
        }
    }

    /// #195 parallel bulk build: swap a freshly merged graph in (the
    /// builder constructs it outside the manager lock; install is one
    /// pointer-assign under the caller's write lock). Same blind-insert
    /// semantics as the sequential `index_vector` path.
    pub fn install_vector_graph(&mut self, collection: &str, field: &str, graph: HnswIndex) {
        self.hnsw
            .entry(collection.to_string())
            .or_default()
            .insert(field.to_string(), graph);
    }

    /// Mark every graph of `collection` complete after a full pass
    /// (create backfill / recovery rescan) flowed through `index_vector`.
    /// Emptiness is data, not incompleteness: an empty pass still flips
    /// the flag, so later puts (hook-fed) serve ANN immediately instead
    /// of stranding the graph incomplete forever.
    pub fn complete_vector(&mut self, collection: &str) {
        if let Some(graphs) = self.hnsw.get_mut(collection) {
            for graph in graphs.values_mut() {
                graph.set_complete(true);
            }
        }
    }

    pub fn indexes_for_collection(
        &self,
        collection: &str,
    ) -> impl Iterator<Item = &CompositeIndex> {
        self.composite.indexes_for_collection(collection)
    }

    pub fn create_index(&mut self, definition: CompositeIndexDefinition) -> u32 {
        self.composite.create_index(definition)
    }

    pub fn has_index(&self, collection: &str, fields: &[String]) -> bool {
        if fields.is_empty() {
            return false;
        }

        self.composite
            .indexes_for_collection(collection)
            .any(|idx| {
                // An index can satisfy a query if the query fields 
                // are the leading prefix of the index fields.
                if idx.definition.fields.len() < fields.len() {
                    return false;
                }

                idx.definition
                    .fields
                    .iter()
                    .zip(fields)
                    .all(|(def, field)| def.field == field.as_str())
            })
    }

    pub fn exact_match_doc_ids(
        &self,
        collection: &str,
        fields: &[String],
        values: &[Value],
        // ) -> Option<Vec<String>> {
    ) -> Option<Vec<Arc<str>>> {
        self.composite
            .exact_match_doc_ids(collection, fields, values)
    }

    pub fn index_document(&mut self, collection: &str, doc_id: &str, doc: &HakoDoc) {
        // 1. Update Composite
        self.composite.index_document(collection, doc_id, doc);

        // 2. Update FTS
        if let Some(fields) = self.fts.get_mut(collection) {
            for (field_name, index) in fields.iter_mut() {
                if let Some(Value::String(text)) = doc.get(field_name) {
                    index.insert(text, doc_id.to_string());
                }
            }
        }

        // 3. ADD THIS: Update Secondary Indexes automatically
        // ponytail: one shared id Arc across every field of this doc (was a
        // String clone per field), keys encoded into a reused scratch buffer
        // with zero-alloc hits for hot values via `insert_borrowed`, and no
        // deep Value clone — `encode_scalar_into` borrows straight from the
        // doc (the old code cloned every indexed String value per write).
        if let Some(sec_map) = self.secondary.get_mut(collection) {
            let id_shared: Arc<str> = Arc::from(doc_id);
            crate::index::index_key::ENC_SCRATCH.with(|scratch| {
                let mut enc = scratch.borrow_mut();
                for (field_name, index) in sec_map.iter_mut() {
                    enc.clear();
                    if field_name.as_str() == "id" {
                        crate::index::index_key::encode_str_scalar_into(doc_id, &mut enc);
                    } else if field_name.as_str() == "_time" {
                        crate::index::index_key::encode_scalar_into(&Value::Int(doc._time), &mut enc);
                    } else if let Some(val) = doc.get(field_name) {
                        crate::index::index_key::encode_scalar_into(val, &mut enc);
                    } else {
                        continue;
                    }
                    index.insert_borrowed(&enc, id_shared.clone());
                }
            });
        }

        // 4. Vector HNSW (P1): upsert the embedding when the doc carries
        // an indexed binary field. Deletes intentionally need no hook
        // (liveness is external — see HnswIndex docs).
        self.index_vector(collection, doc_id, doc);

        // 5. Graph backlinks (issue #53): index outbound refs into
        // tracked targets. Self-gated (no-op when nothing tracked).
        self.traverse.index_doc(collection, doc_id, doc);
    }

    pub fn index_batch<'a, I>(&mut self, collection: &str, docs: I)
    where
        I: IntoIterator<Item = (&'a str, &'a HakoDoc)> + Clone,
    {
        for (doc_id, doc) in docs {
            self.index_document(collection, doc_id, doc);
        }
    }

    pub fn remove_document(&mut self, collection: &str, doc_id: &str, doc: &HakoDoc) {
        self.composite.remove_document(collection, doc_id, doc);

        if let Some(fields) = self.fts.get_mut(collection) {
            for (field_name, index) in fields.iter_mut() {
                if let Some(Value::String(text)) = doc.get(field_name) {
                    index.remove(text, doc_id);
                }
            }
        }

        if let Some(sec_map) = self.secondary.get_mut(collection) {
            for (field_name, index) in sec_map.iter_mut() {
                if let Some(val) = doc.get(field_name) {
                    index.remove(&crate::index::index_key::encode_scalar(val), doc_id);
                }
            }
        }

        // Graph backlinks: drop edges touching the deleted doc (both
        // directions; the old doc rides along on this path).
        self.traverse.remove_doc(collection, doc_id, doc);
    }

    pub fn remove_batch<'a, I>(&mut self, collection: &str, docs: I)
    where
        I: IntoIterator<Item = (&'a str, &'a HakoDoc)> + Clone,
    {
        for (doc_id, doc) in docs {
            self.remove_document(collection, doc_id, doc);
        }
    }

    /// Registers a new single-field index
    pub fn create_secondary_index(&mut self, collection: &str, field: &str) {
        self.secondary
            .entry(collection.to_string())
            .or_default()
            .insert(field.to_string(), SecondaryIndex::default());
    }

    pub fn drop_secondary_index(&mut self, collection: &str, field: &str) -> bool {
        let removed = self
            .secondary
            .get_mut(collection)
            .is_some_and(|fields| fields.remove(field).is_some());
        if self
            .secondary
            .get(collection)
            .is_some_and(|fields| fields.is_empty())
        {
            self.secondary.remove(collection);
        }
        removed
    }

    pub fn drop_fts_index(&mut self, collection: &str, field: &str) -> bool {
        let removed = self
            .fts
            .get_mut(collection)
            .is_some_and(|fields| fields.remove(field).is_some());
        if self.fts.get(collection).is_some_and(|fields| fields.is_empty()) {
            self.fts.remove(collection);
        }
        removed
    }

    /// Remove a vector definition AND its derived HNSW graph. An in-flight
    /// backfill becomes a no-op on its next chunk (the def is gone).
    pub fn drop_vector_index(&mut self, collection: &str, field: &str) -> bool {
        let removed = self
            .vector
            .get_mut(collection)
            .is_some_and(|fields| fields.remove(field).is_some());
        if self
            .vector
            .get(collection)
            .is_some_and(|fields| fields.is_empty())
        {
            self.vector.remove(collection);
        }
        let dropped_graph = self
            .hnsw
            .get_mut(collection)
            .is_some_and(|graphs| graphs.remove(field).is_some());
        if self.hnsw.get(collection).is_some_and(|graphs| graphs.is_empty()) {
            self.hnsw.remove(collection);
        }
        removed || dropped_graph
    }

    pub fn drop_traverse_index(&mut self, collection: &str) -> bool {
        self.traverse.untrack(collection)
    }

    /// Optimized lookup: Check secondary indexes if no composite exists
    pub fn lookup_secondary(
        &self,
        collection: &str,
        field: &str,
        value: &[u8],
    ) -> Option<Vec<Arc<str>>> {
        self.secondary
            .get(collection)?
            .get(field)?
            .range_scan(value, value) // Exact match scan
            .into()
    }

    pub fn export_state(&self) -> Result<Vec<u8>, HakoError> {
        // Composite rides along (hakodb#4): without it every restart
        // emptied composite indexes (probes missed -> full-sweep fallback
        // while secondary/fts survived). Old two-element files still load
        // via the legacy branch of import_state.
        bincode::serialize(&(&self.secondary, &self.fts, self.composite.export_snapshot()))
            .map_err(|e| HakoError::Corrupt(format!("Index export failed: {}", e)))
    }

    /// WAL tails at export, per collection: (wal data_len, wal file_len).
    /// Lets recovery tell a fresh snapshot from a stale one (crash after
    /// the last snapshot) without trusting timestamps.
    ///
    /// 5-element format (#189): the HNSW graphs ride along as derived
    /// state so reopen skips the full rebuild. Element 4 is the graphs
    /// keyed (collection, field) → graph; import validates each against
    /// the live def (dim/metric/params) and drops mismatches — a stale or
    /// foreign graph degrades to the rebuild path, never to wrong results.
    pub fn export_state_with_tails(&self, tails: &WalTails) -> Result<Vec<u8>, HakoError> {
        bincode::serialize(&(
            &self.secondary,
            &self.fts,
            self.composite.export_snapshot(),
            tails,
            &self.hnsw,
        ))
        .map_err(|e| HakoError::Corrupt(format!("Index export failed: {}", e)))
    }

    /// True when the manager holds any RAM entries for `collection`
    /// (secondary, fts, or composite trees). Vector counts as a
    /// registration (P0 keeps no RAM entries — rescan trivially holds).
    pub fn has_collection(&self, collection: &str) -> bool {
        self.secondary.contains_key(collection)
            || self.fts.contains_key(collection)
            || self.composite.has_collection(collection)
            || self.vector.contains_key(collection)
            || self.traverse.is_tracked(collection)
    }

    /// Drop every RAM entry for `collection` while keeping all index
    /// registrations (rescan refills them). Definitions are untouched.
    pub fn clear_collection(&mut self, collection: &str) {
        if let Some(sec_map) = self.secondary.get_mut(collection) {
            for idx in sec_map.values_mut() {
                idx.clear();
            }
        }
        if let Some(fts_map) = self.fts.get_mut(collection) {
            for idx in fts_map.values_mut() {
                idx.clear();
            }
        }
        // Vector defs stay registered; graphs reset to incomplete (the
        // recovery rescan refills them via index_document, then marks
        // complete — same order as every other family).
        if let Some(graphs) = self.hnsw.get_mut(collection) {
            for graph in graphs.values_mut() {
                graph.clear();
            }
        }
        // Traverse defs stay registered; backlinks reset (rescan refills
        // via the hook — same order).
        self.traverse.clear_collection(collection);
        self.composite.clear_collection(collection);
    }

    /// Remove every registration AND RAM structure for `collection`
    /// (issue #31 drop). Unlike [`Self::clear_collection`], definitions
    /// do not survive: the caller re-persists definitions.json after
    /// this, so a dropped collection's indexes are gone for good.
    pub fn drop_collection_defs(&mut self, collection: &str) {
        self.secondary.remove(collection);
        self.fts.remove(collection);
        self.vector.remove(collection);
        self.hnsw.remove(collection);
        self.traverse.untrack(collection);
        self.composite.drop_collection(collection);
    }

    // pub fn import_state(&mut self, bytes: &[u8]) -> Result<(), HakoError> {
    //     // By importing hashbrown::HashMap at the top, 'HashMap' here 
    //     // now correctly refers to the hashbrown version.
    //     let (sec, fts): (
    //         HashMap<String, HashMap<String, crate::index::secondary_index::SecondaryIndex>>,
    //         HashMap<String, HashMap<String, crate::index::inverted_index::InvertedIndex>>
    //     ) = bincode::deserialize(bytes)
    //         .map_err(|e| HakoError::Corrupt(format!("Index import failed: {}", e)))?;
        
    //     self.secondary = sec;
    //     self.fts = fts;
    //     Ok(())
    // }
     pub fn import_state(&mut self, bytes: &[u8], skip: &std::collections::HashSet<String>) -> Result<(bool, Option<WalTails>), HakoError> {
        // Returns (composite trees came from the snapshot, WAL tails or
        // None when the file predates them). Four-element files are
        // current; three-element restore everything but report no tails
        // (caller rescans — one-time upgrade cost); legacy two-element
        // files restore secondary/fts and backfill composites from data.
        // Collections in `skip` were (re)built by a touch/load after
        // open — newer than any snapshot — so their entries are left
        // alone (both orders converge identically this way).
        type Trees = HashMap<u32, crate::index::composite::composite_index::CompositeIndex>;
        // 5-element (#189): graphs ride along. Each graph is validated
        // against its live def (dim/metric/params) — mismatching or
        // unregistered fields drop to the rebuild path (graph stays
        // empty/incomplete; STEP C2's backfill fills it). Imported graphs
        // start `complete = false`: docs written after the snapshot must
        // re-upsert through the repair pass before ANN may serve.
        if let Ok((sec, fts, (trees, next_id), tails, graphs)) = bincode::deserialize::<(
            HashMap<String, HashMap<String, crate::index::secondary_index::SecondaryIndex>>,
            HashMap<String, HashMap<String, crate::index::inverted_index::InvertedIndex>>,
            (Trees, u32),
            WalTails,
            HashMap<String, HashMap<String, crate::index::vector::HnswIndex>>,
        )>(bytes)
        {
            Self::merge_maps_skipping(&mut self.secondary, sec, skip);
            Self::merge_maps_skipping(&mut self.fts, fts, skip);
            self.composite.import_snapshot_filtered(trees, next_id, skip);
            self.import_graphs(graphs, skip);
            return Ok((true, Some(tails)));
        }
        if let Ok((sec, fts, (trees, next_id))) = bincode::deserialize::<(
            HashMap<String, HashMap<String, crate::index::secondary_index::SecondaryIndex>>,
            HashMap<String, HashMap<String, crate::index::inverted_index::InvertedIndex>>,
            (Trees, u32),
        )>(bytes)
        {
            Self::merge_maps_skipping(&mut self.secondary, sec, skip);
            Self::merge_maps_skipping(&mut self.fts, fts, skip);
            self.composite.import_snapshot_filtered(trees, next_id, skip);
            return Ok((true, None));
        }
        #[allow(clippy::type_complexity)]
        let (sec, fts): (
            HashMap<String, HashMap<String, crate::index::secondary_index::SecondaryIndex>>,
            HashMap<String, HashMap<String, crate::index::inverted_index::InvertedIndex>>,
        ) = bincode::deserialize(bytes)
            .map_err(|e| HakoError::Corrupt(format!("Index import failed: {}", e)))?;
        Self::merge_maps_skipping(&mut self.secondary, sec, skip);
        Self::merge_maps_skipping(&mut self.fts, fts, skip);
        Ok((false, None))
    }

    /// Install snapshot-carried HNSW graphs (#189): validate each against
    /// the live def (dim/metric/params must all match — a def edited
    /// between snapshots invalidates its graph), skip collections that
    /// were touched after open (fresher than any snapshot), and force
    /// `complete = false` so the repair pass gates ANN until it ran.
    fn import_graphs(
        &mut self,
        graphs: HashMap<String, HashMap<String, crate::index::vector::HnswIndex>>,
        skip: &std::collections::HashSet<String>,
    ) {
        for (col, fields) in graphs {
            if skip.contains(&col) {
                continue;
            }
            let defs = match self.vector.get(&col) {
                Some(d) => d,
                None => continue,
            };
            for (field, mut graph) in fields {
                let def = match defs.get(&field) {
                    Some(d) => d,
                    None => continue,
                };
                if !graph.matches_def(
                    def.dim,
                    def.metric,
                    crate::index::vector::HnswParams {
                        m: def.m,
                        ef_construction: def.ef_construction,
                        ef_search: def.ef_search,
                        binary_stage1: def.binary_stage1,
                    },
                ) {
                    continue;
                }
                graph.set_complete(false);
                self.hnsw
                    .entry(col.clone())
                    .or_default()
                    .insert(field, graph);
            }
        }
    }

    fn merge_maps_skipping<K, V>(
        into: &mut HashMap<String, HashMap<K, V>>,
        from: HashMap<String, HashMap<K, V>>,
        skip: &std::collections::HashSet<String>,
    )
    where
        K: std::hash::Hash + Eq,
    {
        for (col, fields) in from {
            if skip.contains(&col) {
                continue;
            }
            // Only overwrite live definitions. A stale snapshot must not
            // recreate an empty collection entry for a dropped index.
            let Some(col_map) = into.get_mut(&col) else {
                continue;
            };
            for (field, index) in fields {
                if let Some(existing_index) = col_map.get_mut(&field) {
                    *existing_index = index;
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::document::value::Value;
    use crate::index::composite::definition::SortDirection;

    fn doc(passw: &str, nim: &str) -> HakoDoc {
        let mut d = HakoDoc::default();
        d.insert("passw", Value::String(passw.into()));
        d.insert("nim", Value::String(nim.into()));
        d
    }

    fn manager_with_entries() -> IndexManager {
        let mut m = IndexManager::default();
        m.create_secondary_index("students", "nim");
        let id = m.create_index(
            CompositeIndexDefinition::new("students")
                .with_fields(vec![
                    ("passw".to_string(), SortDirection::Asc),
                    ("nim".to_string(), SortDirection::Asc),
                ]),
        );
        assert_eq!(id, 1);
        m.index_document("students", "d1", &doc("28021988", "F1"));
        m.index_document("students", "d2", &doc("28021988", "F2"));
        m
    }

    fn vec_def(m: &mut IndexManager, metric: Metric) {
        m.create_vector_index(
            "pts",
            "emb",
            4,
            metric,
            HnswParams { m: Some(16), ef_construction: Some(48), ef_search: Some(64), binary_stage1: false },
        )
        .unwrap();
        m.ensure_vector_graph("pts", "emb");
    }

    /// #189: a snapshot-carried graph restores node-for-node, gates ANN
    /// off (complete=false) until the repair pass ran, and a def mismatch
    /// (different metric) drops the graph to the rebuild path.
    #[test]
    fn hnsw_graph_roundtrips_through_snapshot() {
        let mut m = IndexManager::default();
        vec_def(&mut m, Metric::Cosine);
        {
            let g = m.hnsw.get_mut("pts").unwrap().get_mut("emb").unwrap();
            g.upsert("a", vec![1.0, 0.0, 0.0, 0.0]);
            g.upsert("b", vec![0.0, 1.0, 0.0, 0.0]);
            g.set_complete(true);
        }
        let bytes = m
            .export_state_with_tails(&Default::default())
            .expect("export");
        let mut m2 = IndexManager::default();
        vec_def(&mut m2, Metric::Cosine);
        let (restored, tails) = m2.import_state(&bytes, &Default::default()).expect("import");
        assert!(restored);
        assert!(tails.is_some(), "5-element format carries tails");
        let g = m2.hnsw.get("pts").unwrap().get("emb").unwrap();
        assert_eq!(g.len(), 2, "graph restores node-for-node");
        assert!(!g.complete(), "imported graphs gate ANN until repair");

        // Metric changed under the same field: the snapshot graph no
        // longer matches the def — dropped, rebuild path takes over.
        let mut m3 = IndexManager::default();
        vec_def(&mut m3, Metric::L2);
        let _ = m3.import_state(&bytes, &Default::default()).expect("import");
        assert_eq!(m3.hnsw.get("pts").unwrap().get("emb").unwrap().len(), 0);
    }

    #[test]
    fn export_import_round_trip_keeps_composite() {
        let m = manager_with_entries();
        let bytes = m.export_state().expect("export");
        // Fresh manager with the SAME definitions (as restored from
        // definitions.json before import runs in open()).
        let mut m2 = IndexManager::default();
        m2.create_secondary_index("students", "nim");
        m2.create_index(
            CompositeIndexDefinition::new("students")
                .with_fields(vec![
                    ("passw".to_string(), SortDirection::Asc),
                    ("nim".to_string(), SortDirection::Asc),
                ]),
        );
        assert!(m2.import_state(&bytes, &std::collections::HashSet::new()).expect("import").0);
        // Trees restored verbatim: point probe finds both rows.
        let ids = m2
            .composite
            .exact_match_doc_ids(
                "students",
                &["passw".to_string(), "nim".to_string()],
                &[Value::String("28021988".into()), Value::String("F1".into())],
            )
            .expect("probe");
        assert_eq!(ids.len(), 1);
        assert_eq!(&*ids[0], "d1");
    }

    #[test]
    fn import_legacy_two_element_file_reports_false() {
        let m = manager_with_entries();
        // Legacy shape: secondary + fts only (pre-fix files).
        let legacy: Vec<u8> =
            bincode::serialize(&(&m.secondary, &m.fts)).expect("legacy export");
        let mut m2 = IndexManager::default();
        m2.create_secondary_index("students", "nim");
        m2.create_index(
            CompositeIndexDefinition::new("students")
                .with_fields(vec![
                    ("passw".to_string(), SortDirection::Asc),
                    ("nim".to_string(), SortDirection::Asc),
                ]),
        );
        assert!(!m2.import_state(&legacy, &std::collections::HashSet::new()).expect("legacy import").0);
        // Secondary restored, composite untouched (empty, awaiting backfill).
        assert!(m2.secondary.get("students").is_some_and(|mm| mm.contains_key("nim")));
        assert!(m2
            .composite
            .exact_match_doc_ids(
                "students",
                &["passw".to_string(), "nim".to_string()],
                &[Value::String("28021988".into()), Value::String("F1".into())],
            )
            .is_none_or(|v| v.is_empty()));
    }

    #[test]
    fn stale_snapshot_does_not_recreate_dropped_entries() {
        let m = manager_with_entries();
        let legacy: Vec<u8> =
            bincode::serialize(&(&m.secondary, &m.fts)).expect("legacy export");
        let mut m2 = IndexManager::default();
        m2.import_state(&legacy, &std::collections::HashSet::new())
            .expect("legacy import");
        assert!(m2.secondary.is_empty());
        assert!(m2.fts.is_empty());
        assert!(!m2.has_collection("students"));
    }

    #[test]
    fn import_skips_definition_mismatch() {
        let m = manager_with_entries();
        let bytes = m.export_state().expect("export");
        // Same id, DIFFERENT fields: stale entry must not overwrite.
        let mut m2 = IndexManager::default();
        m2.create_secondary_index("students", "nim");
        m2.create_index(
            CompositeIndexDefinition::new("students")
                .with_fields(vec![("passw".to_string(), SortDirection::Asc)]),
        );
        assert!(m2.import_state(&bytes, &std::collections::HashSet::new()).expect("import").0);
        assert!(m2
            .composite
            .exact_match_doc_ids(
                "students",
                &["passw".to_string()],
                &[Value::String("28021988".into())],
            )
            .is_none_or(|v| v.is_empty()));
    }

    #[test]
    fn tails_roundtrip_and_clear_collection() {
        let m = manager_with_entries();
        let mut tails = WalTails::new();
        tails.insert("students".to_string(), (1234, 5678));
        let bytes = m.export_state_with_tails(&tails).expect("export");
        let mut m2 = IndexManager::default();
        // Definitions are restored before the snapshot on open; mirror
        // that here so import has a live registration to fill.
        m2.create_secondary_index("students", "nim");
        let (restored, got) = m2.import_state(&bytes, &std::collections::HashSet::new()).expect("import");
        assert!(restored);
        assert_eq!(got.expect("tails").get("students"), Some(&(1234, 5678)));
        assert!(m2.has_collection("students"));
        m2.clear_collection("students");
        // Entries gone, registrations kept (rescan refills them).
        assert!(m2.has_collection("students"));
        assert!(m2
            .secondary
            .get("students")
            .is_some_and(|mm| mm.values().all(|idx| idx.get_map().is_empty())));
        // Legacy three-element files report no tails (caller rescans).
        let legacy3 = m.export_state().expect("export");
        let mut m3 = IndexManager::default();
        let (_, tails3) = m3.import_state(&legacy3, &std::collections::HashSet::new()).expect("import");
        assert!(tails3.is_none());
    }

    #[test]
    fn import_skips_touched_collections() {
        let m = manager_with_entries();
        let bytes = m.export_state().expect("export");
        let mut skip = std::collections::HashSet::new();
        skip.insert("students".to_string());
        let mut m2 = IndexManager::default();
        m2.create_secondary_index("students", "nim");
        let (restored, _) = m2.import_state(&bytes, &skip).expect("import");
        assert!(restored);
        // Untouched families still merge; skipped collection stays empty.
        assert!(m2
            .secondary
            .get("students")
            .is_some_and(|mm| mm.values().all(|idx| idx.get_map().is_empty())));
    }
}