1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0
/// Top-level error type for all `zeph-memory` operations.
///
/// Wraps database, vector-store, LLM, and serialization errors into a single type
/// consumed by callers in `zeph-core`.
///
/// # Examples
///
/// ```rust
/// use zeph_memory::MemoryError;
///
/// fn demo(e: MemoryError) -> String {
/// e.to_string()
/// }
/// ```
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum MemoryError {
#[error("sqlx error: {0}")]
Sqlx(#[from] zeph_db::SqlxError),
#[error("db error: {0}")]
Db(#[from] zeph_db::DbError),
#[error("Qdrant error: {0}")]
Qdrant(#[from] Box<qdrant_client::QdrantError>),
#[error("vector store error: {0}")]
VectorStore(#[from] crate::vector_store::VectorStoreError),
#[error("LLM error: {0}")]
Llm(#[from] zeph_llm::LlmError),
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
#[error("integer conversion: {0}")]
IntConversion(#[from] std::num::TryFromIntError),
#[error("snapshot error: {0}")]
Snapshot(String),
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
#[error("graph store error: {0}")]
GraphStore(String),
#[error("invalid input: {0}")]
InvalidInput(String),
/// A mutex or `RwLock` was poisoned by a panicking thread.
///
/// This indicates a programming error (a thread panicked while holding the lock).
/// The inner string describes which lock was poisoned.
#[error("lock poisoned: {0}")]
LockPoisoned(String),
/// Catch-all for errors that do not yet have a specific typed variant.
///
/// # Deprecation
///
/// Prefer adding a typed variant over using `Other`. This variant exists for
/// backward compatibility and will be removed once all callsites are migrated.
#[error("{0}")]
Other(String),
#[error("operation timed out: {0}")]
Timeout(String),
/// Returned when inserting a supersede pointer would form a cycle in the chain.
#[error("supersede cycle detected at edge id={0}")]
SupersedeCycle(i64),
/// Returned when the supersede chain depth would exceed [`crate::graph::conflict::SUPERSEDE_DEPTH_CAP`].
#[error("supersede chain depth cap exceeded at edge id={0}")]
SupersedeDepthExceeded(i64),
/// A promotion-scan or promote error (Feature A, #3305).
///
/// Wraps errors from clustering, skill generation, evaluator calls, or disk writes.
#[error("promotion scan failed: {0}")]
Promotion(String),
/// An error during `zeph knowledge ingest` (spec-067).
///
/// Covers path-validation failures, unsupported source kinds, and per-file ingest errors
/// reported by the notes-sink pipeline.
#[error("ingest error: {0}")]
Ingest(String),
/// The post-extract validator rejected this extraction result.
///
/// Returned by `extract_and_store` when the `post_extract_validator` callback returns
/// `Err`. The caller (`ingest_documents`) converts this into `DocOutcome::Rejected`
/// so the document is counted separately from hard failures.
#[error("validation rejected: {0}")]
ValidationRejected(String),
}
impl MemoryError {
/// Returns `true` when this error is a database foreign-key constraint violation.
///
/// Used to distinguish silent-drop-worthy edge/entity write failures (e.g. a stale
/// cross-database entity id) from ordinary transient DB errors, so callers can log the
/// former at `WARN` instead of `DEBUG` (#5801).
#[must_use]
pub fn is_foreign_key_violation(&self) -> bool {
use sqlx::error::DatabaseError;
matches!(self, Self::Sqlx(err) if err
.as_database_error()
.is_some_and(DatabaseError::is_foreign_key_violation))
}
}
#[cfg(test)]
mod tests {
use super::MemoryError;
#[test]
fn sqlx_variant_display() {
let inner = zeph_db::SqlxError::RowNotFound;
let err = MemoryError::Sqlx(inner);
assert!(
err.to_string().starts_with("sqlx error:"),
"unexpected display: {err}"
);
}
#[test]
fn db_variant_display() {
let inner = zeph_db::DbError::Io(std::io::Error::new(std::io::ErrorKind::NotFound, "test"));
let err = MemoryError::Db(inner);
assert!(
err.to_string().starts_with("db error:"),
"unexpected display: {err}"
);
}
#[test]
fn is_foreign_key_violation_false_for_non_constraint_error() {
let err = MemoryError::Sqlx(zeph_db::SqlxError::RowNotFound);
assert!(!err.is_foreign_key_violation());
}
#[test]
fn is_foreign_key_violation_false_for_non_sqlx_variant() {
let err = MemoryError::GraphStore("unrelated failure".into());
assert!(!err.is_foreign_key_violation());
}
/// Regression test for #5801: `is_foreign_key_violation()` must recognize a genuine
/// FK constraint violation (not just a manufactured/mocked one), since it is the
/// linchpin of the WARN-vs-DEBUG observability fix.
#[tokio::test]
async fn is_foreign_key_violation_true_for_real_fk_violation() {
use crate::graph::GraphStore;
use crate::store::SqliteStore;
let sqlite = SqliteStore::new(":memory:").await.unwrap();
let store = GraphStore::new(sqlite.pool().clone());
// Neither entity id exists in this fresh database — a genuine FK violation.
let err = store
.insert_edge(999_999, 888_888, "related_to", "fact", 0.9, None, None)
.await
.expect_err("inserting an edge between nonexistent entities must fail");
assert!(
err.is_foreign_key_violation(),
"expected a foreign-key violation, got: {err:#}"
);
}
}