tapirus 1.2.1

Embedded multi-model database with SQL, vector search and local AI memory
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
use super::*;
use crate::traits::VectorIndexEngine;
use crate::vector::hnsw::HnswConfig;
use crate::vector::{DistanceMetric, HnswIndex};
use sha2::{Digest, Sha256};
use std::borrow::Cow;

type Space = (Option<String>, usize);
type ExternalKey = (Option<String>, Option<String>, String);

pub(super) fn content_hash(content: &str) -> String {
    use std::fmt::Write as _;

    let mut result = String::with_capacity(64);
    for byte in Sha256::digest(content.as_bytes()) {
        write!(&mut result, "{byte:02x}").expect("writing to String cannot fail");
    }
    result
}
fn external_key(entry: &MemoryEntry) -> Option<ExternalKey> {
    Some((
        entry.namespace.as_ref().map(|s| s.to_lowercase()),
        entry.session_id.clone(),
        entry.external_id.clone()?,
    ))
}
fn scope_keys(entry: &MemoryEntry) -> Vec<(u8, String)> {
    let mut keys = Vec::new();
    if let Some(namespace) = &entry.namespace {
        keys.push((0, namespace.to_lowercase()));
    }
    if let Some(session) = &entry.session_id {
        keys.push((1, session.clone()));
    }
    for tag in &entry.tags {
        keys.push((2, tag.to_lowercase()));
    }
    keys.sort();
    keys.dedup();
    keys
}
fn estimate(entry: &MemoryEntry) -> usize {
    let metadata = entry.tags.iter().map(String::len).sum::<usize>()
        + [
            &entry.namespace,
            &entry.session_id,
            &entry.external_id,
            &entry.source_version,
            &entry.embedding_model,
        ]
        .into_iter()
        .flatten()
        .map(String::len)
        .sum::<usize>();
    entry
        .content
        .len()
        .saturating_mul(6)
        .saturating_add(
            entry
                .vector
                .as_ref()
                .map_or(0, |v| v.len().saturating_mul(16)),
        )
        .saturating_add(metadata.saturating_mul(4))
        .saturating_add(2048)
}

fn unit_vector(vector: &[f32]) -> Vec<f32> {
    let norm = vector
        .iter()
        .map(|v| f64::from(*v).powi(2))
        .sum::<f64>()
        .sqrt();
    vector
        .iter()
        .map(|v| {
            if norm > 0.0 {
                (f64::from(*v) / norm) as f32
            } else {
                0.0
            }
        })
        .collect()
}

fn doc_vector_fingerprint(entry: &MemoryEntry) -> u64 {
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    let mix = |h: &mut u64, bytes: &[u8]| {
        for &b in bytes {
            *h ^= u64::from(b);
            *h = h.wrapping_mul(0x0000_0100_0000_01b3);
        }
    };
    mix(&mut hash, &entry.id.to_le_bytes());
    mix(&mut hash, &entry.revision.to_le_bytes());
    if let Some(model) = &entry.embedding_model {
        mix(&mut hash, &[1]);
        mix(&mut hash, &(model.len() as u32).to_le_bytes());
        mix(&mut hash, model.as_bytes());
    } else {
        mix(&mut hash, &[0]);
    }
    if let Some(vec) = &entry.vector {
        mix(&mut hash, &(vec.len() as u32).to_le_bytes());
        for &val in vec {
            mix(&mut hash, &val.to_bits().to_le_bytes());
        }
    }
    hash
}

#[derive(Debug, Clone)]
struct RecordMeta {
    external: Option<ExternalKey>,
    scopes: Vec<(u8, String)>,
    space: Option<Space>,
    bytes: usize,
}
#[derive(Debug, Clone)]
struct VectorSpace {
    index: HnswIndex,
    documents: HashMap<u64, u64>,
    next_node: u64,
}

#[derive(Debug, Clone, Default)]
pub(super) struct MemoryRuntime {
    pub config: MemoryConfig,
    records: HashMap<u64, RecordMeta>,
    external: HashMap<ExternalKey, u64>,
    scopes: HashMap<(u8, String), HashSet<u64>>,
    spaces: HashMap<Space, usize>,
    estimated_bytes: usize,
    dirty: HashSet<u64>,
    indexes: HashMap<Space, VectorSpace>,
    locations: HashMap<u64, (Space, u64)>,
    cache_synced: bool,
}

impl MemoryRuntime {
    pub fn changed(&mut self, id: u64, entry: Option<&MemoryEntry>) {
        self.cache_synced = false;
        if let Some(old) = self.records.remove(&id) {
            self.estimated_bytes = self.estimated_bytes.saturating_sub(old.bytes);
            if let Some(key) = old.external {
                self.external.remove(&key);
            }
            for key in old.scopes {
                if let Some(ids) = self.scopes.get_mut(&key) {
                    ids.remove(&id);
                    if ids.is_empty() {
                        self.scopes.remove(&key);
                    }
                }
            }
            if let Some(space) = old.space
                && let Some(count) = self.spaces.get_mut(&space)
            {
                *count -= 1;
                if *count == 0 {
                    self.spaces.remove(&space);
                }
            }
        }
        if let Some(entry) = entry {
            let meta = RecordMeta {
                external: external_key(entry),
                scopes: scope_keys(entry),
                space: entry
                    .vector
                    .as_ref()
                    .map(|v| (entry.embedding_model.clone(), v.len())),
                bytes: estimate(entry),
            };
            if let Some(key) = &meta.external {
                self.external.insert(key.clone(), id);
            }
            for key in &meta.scopes {
                self.scopes.entry(key.clone()).or_default().insert(id);
            }
            if let Some(space) = &meta.space {
                *self.spaces.entry(space.clone()).or_default() += 1;
            }
            self.estimated_bytes = self.estimated_bytes.saturating_add(meta.bytes);
            self.records.insert(id, meta);
        }
        self.dirty.insert(id);
    }

    fn allowed(&self, search: &MemorySearch) -> Option<Cow<'_, HashSet<u64>>> {
        // Common single-scope queries borrow their posting list. Copying every
        // ID in a large namespace made an otherwise indexed query linear in N.
        let single = if search.tags.is_empty() && search.session_id.is_none() {
            search.namespace.as_ref().map(|ns| (0, ns.to_lowercase()))
        } else if search.tags.is_empty() && search.namespace.is_none() {
            search.session_id.as_ref().map(|id| (1, id.clone()))
        } else if search.namespace.is_none()
            && search.session_id.is_none()
            && search.tags.len() == 1
        {
            Some((2, search.tags[0].to_lowercase()))
        } else {
            None
        };
        if let Some(key) = single {
            return Some(
                self.scopes
                    .get(&key)
                    .map_or_else(|| Cow::Owned(HashSet::new()), Cow::Borrowed),
            );
        }
        let empty = HashSet::new();
        let mut lists = Vec::new();
        if let Some(ns) = &search.namespace {
            lists.push(self.scopes.get(&(0, ns.to_lowercase())).unwrap_or(&empty));
        }
        if let Some(session) = &search.session_id {
            lists.push(self.scopes.get(&(1, session.clone())).unwrap_or(&empty));
        }
        let tags: HashSet<u64> = search
            .tags
            .iter()
            .filter_map(|t| self.scopes.get(&(2, t.to_lowercase())))
            .flatten()
            .copied()
            .collect();
        if !search.tags.is_empty() {
            lists.push(&tags);
        }
        lists.sort_by_key(|ids| ids.len());
        let mut lists = lists.into_iter();
        let mut result = lists.next()?.clone();
        for ids in lists {
            result.retain(|id| ids.contains(id));
        }
        Some(Cow::Owned(result))
    }
}

impl MemoryEngine {
    fn ensure_runtime(&mut self) -> Result<()> {
        if self.runtime.records.len() == self.entries.len() {
            return Ok(());
        }
        // Derived state is deliberately excluded from serialized engines.
        let config = self.runtime.config.clone();
        let old = std::mem::replace(
            &mut self.runtime,
            MemoryRuntime {
                config,
                ..Default::default()
            },
        );
        let result = (|| {
            for entry in self.entries.values() {
                self.validate_entry(entry)?;
                self.runtime.changed(entry.id, Some(entry));
            }
            Ok(())
        })();
        if result.is_err() {
            self.runtime = old;
        }
        result
    }
    /// Create an engine with explicit resource admission limits.
    pub fn with_config(config: MemoryConfig) -> Result<Self> {
        config.validate()?;
        let mut engine = Self::new();
        engine.runtime.config = config;
        Ok(engine)
    }
    /// Current runtime limits; these do not alter the database file format.
    pub fn configuration(&self) -> &MemoryConfig {
        &self.runtime.config
    }
    /// Change admission limits and rebuild derived indexes lazily.
    pub fn configure(&mut self, config: MemoryConfig) -> Result<()> {
        self.ensure_runtime()?;
        config.validate()?;
        if self.runtime.spaces.len() > config.max_vector_spaces {
            return Err(Error::ConstraintViolation(
                "Existing model spaces exceed max_vector_spaces".into(),
            ));
        }
        // Configuration is rare. Validate sources before discarding any old index.
        let previous = std::mem::replace(&mut self.runtime.config, config);
        let checked = self
            .entries
            .values()
            .try_for_each(|entry| self.validate_entry(entry));
        if let Err(error) = checked {
            self.runtime.config = previous;
            return Err(error);
        }
        self.runtime.indexes.clear();
        self.runtime.locations.clear();
        self.runtime.cache_synced = false;
        self.runtime.dirty.extend(self.entries.keys().copied());
        Ok(())
    }
    pub(super) fn validate_entry(&self, entry: &MemoryEntry) -> Result<()> {
        let config = &self.runtime.config;
        let reject = |message: &str| Error::ConstraintViolation(message.into());
        if entry.content.trim().is_empty() || entry.content.len() > config.max_document_bytes {
            return Err(reject(
                "Memory content is empty or exceeds max_document_bytes",
            ));
        }
        if !entry.importance.is_finite() || !(0.0..=1.0).contains(&entry.importance) {
            return Err(reject("Memory importance must be between zero and one"));
        }
        if entry.tags.len() > 256
            || entry
                .tags
                .iter()
                .any(|s| s.is_empty() || s.len() > 256 || s.chars().any(char::is_control))
        {
            return Err(reject(
                "Memory tags must be nonempty, at most 256 bytes each and 256 per document",
            ));
        }
        for value in [
            &entry.namespace,
            &entry.session_id,
            &entry.external_id,
            &entry.source_version,
            &entry.embedding_model,
        ]
        .into_iter()
        .flatten()
        {
            if value.trim().is_empty() || value.len() > 512 || value.chars().any(char::is_control) {
                return Err(reject(
                    "Memory identifiers must be nonempty, at most 512 bytes and contain no control characters",
                ));
            }
        }
        if entry.embedding_model.is_some() && entry.vector.is_none() {
            return Err(reject("embedding_model requires an embedding"));
        }
        if let Some(vector) = &entry.vector {
            if vector.is_empty()
                || vector.len() > config.max_vector_dimensions
                || vector.iter().any(|v| !v.is_finite())
            {
                return Err(reject(
                    "Embedding dimensions/components exceed memory limits",
                ));
            }
            if let Some(model) = &entry.embedding_model
                && let Some(((_, dimension), _)) = self
                    .runtime
                    .spaces
                    .iter()
                    .find(|((m, d), _)| m.as_ref() == Some(model) && *d != vector.len())
            {
                return Err(Error::DimensionMismatch(*dimension, vector.len()));
            }
            let space = (entry.embedding_model.clone(), vector.len());
            if !self.runtime.spaces.contains_key(&space)
                && self.runtime.spaces.len() >= config.max_vector_spaces
            {
                return Err(reject("Memory vector-space budget exceeded"));
            }
        }
        if let Some(key) = external_key(entry)
            && self
                .runtime
                .external
                .get(&key)
                .is_some_and(|id| *id != entry.id)
        {
            return Err(reject("Duplicate external_id within namespace/session"));
        }
        let replacing = self.runtime.records.get(&entry.id);
        if self.entries.len() + usize::from(!self.entries.contains_key(&entry.id))
            > config.max_documents
        {
            return Err(reject("Memory document budget exceeded"));
        }
        let bytes = self
            .runtime
            .estimated_bytes
            .saturating_sub(replacing.map_or(0, |old| old.bytes))
            .saturating_add(estimate(entry));
        if bytes > config.max_estimated_bytes {
            return Err(reject("Memory estimated-resident-byte budget exceeded"));
        }
        Ok(())
    }
    pub(crate) fn write_document(
        &mut self,
        document: &MemoryDocument,
        upsert: bool,
        now: u64,
    ) -> Result<u64> {
        self.ensure_runtime()?;
        if document.expires_at.is_some() && document.ttl_seconds.is_some() {
            return Err(Error::ConstraintViolation(
                "Use expires_at or ttl_seconds, not both".into(),
            ));
        }
        let existing_id = document
            .external_id
            .as_ref()
            .and_then(|id| {
                self.runtime.external.get(&(
                    document.namespace.as_ref().map(|s| s.to_lowercase()),
                    document.session_id.clone(),
                    id.clone(),
                ))
            })
            .copied();
        if !upsert && existing_id.is_some() {
            return Err(Error::ConstraintViolation(
                "external_id already exists; use upsert_memory".into(),
            ));
        }
        if upsert && document.external_id.is_none() {
            return Err(Error::ConstraintViolation(
                "upsert_memory requires external_id".into(),
            ));
        }
        let old = existing_id.and_then(|id| self.entries.get(&id));
        if document
            .expected_revision
            .is_some_and(|revision| revision != old.map_or(0, |e| e.revision))
        {
            return Err(Error::ConstraintViolation(
                "Memory revision conflict".into(),
            ));
        }
        let id = existing_id.unwrap_or(self.next_id);
        if id == 0 || id == u64::MAX {
            return Err(Error::ConstraintViolation(
                "Memory ID space exhausted".into(),
            ));
        }
        let expires_at = match document.ttl_seconds {
            Some(ttl) => Some(now.checked_add(ttl).ok_or_else(|| {
                Error::ConstraintViolation("Memory expiry overflows Unix seconds".into())
            })?),
            None => document.expires_at,
        };
        let revision = old
            .map_or(0, |e| e.revision)
            .checked_add(1)
            .ok_or_else(|| Error::ConstraintViolation("Memory revision overflow".into()))?;
        let entry = MemoryEntry {
            id,
            content: document.content.clone(),
            vector: document.embedding.clone(),
            importance: document.importance,
            timestamp: old.map_or(now, |e| e.timestamp),
            last_accessed: old.map_or(now, |e| e.last_accessed),
            access_count: old.map_or(0, |e| e.access_count),
            tags: document.tags.clone(),
            associations: old.map_or_else(Vec::new, |e| e.associations.clone()),
            namespace: document.namespace.clone(),
            session_id: document.session_id.clone(),
            external_id: document.external_id.clone(),
            source_version: document.source_version.clone(),
            embedding_model: document.embedding_model.clone(),
            expires_at,
            revision,
            updated_at: now,
            content_hash: content_hash(&document.content),
        };
        self.restore_entry(entry)?;
        Ok(id)
    }
    /// Accounting for sources and indexes currently materialized in this engine.
    pub fn stats(&self) -> MemoryStats {
        MemoryStats {
            documents: self.entries.len(),
            estimated_resident_bytes: self.runtime.estimated_bytes,
            max_estimated_bytes: self.runtime.config.max_estimated_bytes,
            vector_spaces: self.runtime.spaces.len(),
            indexed_vectors: self
                .runtime
                .indexes
                .values()
                .map(|s| s.documents.len())
                .sum(),
            pending_index_updates: self.runtime.dirty.len(),
        }
    }
    pub(crate) fn remove_ids(&mut self, ids: &[u64]) -> (Vec<u64>, Vec<u64>) {
        let ids: HashSet<_> = ids.iter().copied().collect();
        let mut removed = Vec::new();
        let mut updated = Vec::new();
        for &id in &ids {
            if self.entries.remove(&id).is_some() {
                self.bm25.remove_document(id);
                self.runtime.changed(id, None);
                removed.push(id);
            }
        }
        for entry in self.entries.values_mut() {
            let old = entry.associations.len();
            entry.associations.retain(|id| !ids.contains(id));
            if old != entry.associations.len() {
                updated.push(entry.id);
            }
        }
        removed.sort_unstable();
        updated.sort_unstable();
        (removed, updated)
    }
    /// Build/update derived vector indexes from authoritative source records.
    pub fn prepare_indexes(&mut self) -> Result<MemoryStats> {
        self.ensure_runtime()?;
        let mut dirty: Vec<_> = self.runtime.dirty.iter().copied().collect();
        dirty.sort_unstable();
        for id in dirty {
            if let Some((space, node)) = self.runtime.locations.remove(&id)
                && let Some(index) = self.runtime.indexes.get_mut(&space)
            {
                index.index.mark_deleted(node);
                index.documents.remove(&node);
            }
            if let Some(entry) = self.entries.get(&id)
                && let Some(vector) = &entry.vector
            {
                let key = (entry.embedding_model.clone(), vector.len());
                let config = &self.runtime.config;
                let index =
                    self.runtime
                        .indexes
                        .entry(key.clone())
                        .or_insert_with(|| VectorSpace {
                            index: HnswIndex::with_config_and_seed(
                                vector.len(),
                                DistanceMetric::Cosine,
                                HnswConfig {
                                    m: config.hnsw_m,
                                    m0: config.hnsw_m * 2,
                                    ef_construction: config.ef_construction,
                                    ef_search: config.ef_search,
                                    quantize_sq8: false,
                                },
                                20_261_016,
                            ),
                            documents: HashMap::new(),
                            next_node: 1,
                        });
                let node = index.next_node;
                index.next_node = node.checked_add(1).ok_or_else(|| {
                    Error::ConstraintViolation("Memory index node space exhausted".into())
                })?;
                index.index.insert_vector(node, &unit_vector(vector))?;
                index.documents.insert(node, id);
                self.runtime.locations.insert(id, (key, node));
            }
            self.runtime.dirty.remove(&id);
        }
        self.runtime
            .indexes
            .retain(|_, index| !index.documents.is_empty());
        for index in self.runtime.indexes.values_mut() {
            if index.index.tombstones.len() > index.documents.len() / 4 + 64 {
                index.index.rebuild()?;
            }
        }
        Ok(self.stats())
    }

    /// Build any pending HNSW updates and encode the persistent index cache when out of sync.
    ///
    /// Returns `Ok(None)` when the in-memory index cache already matches what is synced on disk.
    pub(crate) fn export_cached_indexes(&mut self) -> Result<Option<Vec<u8>>> {
        if !self.runtime.dirty.is_empty() {
            self.prepare_indexes()?;
        } else {
            self.ensure_runtime()?;
        }
        if self.runtime.cache_synced {
            return Ok(None);
        }

        let mut spaces: Vec<_> = self.runtime.indexes.iter().collect();
        spaces.sort_by_key(|(a, _)| *a);

        let mut encoded_spaces = Vec::with_capacity(spaces.len());
        for ((model, dims), space) in spaces {
            let mut docs = Vec::with_capacity(space.documents.len());
            for (&node_id, &doc_id) in &space.documents {
                if let Some(entry) = self.entries.get(&doc_id) {
                    docs.push((node_id, doc_id, doc_vector_fingerprint(entry)));
                }
            }
            docs.sort_unstable_by_key(|&(node_id, _, _)| node_id);
            encoded_spaces.push(super::binary::CachedVectorSpace {
                model: model.clone(),
                dims: *dims,
                next_node: space.next_node,
                documents: docs,
                snapshot: space.index.export_snapshot(),
            });
        }

        let cache = super::binary::CachedMemoryIndexes {
            hnsw_m: self.runtime.config.hnsw_m,
            ef_construction: self.runtime.config.ef_construction,
            ef_search: self.runtime.config.ef_search,
            spaces: encoded_spaces,
        };
        let bytes = super::binary::encode_cached_memory_indexes(&cache)?;
        Ok(Some(bytes))
    }

    pub(crate) fn mark_index_cache_synced(&mut self) {
        self.runtime.cache_synced = self.runtime.dirty.is_empty();
    }

    /// Restore cached HNSW vector topologies and rehydrate live node vectors from loaded entries.
    ///
    /// Returns `Ok(false)` when configuration changed and a rebuild is required. Any stale or
    /// modified document is selectively left dirty so only changed entries are re-indexed.
    pub(crate) fn import_cached_indexes(&mut self, bytes: &[u8]) -> Result<bool> {
        self.ensure_runtime()?;
        let cache = super::binary::decode_cached_memory_indexes(bytes)?;
        let cfg = &self.runtime.config;
        if cache.hnsw_m != cfg.hnsw_m
            || cache.ef_construction != cfg.ef_construction
            || cache.ef_search != cfg.ef_search
        {
            return Ok(false);
        }

        self.runtime.indexes.clear();
        self.runtime.locations.clear();

        let mut exact_match = true;
        for cached_space in cache.spaces {
            let key = (cached_space.model.clone(), cached_space.dims);
            let mut index = HnswIndex::import_snapshot(cached_space.snapshot);
            if let Some(ep) = index.entry_point
                && !index.nodes.contains_key(&ep)
            {
                self.runtime.indexes.clear();
                self.runtime.locations.clear();
                return Ok(false);
            }

            let mut documents = HashMap::with_capacity(cached_space.documents.len());
            for (node_id, doc_id, cached_fp) in cached_space.documents {
                let valid = self.entries.get(&doc_id).filter(|entry| {
                    entry.embedding_model == key.0
                        && entry.vector.as_ref().is_some_and(|v| v.len() == key.1)
                        && doc_vector_fingerprint(entry) == cached_fp
                });
                if let (Some(entry), Some(node)) = (valid, index.nodes.get_mut(&node_id)) {
                    let vec = entry
                        .vector
                        .as_deref()
                        .expect("validated vector presence above");
                    node.vector = unit_vector(vec);
                    documents.insert(node_id, doc_id);
                    self.runtime
                        .locations
                        .insert(doc_id, (key.clone(), node_id));
                    self.runtime.dirty.remove(&doc_id);
                } else {
                    index.mark_deleted(node_id);
                    exact_match = false;
                }
            }

            if !documents.is_empty() {
                self.runtime.indexes.insert(
                    key,
                    VectorSpace {
                        index,
                        documents,
                        next_node: cached_space.next_node,
                    },
                );
            }
        }

        // Non-vector entries need no HNSW indexing; remove them from dirty after cache load
        // if they weren't modified, or keep dirty if we only care about vector entries?
        // Actually prepare_indexes skips vector==None cheaply anyway, and clearing non-vector
        // entries when cache loaded makes pending_index_updates == 0 after clean reopen!
        let entries = &self.entries;
        self.runtime
            .dirty
            .retain(|id| entries.get(id).is_some_and(|e| e.vector.is_some()));

        self.runtime.cache_synced = exact_match && self.runtime.dirty.is_empty();
        Ok(true)
    }
    /// Search bounded channel candidates using indexed lexical/vector retrieval.
    pub fn search_indexed(
        &mut self,
        search: &MemorySearch,
        now: u64,
    ) -> Result<MemorySearchResponse> {
        search.validate(&self.runtime.config)?;
        self.prepare_indexes()?;
        let allowed = self.runtime.allowed(search);
        let eligible = |id: u64| {
            self.entries
                .get(&id)
                .is_some_and(|entry| entry.expires_at.is_none_or(|expiry| now < expiry))
        };
        let lexical = search
            .query
            .as_deref()
            .map(|text| {
                self.bm25
                    .search_where(text, search.candidate_limit, allowed.as_deref(), eligible)
            })
            .unwrap_or_default();
        let mut vector_hits = Vec::new();
        let mut vector_indexes_used = 0;
        if let Some(vector) = &search.embedding {
            let normalized_query = unit_vector(vector);
            if let Some(model) = &search.embedding_model
                && let Some(((_, dimension), _)) = self
                    .runtime
                    .spaces
                    .iter()
                    .find(|((m, _), _)| m.as_ref() == Some(model))
                && *dimension != vector.len()
            {
                return Err(Error::DimensionMismatch(*dimension, vector.len()));
            }
            let key = (search.embedding_model.clone(), vector.len());
            if let Some(space) = self.runtime.indexes.get(&key) {
                vector_indexes_used = 1;
                if search.exact {
                    for &id in space.documents.values() {
                        if allowed.as_ref().is_some_and(|ids| !ids.contains(&id)) || !eligible(id) {
                            continue;
                        }
                        let score = cosine_similarity(
                            vector,
                            self.entries[&id].vector.as_ref().expect("indexed vector"),
                        );
                        if score > 0.0 {
                            vector_hits.push((id, score));
                        }
                    }
                    vector_hits.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
                    vector_hits.truncate(search.candidate_limit);
                } else {
                    // Map only small selective scopes to index IDs. Large scopes
                    // use the predicate during candidate search without an O(N) map.
                    let node_filter: Option<HashSet<u64>> = allowed
                        .as_ref()
                        .filter(|ids| {
                            ids.len() <= space.index.ef_search.max(search.candidate_limit)
                        })
                        .map(|ids| {
                            ids.iter()
                                .filter_map(|id| self.runtime.locations.get(id))
                                .filter(|(s, _)| *s == key)
                                .map(|(_, node)| *node)
                                .collect()
                        });
                    for (node, distance) in space.index.search_knn_where(
                        &normalized_query,
                        search.candidate_limit,
                        DistanceMetric::Cosine,
                        (node_filter.as_ref(), allowed.is_some()),
                        |node| {
                            space.documents.get(&node).is_some_and(|id| {
                                eligible(*id) && allowed.as_ref().is_none_or(|ids| ids.contains(id))
                            })
                        },
                        self.runtime.config.max_candidates,
                    )? {
                        if let Some(id) = space.documents.get(&node) {
                            let score = (1.0 - distance).clamp(0.0, 1.0);
                            if score > 0.0 {
                                vector_hits.push((*id, score));
                            }
                        }
                    }
                }
            }
        }
        let lexical_scores: HashMap<_, _> = lexical.iter().copied().collect();
        let semantic_scores: HashMap<_, _> = vector_hits.iter().copied().collect();
        let lexical_ids: Vec<_> = lexical.iter().map(|(id, _)| *id).collect();
        let vector_ids: Vec<_> = vector_hits.iter().map(|(id, _)| *id).collect();
        let channel_weight = (if search.query.is_some() {
            search.lexical_weight
        } else {
            0.0
        }) + (if search.embedding.is_some() {
            search.vector_weight
        } else {
            0.0
        });
        let fused: HashMap<_, _> = reciprocal_rank_fusion(
            &[
                (&lexical_ids, search.lexical_weight),
                (&vector_ids, search.vector_weight),
            ],
            search.rrf_k,
            search.candidate_limit.saturating_mul(2),
        )
        .into_iter()
        .collect();
        let total_weight = search.vector_weight
            + search.lexical_weight
            + search.recency_weight
            + search.importance_weight;
        let mut ranked = Vec::with_capacity(fused.len());
        for (&id, &rrf) in &fused {
            let Some(entry) = self.entries.get(&id) else {
                continue;
            };
            let lexical_score = lexical_scores.get(&id).copied().unwrap_or(0.0);
            let semantic_score = match (&search.embedding, &entry.vector) {
                (Some(query), Some(vector))
                    if entry.embedding_model == search.embedding_model
                        && query.len() == vector.len() =>
                {
                    cosine_similarity(query, vector).max(0.0)
                }
                _ => 0.0,
            };
            let dt = now.saturating_sub(entry.updated_at.max(entry.timestamp)) as f32;
            let recency_score = if search.half_life_seconds == 0 {
                1.0
            } else {
                (-2.0f32.ln() * dt / search.half_life_seconds as f32).exp()
            };
            let relevance = match search.fusion {
                MemoryFusion::Rrf => rrf * (search.rrf_k + 1.0) / channel_weight.max(f32::EPSILON),
                MemoryFusion::Weighted => {
                    (search.vector_weight * semantic_score
                        + search.lexical_weight * lexical_score / (1.0 + lexical_score))
                        / channel_weight.max(f32::EPSILON)
                }
            };
            let score = ((search.vector_weight + search.lexical_weight) * relevance
                + search.recency_weight * recency_score
                + search.importance_weight * entry.importance)
                / total_weight;
            if score >= search.min_score {
                ranked.push((
                    id,
                    score.clamp(0.0, 1.0),
                    semantic_score,
                    lexical_score,
                    recency_score,
                ));
            }
        }
        let scored_candidates = fused.len();
        ranked.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
        ranked.truncate(search.limit);
        let results = ranked
            .into_iter()
            .map(
                |(id, combined_score, semantic_score, lexical_score, recency_score)| {
                    let entry = self.entries.get_mut(&id).expect("ranked source");
                    entry.last_accessed = now;
                    entry.access_count = entry.access_count.saturating_add(1);
                    MemoryRecallResult {
                        entry: entry.clone(),
                        combined_score,
                        semantic_score,
                        lexical_score,
                        recency_score,
                        is_associative: false,
                    }
                },
            )
            .collect();
        Ok(MemorySearchResponse {
            results,
            diagnostics: MemorySearchDiagnostics {
                total_documents: self.entries.len(),
                candidate_limit: search.candidate_limit,
                lexical_candidates: lexical.len(),
                vector_candidates: semantic_scores.len(),
                scored_candidates,
                exact_vector_search: search.exact,
                vector_indexes_used,
                fusion: search.fusion,
            },
        })
    }
}