iqdb-persist 0.2.0

Atomic snapshot persistence with versioned headers and CRC32 integrity for iQDB indexes - part of the iQDB family.
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
//! [`PersistedIndex`] — the snapshot lifecycle wrapper.
//!
//! Wraps an `I: Index + Persistable` with the framing (file header,
//! CRC32, atomic write) the [`crate::Persistable`] impl does not write
//! itself.

use std::io::Cursor;

use iqdb_index::Index;

use crate::Persistable;
use crate::checksum;
use crate::config::{Compression, PersistConfig};
use crate::error::{PersistError, Result};
use crate::format::{self, CURRENT_VERSION, FileHeader, MAGIC};
use crate::storage::{StdFsStorage, Storage};

/// A snapshot-persistent wrapper around an in-memory index.
///
/// Borrow the wrapped index with [`index`](PersistedIndex::index) /
/// [`index_mut`](PersistedIndex::index_mut) for queries and mutations;
/// call [`save`](PersistedIndex::save) to write the current state to
/// disk; call [`PersistedIndex::load`] later to recover it.
///
/// # Examples
///
/// ```no_run
/// # use iqdb_persist::{PersistConfig, PersistedIndex, Persistable};
/// # use iqdb_index::Index;
/// # fn demo<I: Index + Persistable>(inner: I) -> iqdb_persist::Result<()> {
/// let cfg = PersistConfig::new("snapshot.iqdb");
/// let wrapped = PersistedIndex::open_with(inner, cfg.clone())?;
/// wrapped.save()?;
///
/// // Later:
/// let restored: PersistedIndex<I> = PersistedIndex::load(cfg)?;
/// let _idx = restored.index();
/// # Ok(())
/// # }
/// ```
pub struct PersistedIndex<I: Index + Persistable> {
    inner: I,
    config: PersistConfig,
    storage: Box<dyn Storage>,
}

// `Box<dyn Storage>` is not `Debug`, so we cannot `#[derive(Debug)]`.
// A manual impl that delegates to `I: Debug` is enough to let
// `Result<PersistedIndex<I>, _>::unwrap_err` work in tests, without
// requiring the trait to be `Debug` (which is an internal substrate).
impl<I: Index + Persistable + core::fmt::Debug> core::fmt::Debug for PersistedIndex<I> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("PersistedIndex")
            .field("inner", &self.inner)
            .field("config", &self.config)
            .field("storage", &"<dyn Storage>")
            .finish()
    }
}

impl<I: Index + Persistable> PersistedIndex<I> {
    /// Wrap an already-constructed `inner` for later snapshot saves.
    ///
    /// Performs no disk I/O at construction time.
    ///
    /// # Errors
    ///
    /// Returns [`PersistError::Unsupported`] if `config` requests a
    /// feature this build does not implement
    /// (`wal_enabled = true` or any non-`None` compression in v0.2).
    pub fn open_with(inner: I, config: PersistConfig) -> Result<Self> {
        validate_config(&config)?;
        Ok(Self {
            inner,
            config,
            storage: Box::new(StdFsStorage),
        })
    }

    /// Read `config.path` from disk and reconstruct the wrapped index.
    ///
    /// # Errors
    ///
    /// - [`PersistError::Io`] if the file cannot be read.
    /// - [`PersistError::BadMagic`] / [`PersistError::UnsupportedVersion`]
    ///   / [`PersistError::TruncatedHeader`] / [`PersistError::InvalidMetric`]
    ///   for header-level corruption.
    /// - [`PersistError::InvalidIndexType`] if `header.index_type` does
    ///   not equal `I::INDEX_TYPE` — asking for
    ///   `PersistedIndex::<FlatIndex>::load` on an HNSW file fails here.
    /// - [`PersistError::ChecksumMismatch`] if the payload CRC32 does
    ///   not match the header.
    /// - [`PersistError::InvalidPayload`] if the impl-reconstructed
    ///   index's `dim` / `metric` / `len` disagrees with the header.
    /// - [`PersistError::IndexBuild`] if the
    ///   [`Persistable::load_from`] impl returned a downstream
    ///   [`iqdb_types::IqdbError`].
    /// - [`PersistError::Unsupported`] if `config` requests an
    ///   unsupported feature (see [`open_with`](Self::open_with)).
    pub fn load(config: PersistConfig) -> Result<Self> {
        validate_config(&config)?;
        Self::load_with_storage(config, Box::new(StdFsStorage))
    }

    /// Build a `PersistedIndex` against a non-default [`Storage`]
    /// substrate. Test seam — gated to `cfg(test)` so it does not
    /// appear in the v0.2 public surface.
    #[cfg(test)]
    pub(crate) fn open_with_storage(
        inner: I,
        config: PersistConfig,
        storage: Box<dyn Storage>,
    ) -> Result<Self> {
        validate_config(&config)?;
        Ok(Self {
            inner,
            config,
            storage,
        })
    }

    /// `load`, but reading through `storage`. Test seam.
    pub(crate) fn load_with_storage(
        config: PersistConfig,
        storage: Box<dyn Storage>,
    ) -> Result<Self> {
        let bytes = storage.read_all(&config.path)?;
        let mut cursor = Cursor::new(&bytes[..]);
        let header = format::read_header(&mut cursor)?;

        let header_end =
            usize::try_from(cursor.position()).map_err(|_| PersistError::InvalidPayload {
                reason: "header position does not fit in usize",
            })?;
        if header_end > bytes.len() {
            return Err(PersistError::TruncatedHeader {
                needed: header_end,
                found: bytes.len(),
            });
        }

        // Guard #1 cross-check: caller's I must match the file's tag.
        if header.index_type != I::INDEX_TYPE {
            return Err(PersistError::InvalidIndexType {
                found: header.index_type,
                expected: I::INDEX_TYPE,
            });
        }

        let payload = &bytes[header_end..];
        checksum::verify(payload, header.crc32)?;

        let mut payload_cursor = Cursor::new(payload);
        let inner = <I as Persistable>::load_from(&mut payload_cursor)?;

        if inner.dim() != header.dim {
            return Err(PersistError::InvalidPayload {
                reason: "header dim disagrees with payload-reconstructed index",
            });
        }
        if inner.metric() != header.metric {
            return Err(PersistError::InvalidPayload {
                reason: "header metric disagrees with payload-reconstructed index",
            });
        }
        if inner.len() != header.n_vectors {
            return Err(PersistError::InvalidPayload {
                reason: "header n_vectors disagrees with payload-reconstructed index",
            });
        }

        Ok(Self {
            inner,
            config,
            storage,
        })
    }

    /// Borrow the wrapped index for queries.
    #[must_use]
    pub fn index(&self) -> &I {
        &self.inner
    }

    /// Borrow the wrapped index mutably for inserts / deletes / flush.
    pub fn index_mut(&mut self) -> &mut I {
        &mut self.inner
    }

    /// The [`PersistConfig`] this wrapper was constructed with.
    #[must_use]
    pub fn config(&self) -> &PersistConfig {
        &self.config
    }

    /// Write the current state of the wrapped index to
    /// `self.config.path` atomically.
    ///
    /// # Errors
    ///
    /// - [`PersistError::Io`] if the temp write, rename, or directory
    ///   fsync fails.
    /// - Any error returned by [`Persistable::save_to`].
    /// - [`PersistError::InvalidPayload`] if a `usize` field of the
    ///   index does not fit in `u64`.
    #[tracing::instrument(level = "debug", skip_all, fields(
        path = %self.config.path.display(),
        index_type = I::INDEX_TYPE,
        n = self.inner.len(),
    ))]
    pub fn save(&self) -> Result<()> {
        let mut payload_buf: Vec<u8> = Vec::new();
        <I as Persistable>::save_to(&self.inner, &mut payload_buf)?;

        let crc32 = checksum::compute(&payload_buf);
        let header = FileHeader {
            magic: MAGIC,
            version: CURRENT_VERSION,
            index_type: I::INDEX_TYPE.to_string(),
            dim: self.inner.dim(),
            metric: self.inner.metric(),
            n_vectors: self.inner.len(),
            crc32,
        };

        let mut full: Vec<u8> = Vec::with_capacity(payload_buf.len() + 64);
        format::write_header(&mut full, &header)?;
        full.extend_from_slice(&payload_buf);

        self.storage
            .write_atomic(&self.config.path, &full, self.config.fsync_policy)
    }
}

fn validate_config(config: &PersistConfig) -> Result<()> {
    if config.wal_enabled {
        return Err(PersistError::Unsupported {
            feature: "wal_enabled",
            available_in: "v0.3",
        });
    }
    if !matches!(config.compression, Compression::None) {
        return Err(PersistError::Unsupported {
            feature: "compression",
            available_in: "v0.4",
        });
    }
    Ok(())
}

// ----------------------------------------------------------------------
// Unit tests — exercise the framing logic against a tiny in-crate
// `MockIndex` so iqdb-persist never dev-deps iqdb-flat. Atomicity uses
// a FailingStorage substrate (the pub(crate) test seam exposed above).
// ----------------------------------------------------------------------
#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used)]

    use std::io::{Read, Write};
    use std::sync::Arc;

    use iqdb_index::{Index, IndexCore, IndexStats};
    use iqdb_types::{DistanceMetric, Hit, Metadata, Result as IqdbResult, SearchParams, VectorId};

    use super::*;
    use crate::format::{metric_to_tag, tag_to_metric};

    // -- mock index ------------------------------------------------------

    #[derive(Debug)]
    struct MockIndex {
        dim: usize,
        metric: DistanceMetric,
        n: usize,
    }

    impl IndexCore for MockIndex {
        fn insert(&mut self, _: VectorId, _: Arc<[f32]>, _: Option<Metadata>) -> IqdbResult<()> {
            self.n += 1;
            Ok(())
        }
        fn delete(&mut self, _: &VectorId) -> IqdbResult<()> {
            Ok(())
        }
        fn search(&self, _: &[f32], _: &SearchParams) -> IqdbResult<Vec<Hit>> {
            Ok(Vec::new())
        }
        fn len(&self) -> usize {
            self.n
        }
        fn dim(&self) -> usize {
            self.dim
        }
        fn metric(&self) -> DistanceMetric {
            self.metric
        }
        fn flush(&mut self) -> IqdbResult<()> {
            Ok(())
        }
        fn stats(&self) -> IndexStats {
            IndexStats {
                n_vectors: self.n,
                index_type: "mock",
                ..IndexStats::default()
            }
        }
    }

    impl Index for MockIndex {
        type Config = ();
        fn new(dim: usize, metric: DistanceMetric, _: ()) -> IqdbResult<Self> {
            Ok(Self { dim, metric, n: 0 })
        }
    }

    impl Persistable for MockIndex {
        const INDEX_TYPE: &'static str = "mock";

        fn save_to(&self, writer: &mut dyn Write) -> Result<()> {
            // Self-describing prefix: metric_tag u8, dim u64 LE, n u64 LE.
            writer
                .write_all(&[metric_to_tag(self.metric)?])
                .map_err(io_err)?;
            let dim_u64 = u64::try_from(self.dim).map_err(|_| PersistError::InvalidPayload {
                reason: "mock dim does not fit in u64",
            })?;
            writer.write_all(&dim_u64.to_le_bytes()).map_err(io_err)?;
            let n_u64 = u64::try_from(self.n).map_err(|_| PersistError::InvalidPayload {
                reason: "mock n does not fit in u64",
            })?;
            writer.write_all(&n_u64.to_le_bytes()).map_err(io_err)?;
            Ok(())
        }

        fn load_from(reader: &mut dyn Read) -> Result<Self> {
            let mut tag = [0u8; 1];
            reader.read_exact(&mut tag).map_err(io_err)?;
            let metric = tag_to_metric(tag[0])?;
            let mut buf = [0u8; 8];
            reader.read_exact(&mut buf).map_err(io_err)?;
            let dim = usize::try_from(u64::from_le_bytes(buf)).map_err(|_| {
                PersistError::InvalidPayload {
                    reason: "mock dim does not fit in usize",
                }
            })?;
            reader.read_exact(&mut buf).map_err(io_err)?;
            let n = usize::try_from(u64::from_le_bytes(buf)).map_err(|_| {
                PersistError::InvalidPayload {
                    reason: "mock n does not fit in usize",
                }
            })?;
            Ok(Self { dim, metric, n })
        }
    }

    fn io_err(source: std::io::Error) -> PersistError {
        PersistError::Io {
            path: std::path::PathBuf::new(),
            source,
        }
    }

    // -- failing storage seam -------------------------------------------

    /// A `Storage` that succeeds on read but always fails the rename
    /// leg of `write_atomic`, while doing the preceding temp-write +
    /// fsync correctly. Used to prove atomicity: the target on disk
    /// must be left untouched.
    struct FailingRenameStorage;

    impl Storage for FailingRenameStorage {
        fn read_all(&self, path: &std::path::Path) -> Result<Vec<u8>> {
            StdFsStorage.read_all(path)
        }

        fn write_atomic(
            &self,
            target: &std::path::Path,
            payload: &[u8],
            _policy: crate::config::FsyncPolicy,
        ) -> Result<()> {
            use std::fs::OpenOptions;

            let target_dir = target.parent().unwrap_or_else(|| std::path::Path::new("."));
            let file_name = target.file_name().unwrap();
            let temp_path = target_dir.join(format!(
                "{}.tmp.failtest.{}",
                file_name.to_string_lossy(),
                std::process::id(),
            ));
            {
                let mut f = OpenOptions::new()
                    .create_new(true)
                    .write(true)
                    .open(&temp_path)
                    .map_err(|source| PersistError::Io {
                        path: temp_path.clone(),
                        source,
                    })?;
                f.write_all(payload).map_err(|source| PersistError::Io {
                    path: temp_path.clone(),
                    source,
                })?;
                f.sync_all().map_err(|source| PersistError::Io {
                    path: temp_path.clone(),
                    source,
                })?;
            }
            let _cleanup = std::fs::remove_file(&temp_path);
            Err(PersistError::Io {
                path: target.to_path_buf(),
                source: std::io::Error::other("simulated rename failure"),
            })
        }
    }

    // -- the atomicity test ---------------------------------------------

    #[test]
    fn save_failure_leaves_original_file_intact() {
        let dir = tempfile::tempdir().unwrap();
        let snapshot = dir.path().join("idx.iqdb");

        // 1) Save a "good" snapshot with the real storage.
        let inner = MockIndex {
            dim: 16,
            metric: DistanceMetric::Cosine,
            n: 7,
        };
        let cfg = PersistConfig::new(&snapshot);
        let wrap = PersistedIndex::open_with(inner, cfg.clone()).unwrap();
        wrap.save().unwrap();

        let good_bytes = std::fs::read(&snapshot).unwrap();
        assert!(!good_bytes.is_empty(), "good save produced empty file");

        // 2) Try to save a *different* index using the failing-rename
        //    storage. The save MUST error.
        let other = MockIndex {
            dim: 16,
            metric: DistanceMetric::Cosine,
            n: 99,
        };
        let wrap2 =
            PersistedIndex::open_with_storage(other, cfg.clone(), Box::new(FailingRenameStorage))
                .unwrap();
        let err = wrap2.save().unwrap_err();
        assert!(matches!(err, PersistError::Io { .. }));

        // 3) The on-disk bytes MUST equal the original good save.
        let after_bytes = std::fs::read(&snapshot).unwrap();
        assert_eq!(
            after_bytes, good_bytes,
            "rename failure corrupted the snapshot"
        );

        // 4) The original must still load and report n = 7, not 99.
        let restored: PersistedIndex<MockIndex> = PersistedIndex::load(cfg).unwrap();
        assert_eq!(restored.index().len(), 7);
    }

    #[test]
    fn validate_config_rejects_wal_and_compression() {
        let dir = tempfile::tempdir().unwrap();
        let snapshot = dir.path().join("idx.iqdb");

        let mut cfg = PersistConfig::new(&snapshot);
        cfg.wal_enabled = true;
        let inner = MockIndex {
            dim: 4,
            metric: DistanceMetric::Euclidean,
            n: 0,
        };
        let err = PersistedIndex::open_with(inner, cfg).unwrap_err();
        assert!(matches!(
            err,
            PersistError::Unsupported {
                feature: "wal_enabled",
                ..
            }
        ));

        let mut cfg2 = PersistConfig::new(&snapshot);
        cfg2.compression = Compression::Lz4;
        let inner2 = MockIndex {
            dim: 4,
            metric: DistanceMetric::Euclidean,
            n: 0,
        };
        let err = PersistedIndex::open_with(inner2, cfg2).unwrap_err();
        assert!(matches!(
            err,
            PersistError::Unsupported {
                feature: "compression",
                ..
            }
        ));
    }

    #[test]
    fn crc_mismatch_after_byte_flip_in_payload() {
        let dir = tempfile::tempdir().unwrap();
        let snapshot = dir.path().join("idx.iqdb");

        // 1) Save a good snapshot.
        let inner = MockIndex {
            dim: 8,
            metric: DistanceMetric::Cosine,
            n: 11,
        };
        let cfg = PersistConfig::new(&snapshot);
        PersistedIndex::open_with(inner, cfg.clone())
            .unwrap()
            .save()
            .unwrap();

        // 2) Read the bytes, flip a bit in the LAST byte (well inside
        //    the payload region — the mock payload is 17 bytes long,
        //    and the header is much larger than that).
        let mut bytes = std::fs::read(&snapshot).unwrap();
        let last = bytes.len() - 1;
        bytes[last] ^= 0x01;
        std::fs::write(&snapshot, &bytes).unwrap();

        // 3) Load MUST surface ChecksumMismatch — not a panic, not a
        //    silently-wrong load.
        let err: PersistError = PersistedIndex::<MockIndex>::load(cfg).unwrap_err();
        assert!(
            matches!(err, PersistError::ChecksumMismatch { .. }),
            "expected ChecksumMismatch, got {err:?}",
        );
    }

    #[test]
    fn invalid_index_type_on_wrong_i_surfaces_loudly() {
        // Save a file with INDEX_TYPE = "mock", then try to load it
        // as if its tag were "other".
        let dir = tempfile::tempdir().unwrap();
        let snapshot = dir.path().join("idx.iqdb");
        let cfg = PersistConfig::new(&snapshot);

        let inner = MockIndex {
            dim: 4,
            metric: DistanceMetric::Euclidean,
            n: 3,
        };
        PersistedIndex::open_with(inner, cfg.clone())
            .unwrap()
            .save()
            .unwrap();

        // A second mock with a different INDEX_TYPE.
        #[derive(Debug)]
        struct OtherMock;
        impl IndexCore for OtherMock {
            fn insert(
                &mut self,
                _: VectorId,
                _: Arc<[f32]>,
                _: Option<Metadata>,
            ) -> IqdbResult<()> {
                Ok(())
            }
            fn delete(&mut self, _: &VectorId) -> IqdbResult<()> {
                Ok(())
            }
            fn search(&self, _: &[f32], _: &SearchParams) -> IqdbResult<Vec<Hit>> {
                Ok(Vec::new())
            }
            fn len(&self) -> usize {
                0
            }
            fn dim(&self) -> usize {
                4
            }
            fn metric(&self) -> DistanceMetric {
                DistanceMetric::Euclidean
            }
            fn flush(&mut self) -> IqdbResult<()> {
                Ok(())
            }
            fn stats(&self) -> IndexStats {
                IndexStats {
                    index_type: "other",
                    ..IndexStats::default()
                }
            }
        }
        impl Index for OtherMock {
            type Config = ();
            fn new(_: usize, _: DistanceMetric, _: ()) -> IqdbResult<Self> {
                Ok(Self)
            }
        }
        impl Persistable for OtherMock {
            const INDEX_TYPE: &'static str = "other";
            fn save_to(&self, _w: &mut dyn Write) -> Result<()> {
                Ok(())
            }
            fn load_from(_r: &mut dyn Read) -> Result<Self> {
                Ok(Self)
            }
        }

        let err = PersistedIndex::<OtherMock>::load(cfg).unwrap_err();
        assert!(
            matches!(
                err,
                PersistError::InvalidIndexType {
                    expected: "other",
                    ..
                }
            ),
            "expected InvalidIndexType, got {err:?}",
        );
    }

    #[test]
    fn roundtrip_through_storage_recovers_state() {
        let dir = tempfile::tempdir().unwrap();
        let snapshot = dir.path().join("idx.iqdb");
        let cfg = PersistConfig::new(&snapshot);

        let inner = MockIndex {
            dim: 32,
            metric: DistanceMetric::Manhattan,
            n: 42,
        };
        let wrap = PersistedIndex::open_with(inner, cfg.clone()).unwrap();
        wrap.save().unwrap();

        let restored: PersistedIndex<MockIndex> = PersistedIndex::load(cfg).unwrap();
        assert_eq!(restored.index().dim(), 32);
        assert_eq!(restored.index().metric(), DistanceMetric::Manhattan);
        assert_eq!(restored.index().len(), 42);
    }
}