Skip to main content

mnemo_engine/
error.rs

1//! Error types for Mnemo.
2
3use thiserror::Error;
4
5/// All errors the Mnemo engine can produce.
6#[derive(Error, Debug)]
7pub enum MnemoError {
8    /// An underlying I/O failure.
9    #[error("io error: {0}")]
10    Io(#[from] std::io::Error),
11
12    /// The file does not begin with the Mnemo magic bytes.
13    #[error("bad magic bytes — file is not a .mnemo database")]
14    BadMagic,
15
16    /// The on-disk format version is newer than this build understands.
17    #[error(
18        "unsupported .mnemo format version {0}: this build opens v4 to v9; \
19         a newer file needs a newer mnemo-engine"
20    )]
21    UnsupportedVersion(u16),
22
23    /// The header page failed its CRC check — a torn page-0 write or
24    /// corruption. [`crate::Mnemo::open`] tries to repair this from the WAL.
25    #[error("header checksum mismatch — page 0 is torn or corrupt")]
26    HeaderChecksum,
27
28    /// Returned when the supplied passphrase fails to unwrap the data key.
29    /// The failure is an authenticated-decryption failure, so it is
30    /// indistinguishable from a tampered key blob — both are rejected cleanly.
31    #[error("wrong passphrase, or the key material has been tampered with")]
32    WrongPassphrase,
33
34    /// AEAD authentication failed for a page: corruption or tampering.
35    #[error("page {0} failed authentication — the file is corrupt or tampered")]
36    PageAuthFailed(u64),
37
38    /// The v7 header seal failed authentication — at least one mutable
39    /// header field has been rewritten without the DEK. Open refuses to
40    /// proceed so a silent rollback or pointer-rewrite attack can't
41    /// surface stale data.
42    #[error("header seal authentication failed — mutable fields tampered with")]
43    HeaderTampered,
44
45    /// A low-level cryptographic operation failed.
46    #[error("cryptographic operation failed: {0}")]
47    Crypto(String),
48
49    /// Argon2id key derivation failed.
50    #[error("key derivation failed: {0}")]
51    Kdf(String),
52
53    /// A record failed to (de)serialize.
54    #[error("serialization error: {0}")]
55    Serialize(String),
56
57    /// No memory exists with the requested ID.
58    #[error("memory '{0}' not found")]
59    NotFound(String),
60
61    /// A vector did not match the database's configured dimensionality.
62    #[error("vector dimension mismatch: database expects {expected}, got {got}")]
63    DimensionMismatch {
64        /// Dimensionality the database was created with.
65        expected: usize,
66        /// Dimensionality of the offending vector.
67        got: usize,
68    },
69
70    /// A caller-supplied argument was invalid.
71    #[error("invalid argument: {0}")]
72    Invalid(String),
73
74    /// Another process (or another handle in this process) already holds a
75    /// conflicting OS file lock on the target `.mnemo` file. Write handles
76    /// take an exclusive lock; read-only handles take a shared lock. Two
77    /// writers or a writer + reader will collide.
78    #[error("file already locked by another handle: {path}")]
79    Locked {
80        /// The path whose lock was requested and refused.
81        path: std::path::PathBuf,
82    },
83
84    /// A mutation was attempted on a handle opened via
85    /// [`crate::Mnemo::open_read_only`]. Reopen read-write to mutate.
86    #[error("operation requires a read-write handle (this one is read-only)")]
87    ReadOnly,
88
89    /// A read-only open was requested but the file has pending on-disk work
90    /// that requires a write handle to complete — a committed-but-unchecked
91    /// WAL transaction, or a format-version migration older than the current
92    /// `VERSION`. Open read-write once, close cleanly, then reopen read-only.
93    ///
94    /// On a file older than v9 (which no build opens read-write since the
95    /// v8 sunset) the reason itself says to run `mnemo compact`, which
96    /// completes the work and converts the file, and the generic advice is
97    /// left off.
98    #[error("read-only open blocked: {reason}{}", needs_write_open_hint(reason))]
99    NeedsWriteOpen {
100        /// Human-readable reason (e.g. `"pending WAL recovery"`).
101        reason: &'static str,
102    },
103
104    /// The v8 sunset (v0.13): the file's format is older than v9, so it
105    /// can't be opened read-write. A v8 file still opens read-only
106    /// ([`crate::Mnemo::open_read_only`]); `mnemo compact` (or
107    /// [`crate::Mnemo::compact_file`]) converts any v4–v8 file to v9 and
108    /// keeps every live memory.
109    #[error(
110        "this file is format v{version}, which this build {}; run `mnemo compact <file>` \
111         to convert it to v9 (every live memory is kept)",
112        if *version == 8 { "opens read-only" } else { "no longer opens" }
113    )]
114    FormatTooOld {
115        /// The file's on-disk format version.
116        version: u16,
117    },
118
119    /// EMBED-ID-1: the embedder passed to [`crate::Mnemo::set_embedder`]
120    /// isn't the one this file's vectors came from. The file records the
121    /// identity of the first embedder attached to it; a different name,
122    /// width or `normalize` flag is refused, because mixing two models'
123    /// vectors in one file silently breaks recall. Use the original
124    /// embedder, or create a new store for the new model.
125    #[error(
126        "embedder identity mismatch: this file's vectors come from embedder \
127         (name={:?}, dimensions={}, normalize={}), but the embedder given is \
128         (name={:?}, dimensions={}, normalize={}). Open the file with its \
129         original embedder, or create a new store for the new model.",
130        stored.name, stored.dimensions, stored.normalize,
131        given.name, given.dimensions, given.normalize
132    )]
133    EmbedderMismatch {
134        /// The identity the file records.
135        stored: crate::embed::EmbedderIdentity,
136        /// The identity of the embedder that was passed.
137        given: crate::embed::EmbedderIdentity,
138    },
139}
140
141/// Convenience result alias used throughout the crate.
142pub type Result<T> = std::result::Result<T, MnemoError>;
143
144/// The advice after a [`MnemoError::NeedsWriteOpen`] reason. A reason that
145/// names its own fix (`mnemo compact`, for a pre-v9 file) needs no other.
146pub(crate) fn needs_write_open_hint(reason: &str) -> &'static str {
147    if reason.contains("mnemo compact") {
148        ""
149    } else {
150        " — open read-write once to fix"
151    }
152}