Skip to main content

velesdb_memory/
error.rs

1//! Error type for the memory layer.
2
3#[cfg(feature = "persistence")]
4use velesdb_core::agent::AgentMemoryError;
5use velesdb_core::Error as CoreError;
6
7use crate::embedder::EmbedError;
8use crate::extract::ExtractError;
9use crate::rerank::RerankError;
10
11/// The transport-neutral class of a [`MemoryError`] — the single source of
12/// truth every adapter maps onto its own error channel (JSON-RPC code, napi
13/// status, `PyO3` exception type), so the taxonomy can never drift between them.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum ErrorCategory {
16    /// The caller supplied bad input (empty fact, reserved key, malformed
17    /// filter) — a 4xx-style fault.
18    InvalidInput,
19    /// A referenced memory id does not exist.
20    NotFound,
21    /// An internal storage / embedding / extraction failure — a 5xx-style fault.
22    Internal,
23}
24
25/// Errors returned by [`crate::service::MemoryService`].
26#[derive(Debug, thiserror::Error)]
27pub enum MemoryError {
28    /// Failure in the underlying `VelesDB` storage engine.
29    #[error("storage error: {0}")]
30    Storage(#[from] CoreError),
31
32    /// Failure in the Agent Memory SDK. Only constructible with the
33    /// `persistence` feature (the native, file-backed store) — a
34    /// `persistence`-free backend (e.g. `velesdb-wasm`'s in-memory one) never
35    /// touches `velesdb-core`'s `agent` module, so this variant can't arise.
36    #[cfg(feature = "persistence")]
37    #[error("memory error: {0}")]
38    Memory(#[from] AgentMemoryError),
39
40    /// A fact was empty or whitespace-only.
41    #[error("fact text must not be empty")]
42    EmptyFact,
43
44    /// A `remember` link or a `relate` endpoint referenced a memory id that
45    /// does not exist.
46    #[error("memory {0} does not exist")]
47    UnknownMemory(u64),
48
49    /// Caller metadata or a recall filter named a reserved key (`content` or a
50    /// `_veles_`-prefixed system key), which callers may not set or filter on.
51    #[error("metadata key '{0}' is reserved")]
52    ReservedKey(String),
53
54    /// Caller-supplied `metadata` (on `remember`/`remember_with_ttl` or a
55    /// context-compiler fragment) exceeded [`crate::limits::MAX_METADATA_BYTES`]
56    /// — a `DoS` guard, since metadata is a keyed lookup facet, not a payload.
57    #[error("metadata of {bytes} bytes exceeds the cap of {max} bytes")]
58    MetadataTooLarge {
59        /// The serialized size of the rejected metadata, in bytes.
60        bytes: usize,
61        /// The cap that was exceeded ([`crate::limits::MAX_METADATA_BYTES`]).
62        max: usize,
63    },
64
65    /// Failure producing a text embedding.
66    #[error("embedding error: {0}")]
67    Embed(#[from] EmbedError),
68
69    /// Failure extracting facts from raw text in
70    /// [`crate::service::MemoryService::remember_extracted`].
71    #[error("extraction error: {0}")]
72    Extract(#[from] ExtractError),
73
74    /// Failure reranking a fused-recall candidate pool in
75    /// [`crate::service::MemoryService::recall_fused_reranked`].
76    #[error("rerank error: {0}")]
77    Rerank(#[from] RerankError),
78
79    /// A fused-recall filter referenced a field name that is not a plain
80    /// identifier, named a reserved key, or carried a non-scalar value.
81    #[error("invalid filter field: {0}")]
82    InvalidFilter(String),
83
84    /// A relation label supplied to [`crate::service::MemoryService::relate`] or
85    /// a [`crate::model::Link`] in
86    /// [`crate::service::MemoryService::remember`] was invalid — empty, too long,
87    /// or contained non-printable characters.
88    #[error("invalid relation label: {0}")]
89    InvalidRelation(String),
90
91    /// A context-compile request carried a token budget that cannot hold any
92    /// context: zero, or not larger than the response reserve the policy
93    /// keeps aside for the model's answer.
94    #[cfg(feature = "context")]
95    #[error("token budget {budget} cannot hold any context (reserve {reserve})")]
96    ContextBudget {
97        /// The caller-supplied token budget.
98        budget: u64,
99        /// The response reserve the policy subtracts from the budget.
100        reserve: u64,
101    },
102
103    /// A context-compile request exceeded a resource cap from
104    /// [`crate::limits`] — too many fragments, or one fragment larger than
105    /// the per-fragment byte ceiling.
106    #[cfg(feature = "context")]
107    #[error("context request over limit: {0}")]
108    ContextOverLimit(String),
109
110    /// A `ctx://source/<hash>` handle was malformed or nothing is stored
111    /// under it (the source was never stored, expired, or was forgotten).
112    #[cfg(feature = "context")]
113    #[error("unknown context source handle: {0}")]
114    UnknownHandle(String),
115
116    /// A persisted working context could not be (de)serialized — the stored
117    /// payload predates or postdates this crate's schema.
118    #[cfg(feature = "context")]
119    #[error("working context codec error: {0}")]
120    WorkingContextCodec(String),
121
122    /// A `remember` link failed after the fact was stored AND the
123    /// compensating rollback delete also failed — unlike every other error
124    /// from `remember`, the fact **remains stored**. Both errors are
125    /// carried so the caller can see why the write failed and why the
126    /// cleanup couldn't undo it.
127    ///
128    /// Neither field is `#[source]` — deliberately: the `Display` message
129    /// already embeds both errors, and a source chain would double-print
130    /// them in chain-style reports (anyhow, miette). Match on the variant
131    /// to inspect the two errors programmatically.
132    #[error(
133        "link failed ({cause}); rollback delete also failed ({rollback}) — the fact remains stored"
134    )]
135    RollbackFailed {
136        /// The link failure that triggered the rollback.
137        cause: Box<MemoryError>,
138        /// The storage failure that prevented the rollback delete.
139        rollback: Box<MemoryError>,
140    },
141}
142
143impl MemoryError {
144    /// Classify this error into a transport-neutral [`ErrorCategory`]. Adapters
145    /// map the *category*, not the variant, so the client-facing taxonomy stays
146    /// identical across the MCP server and every binding.
147    #[must_use]
148    pub fn category(&self) -> ErrorCategory {
149        match self {
150            Self::EmptyFact
151            | Self::ReservedKey(_)
152            | Self::InvalidFilter(_)
153            | Self::InvalidRelation(_)
154            | Self::MetadataTooLarge { .. } => ErrorCategory::InvalidInput,
155            #[cfg(feature = "context")]
156            Self::ContextBudget { .. } | Self::ContextOverLimit(_) => ErrorCategory::InvalidInput,
157            #[cfg(feature = "context")]
158            Self::UnknownHandle(_) => ErrorCategory::NotFound,
159            #[cfg(feature = "context")]
160            Self::WorkingContextCodec(_) => ErrorCategory::Internal,
161            Self::UnknownMemory(_) => ErrorCategory::NotFound,
162            #[cfg(feature = "persistence")]
163            Self::Memory(_) => ErrorCategory::Internal,
164            Self::Storage(_) | Self::Embed(_) | Self::Extract(_) | Self::Rerank(_) => {
165                ErrorCategory::Internal
166            }
167            // The rollback failure is the storage-level fault that matters
168            // to a client: the write is in an unexpected state.
169            Self::RollbackFailed { .. } => ErrorCategory::Internal,
170        }
171    }
172}