Skip to main content

bifrost/
error.rs

1use std::{fmt, io};
2
3/// Fallible public API result. The error type is always [`Error`].
4pub type Result<T> = std::result::Result<T, Error>;
5
6/// Recoverable failure from configuration, insert, search, or `.hnsw` I/O.
7///
8/// Match on the variant. The `Display` text is a diagnostic, not a stable
9/// protocol.
10#[derive(Debug)]
11pub enum Error {
12    /// A [`crate::Config`] field failed validation, or a later setter received
13    /// an out-of-range value.
14    ///
15    /// Returned by [`crate::HnswIndex::new`], [`crate::HnswIndex::set_ef_search`],
16    /// and [`crate::HnswIndex::set_level_mult`]. The payload names the failed
17    /// rule (`dim`, `m`, `ef_construction`, and `ef_search` must be greater
18    /// than zero; `max_level` must be in `1..=254`; `level_mult` must be
19    /// finite and in `[0, 1]`). Fix the parameter and retry.
20    InvalidConfig(&'static str),
21    /// A vector's length does not match the expected dimension.
22    ///
23    /// Insert and search compare against [`crate::Config::dim`].
24    /// [`crate::vector::dot`], [`crate::vector::cosine_distance`], and
25    /// [`crate::vector::cosine_similarity`] compare the two argument lengths
26    /// (`expected` from the first slice, `actual` from the second). Supply a
27    /// slice of the expected length.
28    DimensionMismatch { expected: usize, actual: usize },
29    /// A coordinate is non-finite, or the L2 norm is more than
30    /// [`crate::vector::UNIT_NORM_TOLERANCE`] from `1`.
31    ///
32    /// Returned only when [`crate::Config::check_vectors`] is set (or after
33    /// [`crate::HnswIndex::set_check_vectors`] /
34    /// [`crate::LoadedHnsw::set_check_vectors`]). Debug builds `debug_assert`
35    /// the same contract even when the flag is off. Normalize the vector and
36    /// drop NaN/Inf before retrying.
37    InvalidVector(&'static str),
38    /// [`crate::HnswIndex::insert`] or [`crate::HnswIndex::build`] reused an
39    /// external ID already in the index.
40    ///
41    /// The payload is the colliding ID. [`crate::HnswIndex::build`] assigns
42    /// `0..n-1` and is for an empty index; a second `build` or `build` after
43    /// `insert(0, …)` fails here. Choose a free ID, or call `insert` to append.
44    DuplicateExternalId(u32),
45    /// An in-memory or on-disk count cannot be stored in `u32`.
46    ///
47    /// The graph may hold [`u32::MAX`] nodes (`0..=u32::MAX - 1`). A further
48    /// insert, a `build` ID that does not fit in `u32`, or a vector/edge table
49    /// that would overflow `u32` returns this. The payload names the quantity.
50    /// The index is unchanged; split the data or use another index.
51    CapacityExceeded(&'static str),
52    /// A node index is missing from the graph, or is not a valid search entry.
53    ///
54    /// Public [`crate::Graph`] accessors return empty/`None` instead of this
55    /// error. Insert and search can return it when the entry point is absent
56    /// or a mapped vector is missing. A failed [`crate::HnswIndex::insert`] is
57    /// rolled back, so the ID can be retried. Treat a persistent occurrence as
58    /// a corrupt in-memory graph or snapshot.
59    InvalidNode(u32),
60    /// A layer is above a node's assigned level, or the layer does not exist.
61    ///
62    /// Public [`crate::Graph::edges`] returns an empty slice for this case.
63    /// Insert and search can return it when descent starts from an entry that
64    /// does not occupy the requested layer. Same recovery as
65    /// [`Error::InvalidNode`].
66    InvalidLayer(u8),
67    /// The file does not start with [`crate::MAGIC`].
68    ///
69    /// The path is not a Bifrost `.hnsw` snapshot, or it is corrupt before the
70    /// magic. Open a file written by [`crate::HnswIndex::save`].
71    InvalidMagic,
72    /// The snapshot version is neither [`crate::VERSION`] nor
73    /// [`crate::MIGRATABLE_VERSION`].
74    ///
75    /// `expected` is the current writer version. `actual` is the file's
76    /// version. Valid v2 files are rewritten to v3 on load; other versions
77    /// cannot be opened. Rebuild the index with this crate, or use a matching
78    /// reader.
79    UnsupportedVersion { expected: u16, actual: u16 },
80    /// The v3 data-section CRC32 does not match [`crate::Header::stored_crc`].
81    ///
82    /// `expected` is the header value; `actual` is the hash of bytes after
83    /// [`crate::HEADER_SIZE`]. The file was truncated or overwritten in place.
84    /// Restore a good snapshot; do not search this mapping.
85    CrcMismatch { expected: u32, actual: u32 },
86    /// The snapshot failed layout or writer-invariant checks after a valid
87    /// magic and version.
88    ///
89    /// Typical causes: truncated sections, invalid header fields, duplicate
90    /// external IDs, gapped vector offsets, or unsorted edge lists. The
91    /// payload is a static reason. The file cannot be searched; rewrite it
92    /// from a live [`crate::HnswIndex`].
93    InvalidFile(&'static str),
94    /// A filesystem or mmap error from save, load, or rename.
95    ///
96    /// Implements [`std::error::Error::source`]. Retry transient I/O; check
97    /// permissions and disk space for persistent failures.
98    Io(io::Error),
99}
100
101impl fmt::Display for Error {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        match self {
104            Self::InvalidConfig(message) => write!(f, "invalid configuration: {message}"),
105            Self::DimensionMismatch { expected, actual } => {
106                write!(f, "dimension mismatch: expected {expected}, got {actual}")
107            }
108            Self::InvalidVector(message) => write!(f, "invalid vector: {message}"),
109            Self::DuplicateExternalId(id) => write!(f, "duplicate external ID {id}"),
110            Self::CapacityExceeded(what) => write!(f, "{what} exceeds the on-disk u32 capacity"),
111            Self::InvalidNode(node) => write!(f, "invalid node index {node}"),
112            Self::InvalidLayer(layer) => write!(f, "invalid graph layer {layer}"),
113            Self::InvalidMagic => write!(f, "invalid HNSW file magic"),
114            Self::UnsupportedVersion { expected, actual } => write!(
115                f,
116                "unsupported HNSW file version {actual}; expected {expected}"
117            ),
118            Self::CrcMismatch { expected, actual } => write!(
119                f,
120                "HNSW data CRC mismatch: expected {expected:#010x}, got {actual:#010x}"
121            ),
122            Self::InvalidFile(message) => write!(f, "invalid HNSW file: {message}"),
123            Self::Io(error) => error.fmt(f),
124        }
125    }
126}
127
128impl std::error::Error for Error {
129    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
130        match self {
131            Self::Io(error) => Some(error),
132            _ => None,
133        }
134    }
135}
136
137impl From<io::Error> for Error {
138    fn from(value: io::Error) -> Self {
139        Self::Io(value)
140    }
141}