Skip to main content

itzma_core/
error.rs

1//! The error type shared by every module in the crate.
2
3use thiserror::Error;
4
5/// Everything that can go wrong in `itzma-core`.
6///
7/// The enum is `#[non_exhaustive]`, so downstream `match` expressions need a
8/// wildcard arm. New variants can then be added without a breaking change.
9///
10/// Input is validated before any storage call, so the input-shaped variants
11/// ([`InvalidNamespaceId`](Self::InvalidNamespaceId),
12/// [`InvalidSchema`](Self::InvalidSchema),
13/// [`DimensionMismatch`](Self::DimensionMismatch),
14/// [`InvalidVector`](Self::InvalidVector), [`InvalidId`](Self::InvalidId),
15/// [`InvalidQuery`](Self::InvalidQuery), [`EmptyBatch`](Self::EmptyBatch))
16/// never leave a partial write behind.
17#[derive(Debug, Error)]
18#[non_exhaustive]
19pub enum ItzmaError {
20    /// The object store failed. Passed through unchanged, and never retried
21    /// except inside the two contention loops ([`WriteContention`] and
22    /// [`ManifestContention`]).
23    ///
24    /// [`WriteContention`]: Self::WriteContention
25    /// [`ManifestContention`]: Self::ManifestContention
26    #[error("storage error: {0}")]
27    Storage(#[from] object_store::Error),
28
29    /// An object was fetched but its JSON could not be decoded (or, on the
30    /// write side, an entry could not be encoded).
31    #[error("failed to decode {path}: {source}")]
32    Serde {
33        /// Object key of the offending object, or a short label such as
34        /// `"wal entry"` when encoding something that has no key yet.
35        path: String,
36        /// The underlying `serde_json` error.
37        #[source]
38        source: serde_json::Error,
39    },
40
41    /// The namespace id is empty, longer than 64 bytes, or contains anything
42    /// outside `[a-z0-9_-]`. Keeping `/` out of ids keeps namespaces from
43    /// nesting into each other's prefixes.
44    #[error("invalid namespace id {0:?}: must match [a-z0-9_-]{{1,64}}")]
45    InvalidNamespaceId(String),
46
47    /// `Namespace::create` was called for an id whose manifest already exists.
48    #[error("namespace {0:?} already exists")]
49    NamespaceExists(String),
50
51    /// `Namespace::open` was called for an id with no manifest.
52    #[error("namespace {0:?} not found")]
53    NamespaceNotFound(String),
54
55    /// `Namespace::recover` was called for an id whose manifest exists, or that
56    /// another recovery wrote first. Nothing was changed. The namespace is
57    /// there to [`open`](crate::Namespace::open).
58    #[error("namespace {0:?} already has a manifest")]
59    ManifestExists(String),
60
61    /// `Namespace::recover` cannot rebuild the manifest from what the store
62    /// holds. Nothing was written. `reason` says what is missing, and `keys` are
63    /// the objects to put back from a replica, a versioned bucket or a backup.
64    /// Once they are back, running `recover` again can succeed.
65    #[error("cannot rebuild the manifest: {reason}; restore {keys:?} and run recover again")]
66    Unrecoverable {
67        /// What has no readable copy.
68        reason: String,
69        /// Object keys that would fill the gap, at most a handful.
70        keys: Vec<String>,
71    },
72
73    /// The schema passed to `Namespace::create` cannot be used. Today that
74    /// means `dim == 0`.
75    #[error("invalid schema: {0}")]
76    InvalidSchema(&'static str),
77
78    /// A vector's length differs from the namespace's `dim`. Raised for
79    /// documents on write and for the query vector on read.
80    #[error("dimension mismatch: expected {expected}, got {got}")]
81    DimensionMismatch {
82        /// The namespace's `dim`.
83        expected: usize,
84        /// The length of the vector that was passed in.
85        got: usize,
86    },
87
88    /// A vector has a NaN or infinite component, or is all zeros under the
89    /// cosine metric (which has no direction to compare).
90    #[error("invalid vector: {0}")]
91    InvalidVector(&'static str),
92
93    /// A document's attributes, or a predicate, name a field the namespace's
94    /// attribute schema does not declare.
95    #[error("unknown attribute field {field:?}")]
96    UnknownAttr {
97        /// The field name as given.
98        field: String,
99    },
100
101    /// A value or an operator does not fit the declared type of a field.
102    /// `expected` is what the schema or the operator needs, `found` what was
103    /// given.
104    #[error("attribute {field:?}: expected {expected}, found {found}")]
105    AttrTypeMismatch {
106        /// The field name.
107        field: String,
108        /// The type the schema or the operator needs.
109        expected: &'static str,
110        /// The type that was found.
111        found: &'static str,
112    },
113
114    /// A document's `attrs` are not acceptable under the namespace's attribute
115    /// schema for a reason that is not one field's type: not a JSON object, or
116    /// a set with too many elements.
117    #[error("invalid attributes: {0}")]
118    InvalidAttrs(&'static str),
119
120    /// A [`DocColumns`](crate::DocColumns) batch is malformed: offsets that do
121    /// not start at zero, go down or overrun their buffer, a column that does
122    /// not mark every row, text that is not UTF-8, a repeated or empty column
123    /// name, or batches of one stream that do not share their columns.
124    #[error("invalid columns: {0}")]
125    InvalidColumns(&'static str),
126
127    /// [`QueryOptions`](crate::QueryOptions) that cannot be run: a shortlist
128    /// factor or a probe count of zero.
129    #[error("invalid query options: {0}")]
130    InvalidQuery(&'static str),
131
132    /// A process-wide setting was refused: for instance sizing the compute
133    /// pools with [`configure_cpu`](crate::configure_cpu) after they started,
134    /// or with zero threads.
135    #[error("invalid configuration: {0}")]
136    InvalidConfig(&'static str),
137
138    /// `upsert` or `delete` was called with nothing to write.
139    #[error("empty batch")]
140    EmptyBatch,
141
142    /// A WAL append lost the put-if-absent race 32 times in a row and gave up.
143    /// Retrying the whole call is safe: nothing was written.
144    #[error("write contention: gave up after {attempts} attempts")]
145    WriteContention {
146        /// How many sequence numbers were tried.
147        attempts: u32,
148    },
149
150    /// A manifest compare-and-swap lost the race 32 times in a row and gave up.
151    /// Compaction's publish step is bound by the same cap, and so is raising a
152    /// segment's generation mark before an index build writes its object;
153    /// nothing was written then either.
154    #[error("manifest contention: gave up after {attempts} attempts")]
155    ManifestContention {
156        /// How many read-modify-write rounds were tried.
157        attempts: u32,
158    },
159
160    /// The WAL is not a contiguous run of sequence numbers. The write path
161    /// never leaves a hole, so this means an object was deleted by hand or
162    /// there is a bug.
163    #[error("wal gap: expected seq {expected}, found {found}")]
164    WalGap {
165        /// The sequence number that should have come next.
166        expected: u64,
167        /// The sequence number that was there instead.
168        found: u64,
169    },
170
171    /// An object carries a `format_version` this build does not understand.
172    #[error("unsupported format version {version}")]
173    UnsupportedFormat {
174        /// The version found in the object.
175        version: u32,
176    },
177
178    /// The namespace's manifest says its WAL may hold objects in a format newer
179    /// than this build reads. Nothing was read or written. Upgrade the build,
180    /// then retry. Raised for every operation on the namespace, since each one
181    /// loads the manifest first.
182    #[error(
183        "namespace needs WAL format {found}, this build reads up to {supported}: upgrade this build"
184    )]
185    WalFormatTooNew {
186        /// The `wal_format` in the manifest.
187        found: u32,
188        /// The newest WAL format this build reads.
189        supported: u32,
190    },
191
192    /// The namespace's manifest says its segments may be in a format newer than
193    /// this build reads. Nothing was read or written. Upgrade the build, then
194    /// retry. Raised for every operation on the namespace, like
195    /// [`ItzmaError::WalFormatTooNew`].
196    #[error(
197        "namespace has segment format {found}, this build reads up to {supported}: upgrade this build"
198    )]
199    SegmentFormatTooNew {
200        /// The `segment_format` in the manifest.
201        found: u32,
202        /// The newest segment format this build reads.
203        supported: u32,
204    },
205
206    /// The namespace's WAL format is lower than the operation needs. A keyed
207    /// write needs level 3, fencing WAL objects in `Namespace::gc` needs level
208    /// 4, and a namespace created by an older build is at 2. Nothing was
209    /// written or changed. Once every build that touches the namespace reads
210    /// the newer format, raise it with `Namespace::upgrade_wal_format`.
211    #[error(
212        "namespace is at WAL format {have}, this operation needs {need}: upgrade the namespace with upgrade_wal_format({need})"
213    )]
214    WalFormatTooOld {
215        /// The `wal_format` in the manifest.
216        have: u32,
217        /// The level the operation needs.
218        need: u32,
219    },
220
221    /// The namespace's segment format is lower than the operation needs.
222    /// `Namespace::index` needs level 2, because an index is built for the
223    /// block-addressable layout, and a namespace created by an older build is
224    /// at level one. Nothing was written or changed. Once every build that
225    /// touches the namespace reads version 2, raise it with
226    /// `Namespace::upgrade_segment_format`.
227    #[error(
228        "namespace is at segment format {have}, this operation needs {need}: upgrade the namespace with upgrade_segment_format({need})"
229    )]
230    SegmentFormatTooOld {
231        /// The `segment_format` in the manifest.
232        have: u32,
233        /// The level the operation needs.
234        need: u32,
235    },
236
237    /// A segment object cannot be used: it is truncated, has the wrong
238    /// magic, disagrees with its own counts, has ids out of order, or is
239    /// missing although the manifest lists it. Also raised when a segment's
240    /// dimension differs from the namespace schema.
241    #[error("corrupt segment {path}: {reason}")]
242    CorruptSegment {
243        /// Object key of the segment.
244        path: String,
245        /// What is wrong with it.
246        reason: String,
247    },
248
249    /// An index object cannot be used: it is truncated, has the wrong magic, a
250    /// kind this build does not know, counts, offsets or a head length that
251    /// disagree with each other, values that are not finite, or a row count or
252    /// data size that differs from the segment it was built for.
253    /// A query never falls back to a flat scan over one (`exact` skips indexes
254    /// altogether), and `index` with `rebuild` replaces it.
255    #[error("corrupt index {path}: {reason}")]
256    CorruptIndex {
257        /// Object key of the index, or `"(encoding)"` on the write side.
258        path: String,
259        /// What is wrong with it.
260        reason: String,
261    },
262
263    /// A sparse inverted-index object cannot be used: it is truncated, has
264    /// the wrong magic, counts or offsets that disagree with each other, or
265    /// a row count that differs from the segment it was built for. A query
266    /// never falls back to a flat scan over one, and
267    /// [`Namespace::index_sparse`](crate::Namespace::index_sparse) with
268    /// `rebuild` replaces it.
269    #[error("corrupt sparse index {path}: {reason}")]
270    CorruptSparseIndex {
271        /// Object key of the index, or `"(encoding)"` on the write side.
272        path: String,
273        /// What is wrong with it.
274        reason: String,
275    },
276
277    /// A binary WAL object (format version 2) cannot be used: it is
278    /// truncated, names an unknown codec, disagrees with its own lengths or
279    /// counts, holds a ZSTD frame that does not match its header, has invalid
280    /// UTF-8 or JSON inside, or has trailing bytes. Also raised on the write
281    /// side when a length cannot be encoded. An object without the WAL magic
282    /// is refused the same way.
283    #[error("corrupt wal object {path}: {reason}")]
284    CorruptWal {
285        /// Object key of the WAL object, or `"(encoding)"` on the write side.
286        path: String,
287        /// What is wrong with it.
288        reason: String,
289    },
290
291    /// An idempotency key is empty or longer than 128 bytes. Raised before
292    /// anything is written.
293    #[error("invalid idempotency key: {0}")]
294    InvalidKey(&'static str),
295
296    /// A document id (on `upsert`) or a delete id is empty or longer than
297    /// [`document::MAX_ID_BYTES`](crate::document::MAX_ID_BYTES) bytes.
298    /// Raised before anything is written.
299    #[error("invalid id: {0}")]
300    InvalidId(&'static str),
301
302    /// A WAL object already carries this idempotency key but holds a batch of
303    /// a different size, so the key is being reused for a different write.
304    /// Nothing was written. A key names one batch.
305    #[error("idempotency key {key:?} was already used for a different batch")]
306    KeyConflict {
307        /// The key.
308        key: String,
309    },
310
311    /// A write batch is bigger than the writer limit,
312    /// [`MAX_BODY_BYTES`](crate::wal::MAX_BODY_BYTES). Nothing was built or
313    /// written. Split the load into several batches; each is atomic, the split
314    /// as a whole is not.
315    #[error("batch of {bytes} bytes is over the {max} byte limit")]
316    BatchTooLarge {
317        /// The exact size the batch would have, before compression.
318        bytes: u64,
319        /// The writer limit.
320        max: u64,
321    },
322
323    /// A query or a compaction run would read more than the handle's read
324    /// budget. Nothing was written. `needed` is the total of the
325    /// objects the read had asked for when it hit the limit, this one
326    /// included. Compact to shorten the WAL tail, or raise the budget with
327    /// [`Namespace::with_read_budget`](crate::Namespace::with_read_budget).
328    #[error("reading {path} needs {needed} bytes, over the {max} byte read budget")]
329    ReadBudgetExceeded {
330        /// Object key of the object that went over.
331        path: String,
332        /// The running total, including that object.
333        needed: u64,
334        /// The read budget.
335        max: u64,
336    },
337
338    /// The manifest's segment list breaks the invariant: ids that do not
339    /// parse, ranges that do not start at 1 or do not follow one another, or a
340    /// last range that does not end at `wal_folded_through`. Also raised when
341    /// `schema.json` holds a different schema from the manifest.
342    #[error("corrupt manifest: {0}")]
343    CorruptManifest(String),
344}
345
346/// `std::result::Result` with [`ItzmaError`] as the error type.
347pub type Result<T> = std::result::Result<T, ItzmaError>;