zeph_durable/error.rs
1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! The crate-wide error type.
5//!
6//! [`DurableError`] never carries payload bytes or resolver tokens in its messages (INV-5): every
7//! variant reports metadata only, so an error can be logged without leaking sealed content.
8
9use crate::ids::{ExecutionId, StepId};
10
11/// An error raised by the durable execution layer.
12///
13/// The enum is `#[non_exhaustive]`: follow-up issues add variants as runtime behavior lands, and
14/// downstream `match` expressions must keep a wildcard arm.
15#[derive(Debug, thiserror::Error)]
16#[non_exhaustive]
17pub enum DurableError {
18 /// The replayed step's descriptor fingerprint did not match the fingerprint journaled for this
19 /// [`StepId`] (INV-3). The execution is discarded and restarted fresh rather than returning a
20 /// result for a structurally different step.
21 #[error("replay divergence at step {step_id}: journaled descriptor fingerprint mismatch")]
22 ReplayDivergence {
23 /// The step whose fingerprint diverged.
24 step_id: StepId,
25 },
26
27 /// A destructive or security-relevant `ExactlyOnceGuarded` step was constructed without an
28 /// explicit ambiguity policy. The safety decision must be made at the call site, not deferred
29 /// to a runtime default.
30 #[error("step '{step}' requires an explicit on_ambiguous policy for its effect class")]
31 AmbiguityPolicyRequired {
32 /// The name of the offending step descriptor.
33 step: &'static str,
34 },
35
36 /// The journal writer did not acknowledge an append within the configured timeout, or is
37 /// otherwise unreachable. The calling path degrades to non-durable mode rather than hanging
38 /// (INV-12).
39 #[error("journal writer unavailable: append was not acknowledged in time")]
40 JournalUnavailable,
41
42 /// A payload exceeded the configured `max_payload_bytes` limit. Enforced on both append and
43 /// read; it fails closed and never panics (INV-11).
44 #[error("payload of {size} bytes exceeds the {max}-byte limit")]
45 PayloadTooLarge {
46 /// The size of the offending payload, in bytes.
47 size: u64,
48 /// The configured maximum payload size, in bytes.
49 max: u64,
50 },
51
52 /// A journal entry could not be decoded: corrupt, truncated, or written under an unknown wire
53 /// format version. Fails closed.
54 #[error("failed to decode journal entry: {context}")]
55 Decode {
56 /// A non-sensitive description of the decode failure.
57 context: &'static str,
58 },
59
60 /// AEAD authentication failed when opening a sealed payload: the entry was forged, moved to a
61 /// different step, or replayed under a different execution. Fails closed.
62 #[error("replay integrity check failed: sealed payload did not authenticate")]
63 ReplayIntegrity,
64
65 /// A control entry's row-level HMAC (INV-8) did not verify against a recomputed value: the row
66 /// was forged, relocated to a different step/execution, or is missing its HMAC even though the
67 /// backend is keyed. Fails closed like [`ReplayIntegrity`](Self::ReplayIntegrity), but for
68 /// HMAC-authenticated control entries (`EffectIntent`) rather than AEAD-sealed payloads.
69 #[error("control-entry integrity check failed: row HMAC did not authenticate")]
70 ControlIntegrity,
71
72 /// An execution exceeded the hard per-execution step cap and was aborted rather than allowed to
73 /// grow unboundedly.
74 #[error("execution exceeded the step cap of {cap} steps")]
75 StepCapExceeded {
76 /// The configured hard step cap.
77 cap: u32,
78 },
79
80 /// AEAD payload encryption was disabled (`encrypt_payload = false`) for a deployment where it
81 /// is mandatory — a non-local backend or a shared database (INV-8). The DB-file trust boundary
82 /// does not hold in multi-client environments, so this fails closed at startup.
83 #[error(
84 "AEAD payload encryption is required for the '{context}' deployment and cannot be disabled"
85 )]
86 EncryptionRequired {
87 /// A non-sensitive label for the deployment that mandates encryption (e.g. `"restate"` or
88 /// `"shared-database"`).
89 context: &'static str,
90 },
91
92 /// A journal entry of a kind whose persistence is provided by a higher layer not yet wired into
93 /// this backend revision. Promise, timer, and checkpoint entries land with the promise/timer and
94 /// retention layers; until then the backend fails closed rather than silently dropping the
95 /// entry's kind-specific state.
96 #[error("journal persistence for '{kind}' entries is not available in this backend revision")]
97 UnsupportedEntryKind {
98 /// The `entry_kind` tag of the entry whose persistence is deferred.
99 kind: &'static str,
100 },
101
102 /// A journal storage operation failed at the database layer (connection, migration, or query).
103 ///
104 /// The static `op` names the failing operation; the underlying database error is attached as
105 /// the error source. Per INV-5 the `Display` message carries only the operation name — the
106 /// boxed source never contains plaintext payloads, since every bind is ciphertext, a hash, or a
107 /// non-secret descriptor.
108 #[error("durable storage operation '{op}' failed")]
109 Storage {
110 /// The static name of the failing operation (e.g. `"append"`, `"finalize"`, `"open"`).
111 op: &'static str,
112 /// The underlying database error.
113 #[source]
114 source: Box<dyn std::error::Error + Send + Sync>,
115 },
116
117 /// A step's operation closure returned an error on a fresh execution. The step did not complete,
118 /// so no `StepResult` is journaled; on a later resume the step re-runs (or, for a guarded effect,
119 /// its [`OnAmbiguous`](crate::OnAmbiguous) policy applies). The closure's own error is attached
120 /// as the source.
121 #[error("step '{step}' operation failed")]
122 StepFailed {
123 /// The name of the step whose operation closure failed.
124 step: &'static str,
125 /// The closure's underlying error.
126 #[source]
127 source: Box<dyn std::error::Error + Send + Sync>,
128 },
129
130 /// A guarded step resumed inside the ambiguous window (an `EffectIntent` is journaled but no
131 /// `StepResult`) and its policy is [`OnAmbiguous::Fail`](crate::OnAmbiguous::Fail): the layer
132 /// refuses to guess whether the irreversible effect fired and surfaces the decision to the
133 /// operator instead of re-running or skipping it.
134 #[error("step {step_id} resumed in the ambiguous window and its on_ambiguous policy is 'fail'")]
135 AmbiguousEffect {
136 /// The step caught in the ambiguous window.
137 step_id: StepId,
138 },
139
140 /// A step result could not be serialized into journal bytes before sealing. The step's value is
141 /// the consumer's serializable type, so this indicates a faulty `Serialize` implementation; it
142 /// fails closed rather than journaling a partial payload. Per INV-5 only the step name is named.
143 #[error("step '{step}' result could not be serialized for the journal")]
144 Serialize {
145 /// The name of the step whose result failed to serialize.
146 step: &'static str,
147 },
148
149 /// A promise resolution referenced a promise that has no `durable_promises` row — either never
150 /// created, or pruned. Fails closed rather than silently succeeding. Per INV-5 the raw
151 /// `PromiseId` is semi-sensitive and is therefore not embedded in the message.
152 #[error("promise resolution failed: no such promise")]
153 UnknownPromise,
154
155 /// A promise resolution presented a resolver token that did not match the stored hash (INV-9).
156 /// The comparison is constant-time, and neither the presented token nor the raw `PromiseId`
157 /// appears in the message (INV-5). The pending promise is left untouched.
158 #[error("promise resolution rejected: resolver token did not authenticate")]
159 PromiseRejected,
160
161 /// The execution's authenticated high-water-mark (issue #6360) did not verify on resume.
162 ///
163 /// The high-water-mark is a signed `{key_epoch, max_committed_step_id,
164 /// committed_result_count}` tuple, recomputed on every resume from the surviving `StepResult`
165 /// rows plus every checkpoint's persisted `folded_count` and compared against the value signed
166 /// at write time. Unlike [`ControlIntegrity`](Self::ControlIntegrity) (a single-row check),
167 /// this is a whole-execution fail-closed abort (FR-004, US-003): a mismatch means a committed
168 /// result was deleted, or the signed tuple itself was tampered with outside the write path.
169 /// The durable resume path never offers an override for this variant — it always hard-aborts.
170 #[error("execution {execution_id} high-water-mark integrity check failed ({reason}): {hint}")]
171 HighWaterMarkIntegrity {
172 /// The execution whose high-water-mark did not verify.
173 execution_id: ExecutionId,
174 /// A stable, non-sensitive, machine-matchable classification of the failure (INV-5):
175 /// `"count_mismatch"` (the recomputed committed-result count disagreed with the signed
176 /// value), `"hmac_mismatch"` (the signed tuple's HMAC did not authenticate under the
177 /// current epoch's key), or `"key_epoch_unresolvable"` (the stored `key_epoch` is neither
178 /// the current nor a known previous rotation epoch, per FR-008/NFR-004 — a chained/HWM-
179 /// bearing entry with an unresolvable key always fails closed rather than degrading to
180 /// legacy).
181 reason: &'static str,
182 /// A human-readable operator hint distinguishing "possibly re-keyed" (a legitimate key
183 /// rotation the durable resume path cannot resolve automatically) from "TAMPER" (the
184 /// content itself did not authenticate), per FR-008 — so an operator reading logs is not
185 /// misled into treating a rotation-window miss the same as a confirmed forgery. Durable
186 /// resume never offers an interactive override for either case (FR-004): the hint informs
187 /// the operator's own follow-up action, it does not unlock a bypass.
188 hint: &'static str,
189 },
190
191 /// [`crate::backend::LocalBackend::open_execution_exclusive`] found another process already
192 /// holding the execution's advisory lock (INV-15, #6122).
193 ///
194 /// Two processes deriving the same `ExecutionId` (e.g. two CLI instances pointed at the same
195 /// `memory.sqlite_path` and the same `ConversationId`) can no longer both drive it
196 /// concurrently: the second process gets this error instead of silently racing the first into
197 /// `ReplayDivergence`/`ReplayIntegrity` failures. Distinct from those two variants so callers
198 /// (and operators reading logs) can tell "another live process owns this execution" apart from
199 /// "the journal itself is corrupt or was tampered with".
200 #[error("execution {execution_id} is already open in another process (pid {holder_pid})")]
201 ExecutionLocked {
202 /// The execution whose lock is already held.
203 execution_id: ExecutionId,
204 /// PID of the process currently holding the lock, or `0` if it could not be determined.
205 holder_pid: u32,
206 },
207
208 /// [`crate::backend::LocalBackend::open_execution`] (or its exclusive variant) found the
209 /// execution's row already `canceled` (INV-16′, #6362). Unlike `completed`/`failed`/`aborted`,
210 /// a canceled row is never un-finalized and reopened — the cancellation was an explicit
211 /// operator decision that this execution must not run again.
212 #[error("execution {execution_id} was canceled and cannot be resumed")]
213 ExecutionCanceled {
214 /// The execution whose row is `canceled`.
215 execution_id: ExecutionId,
216 },
217}
218
219impl DurableError {
220 /// Wrap a database-layer failure as a [`DurableError::Storage`] for the named operation.
221 ///
222 /// Used at every `zeph-db` call site so storage failures carry a stable, greppable operation
223 /// label while the original error remains reachable via [`std::error::Error::source`].
224 pub(crate) fn storage(
225 op: &'static str,
226 source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
227 ) -> Self {
228 Self::Storage {
229 op,
230 source: source.into(),
231 }
232 }
233
234 /// Wrap a step operation closure's failure as a [`DurableError::StepFailed`].
235 ///
236 /// Keeps the originating error reachable via [`std::error::Error::source`] while the `Display`
237 /// line stays metadata-only (INV-5).
238 pub(crate) fn step_failed(step: &'static str, source: crate::step::StepError) -> Self {
239 Self::StepFailed {
240 step,
241 source: source.into_inner(),
242 }
243 }
244}
245
246#[cfg(test)]
247mod tests {
248 use super::*;
249
250 #[test]
251 fn messages_are_metadata_only() {
252 let err = DurableError::PayloadTooLarge {
253 size: 2_000_000,
254 max: 1_048_576,
255 };
256 let rendered = err.to_string();
257 assert!(rendered.contains("2000000"));
258 assert!(rendered.contains("1048576"));
259 }
260
261 #[test]
262 fn replay_divergence_reports_step() {
263 let err = DurableError::ReplayDivergence {
264 step_id: StepId::new(12),
265 };
266 assert!(err.to_string().contains("step 12"));
267 }
268
269 #[test]
270 fn storage_message_names_op_but_not_the_source_detail() {
271 let inner = std::io::Error::other("secret-bind-value");
272 let err = DurableError::storage("append", inner);
273 let rendered = err.to_string();
274 assert!(rendered.contains("append"));
275 // The top-line message is metadata-only: the source detail is reachable via `source()`,
276 // never inlined into Display (INV-5).
277 assert!(!rendered.contains("secret-bind-value"));
278 assert!(std::error::Error::source(&err).is_some());
279 }
280
281 #[test]
282 fn step_failed_names_step_but_not_the_source_detail() {
283 let err = DurableError::step_failed(
284 "transfer_funds",
285 crate::step::StepError::new("secret-operation-detail"),
286 );
287 let rendered = err.to_string();
288 assert!(rendered.contains("transfer_funds"));
289 assert!(!rendered.contains("secret-operation-detail"));
290 assert!(std::error::Error::source(&err).is_some());
291 }
292
293 #[test]
294 fn ambiguous_and_serialize_messages_are_metadata_only() {
295 let ambiguous = DurableError::AmbiguousEffect {
296 step_id: StepId::new(4),
297 };
298 assert!(ambiguous.to_string().contains("step 4"));
299
300 let serialize = DurableError::Serialize { step: "persist" };
301 assert!(serialize.to_string().contains("persist"));
302 }
303
304 #[test]
305 fn high_water_mark_integrity_names_execution_reason_and_hint() {
306 let execution_id = ExecutionId::new();
307 let err = DurableError::HighWaterMarkIntegrity {
308 execution_id,
309 reason: "count_mismatch",
310 hint: "TAMPER: a committed result was likely deleted outside the write path",
311 };
312 let rendered = err.to_string();
313 assert!(rendered.contains(&execution_id.to_string()));
314 assert!(rendered.contains("count_mismatch"));
315 assert!(rendered.contains("TAMPER"));
316 }
317
318 #[test]
319 fn high_water_mark_integrity_distinguishes_rekeyed_from_tamper_in_the_hint() {
320 // FR-008: the operator-facing hint must read differently for "possibly re-keyed" than
321 // for a confirmed content mismatch, even though both fail closed identically (FR-004).
322 let execution_id = ExecutionId::new();
323 let rekeyed = DurableError::HighWaterMarkIntegrity {
324 execution_id,
325 reason: "key_epoch_unresolvable",
326 hint: "possibly re-keyed: register the prior key",
327 };
328 let tampered = DurableError::HighWaterMarkIntegrity {
329 execution_id,
330 reason: "hmac_mismatch",
331 hint: "TAMPER: the signed value did not authenticate",
332 };
333 assert!(rekeyed.to_string().contains("re-keyed"));
334 assert!(!rekeyed.to_string().contains("TAMPER"));
335 assert!(tampered.to_string().contains("TAMPER"));
336 }
337
338 #[test]
339 fn execution_locked_names_execution_and_holder_pid() {
340 let execution_id = ExecutionId::new();
341 let err = DurableError::ExecutionLocked {
342 execution_id,
343 holder_pid: 4242,
344 };
345 let rendered = err.to_string();
346 assert!(rendered.contains(&execution_id.to_string()));
347 assert!(rendered.contains("4242"));
348 }
349
350 #[test]
351 fn execution_canceled_names_execution_and_is_metadata_only() {
352 let execution_id = ExecutionId::new();
353 let err = DurableError::ExecutionCanceled { execution_id };
354 let rendered = err.to_string();
355 assert!(rendered.contains(&execution_id.to_string()));
356 assert!(rendered.contains("canceled"));
357 }
358}