mnemo_engine/error.rs
1//! Error types for Mnemo.
2
3use thiserror::Error;
4
5/// All errors the Mnemo engine can produce.
6///
7/// `#[non_exhaustive]` (v0.14): new variants can arrive in a minor release,
8/// so a `match` needs a catch-all arm.
9#[derive(Error, Debug)]
10#[non_exhaustive]
11pub enum MnemoError {
12 /// An underlying I/O failure.
13 #[error("io error: {0}")]
14 Io(#[from] std::io::Error),
15
16 /// The file does not begin with the Mnemo magic bytes.
17 #[error("bad magic bytes — file is not a .mnemo database")]
18 BadMagic,
19
20 /// The on-disk format version is newer than this build understands.
21 #[error(
22 "unsupported .mnemo format version {0}: this build opens v4 to v9; \
23 a newer file needs a newer mnemo-engine"
24 )]
25 UnsupportedVersion(u16),
26
27 /// The header page failed its CRC check — a torn page-0 write or
28 /// corruption. [`crate::Mnemo::open`] tries to repair this from the WAL.
29 #[error("header checksum mismatch — page 0 is torn or corrupt")]
30 HeaderChecksum,
31
32 /// Returned when the supplied passphrase fails to unwrap the data key.
33 /// The failure is an authenticated-decryption failure, so it is
34 /// indistinguishable from a tampered key blob — both are rejected cleanly.
35 #[error("wrong passphrase, or the key material has been tampered with")]
36 WrongPassphrase,
37
38 /// AEAD authentication failed for a page: corruption or tampering.
39 #[error("page {0} failed authentication — the file is corrupt or tampered")]
40 PageAuthFailed(u64),
41
42 /// The v7 header seal failed authentication — at least one mutable
43 /// header field has been rewritten without the DEK. Open refuses to
44 /// proceed so a silent rollback or pointer-rewrite attack can't
45 /// surface stale data.
46 #[error("header seal authentication failed — mutable fields tampered with")]
47 HeaderTampered,
48
49 /// A low-level cryptographic operation failed.
50 #[error("cryptographic operation failed: {0}")]
51 Crypto(String),
52
53 /// Argon2id key derivation failed.
54 #[error("key derivation failed: {0}")]
55 Kdf(String),
56
57 /// A record failed to (de)serialize.
58 #[error("serialization error: {0}")]
59 Serialize(String),
60
61 /// No memory exists with the requested ID.
62 #[error("memory '{0}' not found")]
63 NotFound(String),
64
65 /// A vector did not match the database's configured dimensionality.
66 #[error("vector dimension mismatch: database expects {expected}, got {got}")]
67 DimensionMismatch {
68 /// Dimensionality the database was created with.
69 expected: usize,
70 /// Dimensionality of the offending vector.
71 got: usize,
72 },
73
74 /// A caller-supplied argument was invalid.
75 #[error("invalid argument: {0}")]
76 Invalid(String),
77
78 /// Another process (or another handle in this process) already holds a
79 /// conflicting OS file lock on the target `.mnemo` file. Write handles
80 /// take an exclusive lock; read-only handles take a shared lock. Two
81 /// writers or a writer + reader will collide.
82 ///
83 /// A shared-mode call that waits out its deadline also returns this, with
84 /// `holder` naming the long operation that holds the file when one said
85 /// so (12.4: "compact since 12:01 (pid 4242, mnemo)").
86 #[error(
87 "file already locked by another handle: {path}{}",
88 holder_suffix(holder)
89 )]
90 #[non_exhaustive]
91 Locked {
92 /// The path whose lock was requested and refused.
93 path: std::path::PathBuf,
94 /// What holds the file, when the holder left a note: a shared-mode
95 /// long operation (compaction, an index build, an import) writes one.
96 holder: Option<String>,
97 },
98
99 /// A shared-mode write failed after its commit point and the handle
100 /// couldn't finish the commit itself, so the write **may have been
101 /// stored**: the next process to open the file finishes it. Don't retry
102 /// the same write blindly; check whether it's there.
103 #[error("the write may have been stored: {0}")]
104 MaybeStored(String),
105
106 /// A shared-mode write committed to a file that something renamed away
107 /// from the handle's path during the commit (an older `mnemo compact`,
108 /// say). The write isn't in the file now at the path.
109 #[error(
110 "the file at {path} was replaced during the write; the write isn't in the file \
111 now at that path"
112 )]
113 ReplacedDuringWrite {
114 /// The path that now names a different file.
115 path: std::path::PathBuf,
116 },
117
118 /// A shared-mode call was cancelled from another thread (an iOS
119 /// background activity's expiry handler, say) while it waited for the
120 /// file's lock. It released every lock it held and changed nothing.
121 #[error("cancelled while waiting for the file's lock; nothing was changed")]
122 Cancelled,
123
124 /// This build or this location can't do what was asked: shared mode on a
125 /// network or synced filesystem (without `allow_network_fs`), or on a
126 /// Windows build made with Rust before 1.85. The message says which.
127 #[error("not supported: {0}")]
128 Unsupported(String),
129
130 /// The file at this handle's path is no longer the file the handle
131 /// opened: something renamed another file over it (a compaction in
132 /// another process, or another program), or the file was moved or
133 /// removed (`missing`). Writing would go to a file nobody finds at the
134 /// path, so the handle refuses, and writes nothing.
135 /// A plain handle: reopen the path to use the file that's there now
136 /// ([`crate::Mnemo::try_close`] hands the handle back). A shared handle
137 /// (`shared`): the rename came between the window's identity check and
138 /// its commit (an older build's compaction renames without its lock);
139 /// calling again is safe, and the next call follows the new file.
140 #[error("{}", replaced_message(path, *shared, *missing))]
141 #[non_exhaustive]
142 Replaced {
143 /// The handle's path, which no longer names the file it opened.
144 path: std::path::PathBuf,
145 /// Raised in a shared-mode write window, where the next call
146 /// follows the new file by itself.
147 shared: bool,
148 /// Nothing is at the path any more: the file was moved or removed,
149 /// rather than another file renamed over it.
150 missing: bool,
151 },
152
153 /// A mutation was attempted on a handle opened via
154 /// [`crate::Mnemo::open_read_only`]. Reopen read-write to mutate.
155 #[error("operation requires a read-write handle (this one is read-only)")]
156 ReadOnly,
157
158 /// A read-only open was requested but the file has pending on-disk work
159 /// that requires a write handle to complete — a committed-but-unchecked
160 /// WAL transaction, or a format-version migration older than the current
161 /// `VERSION`. Open read-write once, close cleanly, then reopen read-only.
162 ///
163 /// On a file older than v9 (which no build opens read-write since the
164 /// v8 sunset) the reason itself says to run `mnemo compact`, which
165 /// completes the work and converts the file, and the generic advice is
166 /// left off.
167 #[error("read-only open blocked: {reason}{}", needs_write_open_hint(reason))]
168 NeedsWriteOpen {
169 /// Human-readable reason (e.g. `"pending WAL recovery"`).
170 reason: &'static str,
171 },
172
173 /// The v8 sunset (v0.13): the file's format is older than v9, so it
174 /// can't be opened read-write. A v8 file still opens read-only
175 /// ([`crate::Mnemo::open_read_only`]); `mnemo compact` (or
176 /// [`crate::Mnemo::compact_file`]) converts any v4–v8 file to v9 and
177 /// keeps every live memory.
178 #[error(
179 "this file is format v{version}, which this build {}; run `mnemo compact <file>` \
180 (with `--key-file <key>` for a raw-key file) to convert it to v9 (every live \
181 memory is kept)",
182 if *version == 8 { "opens read-only" } else { "no longer opens" }
183 )]
184 FormatTooOld {
185 /// The file's on-disk format version.
186 version: u16,
187 },
188
189 /// EMBED-ID-1: the embedder passed to [`crate::Mnemo::set_embedder`]
190 /// isn't the one this file's vectors came from. The file records the
191 /// identity of the first embedder attached to it; a different name,
192 /// width or `normalize` flag is refused, because mixing two models'
193 /// vectors in one file silently breaks recall. Use the original
194 /// embedder, or create a new store for the new model.
195 ///
196 /// Since v0.15 the identity includes the query convention
197 /// ([`crate::EmbedderIdentity::query_convention`]), and `mnemo reembed`
198 /// moves a file to a new embedder.
199 #[error(
200 "embedder identity mismatch: this file's vectors come from embedder {}, \
201 but the embedder given is {}. Open the file with its original embedder, \
202 create a new store for the new model, or move this file to it with \
203 `mnemo reembed`.",
204 stored.describe(),
205 given.describe()
206 )]
207 EmbedderMismatch {
208 /// The identity the file records (boxed since v0.15, which added
209 /// `query_convention`, to keep the error small).
210 stored: Box<crate::embed::EmbedderIdentity>,
211 /// The identity of the embedder that was passed.
212 given: Box<crate::embed::EmbedderIdentity>,
213 },
214}
215
216/// Convenience result alias used throughout the crate.
217pub type Result<T> = std::result::Result<T, MnemoError>;
218
219/// The advice after a [`MnemoError::NeedsWriteOpen`] reason. A reason that
220/// names its own fix (`mnemo compact`, for a pre-v9 file) needs no other.
221pub(crate) fn needs_write_open_hint(reason: &str) -> &'static str {
222 if reason.contains("mnemo compact") {
223 ""
224 } else {
225 " — open read-write once to fix"
226 }
227}
228
229fn holder_suffix(holder: &Option<String>) -> String {
230 match holder {
231 Some(h) => format!(" (held by {h})"),
232 None => String::new(),
233 }
234}
235
236fn replaced_message(path: &std::path::Path, shared: bool, missing: bool) -> String {
237 let path = path.display();
238 if missing {
239 format!(
240 "the file at {path} was moved or removed after this handle opened it, and this \
241 handle's path no longer names it; nothing was written. Move it back, or open it \
242 where it is now"
243 )
244 } else if shared {
245 format!(
246 "the file at {path} was replaced (by an older build's compaction, or by another \
247 program) before this write; nothing was written, and the next call follows the \
248 new file"
249 )
250 } else {
251 format!(
252 "the file at {path} was replaced after this handle opened it (by a compaction, or \
253 by another program); nothing was written. Reopen it"
254 )
255 }
256}