ff_core/engine_error.rs
1//! Typed engine-error surface (issue #58.6).
2//!
3//! **RFC-012 Stage 1a:** moved from `ff-sdk::engine_error` to
4//! `ff-core::engine_error` so it becomes nameable by the
5//! `EngineBackend` trait (which lives in `ff-core::engine_backend`) without
6//! forcing a public-surface dependency from ff-core on ff-script. The
7//! [`ScriptError`]-aware helpers (`From<ScriptError>`, `valkey_kind`,
8//! `transport_script`, `transport_script_ref`) live in ff-script as
9//! free functions (see `ff_script::engine_error_ext`) — ff-core owns
10//! the enum shapes; ff-script owns the transport-downcast plumbing.
11//!
12//! # Mapping shape
13//!
14//! `ScriptError` lives in the `ff-script` crate (transport-adjacent).
15//! `EngineError` lives here in `ff-core` and is what public SDK calls
16//! return via `ff_sdk::SdkError::Engine`. The bidirectional mapping:
17//!
18//! * `From<ScriptError> for EngineError` — every `ScriptError` variant
19//! is classified into `NotFound` / `Validation` / `Contention` /
20//! `Conflict` / `State` / `Bug` / `Transport`. `Parse` + `Valkey`
21//! flow through `Transport { source: Box<ScriptError> }` so the
22//! underlying `ferriskey::ErrorKind` / parse detail is preserved.
23//! * `DependencyAlreadyExists` is special: per the #58.6 design the
24//! variant carries the pre-existing [`EdgeSnapshot`] inline.
25//! Populating that field requires an extra round-trip (the Lua
26//! script only knows the edge_id), so plain `From<ScriptError>`
27//! returns a `Transport` fallback for that code — callers in the
28//! `stage_dependency` path use `ff_sdk::engine_error::enrich_dependency_conflict`
29//! to perform the follow-up `describe_edge` and upgrade the error
30//! before returning.
31//!
32//! # Exhaustiveness
33//!
34//! The top-level [`EngineError`] and every sub-kind are
35//! `#[non_exhaustive]`. FF can add new Lua error codes in minors
36//! without a breaking change to this surface — consumers that
37//! `match` on a sub-kind must include a `_` arm.
38
39use crate::error::ErrorClass;
40
41/// Typed engine-error surface. See module docs.
42#[derive(Debug, thiserror::Error)]
43#[non_exhaustive]
44pub enum EngineError {
45 /// A uniquely-identified resource did not exist. `entity` is a
46 /// stable label (e.g. `"execution"`, `"flow"`, `"attempt"`) that
47 /// consumers can match without re-parsing a message.
48 #[error("not found: {entity}")]
49 NotFound { entity: &'static str },
50
51 /// Caller supplied a malformed, out-of-range, or otherwise
52 /// rejected input. `detail` carries the Lua-side payload (field
53 /// name, offending value, or CSV of missing tokens, depending on
54 /// `kind`).
55 #[error("validation: {kind:?}: {detail}")]
56 Validation {
57 kind: ValidationKind,
58 detail: String,
59 },
60
61 /// Transient conflict with another worker or with the current
62 /// state of the execution/flow. Caller should retry per
63 /// RFC-010 §10.7.
64 #[error("contention: {0:?}")]
65 Contention(ContentionKind),
66
67 /// Permanent conflict — the requested mutation conflicts with
68 /// an existing record (e.g. duplicate edge, cycle, already-in-flow).
69 /// Caller must not blindly retry.
70 #[error("conflict: {0:?}")]
71 Conflict(ConflictKind),
72
73 /// Legal but surprising state — lease expired, already-suspended,
74 /// duplicate-signal, budget-exceeded, etc. Per-variant semantics
75 /// documented on [`StateKind`].
76 #[error("state: {0:?}")]
77 State(StateKind),
78
79 /// FF-internal invariant violation that should not be reachable
80 /// in a correctly-behaving deployment. Consumers typically log
81 /// and surface as a 5xx.
82 #[error("bug: {0:?}")]
83 Bug(BugKind),
84
85 /// Backend transport fault or response-parse failure (RFC-012 §4.2
86 /// round-4 shape). Broadened in Stage 0 to carry `Box<dyn Error>`
87 /// so non-Valkey backends (Postgres, future) can route their
88 /// native transport errors through this variant without going via
89 /// `ScriptError`.
90 ///
91 /// * `backend` — static diagnostic label (`"valkey"`, `"postgres"`,
92 /// etc.). Kept `&'static str` to avoid heap alloc on construction.
93 /// * `source` — boxed error. For the Valkey backend this is
94 /// `ff_script::error::ScriptError`; downcast with
95 /// `source.downcast_ref::<ScriptError>()` to recover
96 /// `ferriskey::ErrorKind` / parse detail. Helper lives in
97 /// `ff_script::engine_error_ext::transport_script_ref`.
98 #[error("transport ({backend}): {source}")]
99 Transport {
100 backend: &'static str,
101 #[source]
102 source: Box<dyn std::error::Error + Send + Sync + 'static>,
103 },
104
105 /// Backend method not wired up yet (RFC-012 §4.2 K#7 holdover).
106 /// Returned by staged backend impls for methods that are known
107 /// types in the trait but not yet implemented. Graceful degradation
108 /// in place of `unimplemented!()` panics. Additive; does not
109 /// participate in the `From<ScriptError>` mapping.
110 #[error("unavailable: {op}")]
111 Unavailable { op: &'static str },
112
113 /// Backend-owned concurrency pool reached its ceiling (RFC-017 §6).
114 /// `pool` is a stable label (`"stream_ops"`, `"admin_rotate"`, …);
115 /// `max` is the pool ceiling; `retry_after_ms`, when set, is an
116 /// advisory retry hint the backend computed from its own back-
117 /// pressure signal. Maps to HTTP 429 at the `ff-server` boundary.
118 #[error("resource exhausted: pool={pool} max={max}")]
119 ResourceExhausted {
120 pool: &'static str,
121 max: u32,
122 retry_after_ms: Option<u32>,
123 },
124
125 /// An operation ran past its deadline (RFC-017 §5.4
126 /// `shutdown_prepare`). `op` is a stable label, `elapsed` is how
127 /// long the operation ran before the caller aborted. Additive;
128 /// call sites that previously did not emit this variant keep
129 /// emitting whatever they emitted before.
130 #[error("timeout: op={op} elapsed={elapsed:?}")]
131 Timeout {
132 op: &'static str,
133 elapsed: std::time::Duration,
134 },
135
136 /// An inner [`EngineError`] wrapped with a call-site label so
137 /// operators triaging logs can see which op the error came from
138 /// without inferring from surrounding spans. Constructed via
139 /// [`backend_context`]; carries a lightweight string context
140 /// (e.g. `"renew: FCALL ff_renew_lease"`).
141 ///
142 /// Classification helpers (`ErrorClass`, `BackendErrorKind`,
143 /// etc.) transparently descend into `source` so a consumer that
144 /// matches on the wrapper arm keeps the same retry/terminal
145 /// semantics as the unwrapped inner error.
146 #[error("{context}: {source}")]
147 Contextual {
148 #[source]
149 source: Box<EngineError>,
150 context: String,
151 },
152}
153
154/// Wrap an [`EngineError`] with a call-site label when the error is
155/// a transport-family fault — `Transport` or `Unavailable`. Typed
156/// classifications (`NotFound`, `Validation`, `Contention`,
157/// `Conflict`, `State`, `Bug`) form the public contract boundary
158/// for consumers that `match` on the variant, so we return them
159/// unchanged. Repeated wraps on an already-`Contextual` error
160/// nest an additional layer; callers should wrap once per op
161/// boundary.
162///
163/// Promoted to ff-core so `ff-backend-valkey` can annotate its
164/// `EngineBackend` impls with the same context shape ff-sdk's
165/// snapshot helpers use (issue #154).
166pub fn backend_context(err: EngineError, context: impl Into<String>) -> EngineError {
167 match err {
168 EngineError::Transport { .. }
169 | EngineError::Unavailable { .. }
170 | EngineError::ResourceExhausted { .. }
171 | EngineError::Timeout { .. }
172 | EngineError::Contextual { .. } => EngineError::Contextual {
173 source: Box::new(err),
174 context: context.into(),
175 },
176 // Typed classifications are part of the public contract;
177 // wrapping them would break `match` call sites that inspect
178 // the inner variant (e.g. tests asserting
179 // `EngineError::Validation { kind: Corruption, .. }`).
180 other => other,
181 }
182}
183
184/// Validation sub-kinds. 1:1 with the Lua validation codes.
185#[derive(Debug, Clone, PartialEq, Eq)]
186#[non_exhaustive]
187pub enum ValidationKind {
188 /// Generic caller-supplied input rejected (field-name detail).
189 InvalidInput,
190 /// Worker caps do not satisfy execution's required_capabilities.
191 /// `detail` is the sorted-CSV of missing tokens.
192 CapabilityMismatch,
193 /// Malformed/oversized capability list.
194 InvalidCapabilities,
195 /// `policy_json` not valid JSON or structurally wrong.
196 InvalidPolicyJson,
197 /// Signal payload > 64KB.
198 PayloadTooLarge,
199 /// Max signals per execution reached.
200 SignalLimitExceeded,
201 /// MAC verification failed on waitpoint_key.
202 InvalidWaitpointKey,
203 /// HMAC verification failed on a bearer waitpoint_token (signal
204 /// delivery path). Preserved as a distinct variant so the REST
205 /// layer can surface the Lua code `invalid_token` verbatim.
206 InvalidToken,
207 /// Pending waitpoint has no HMAC token field.
208 WaitpointNotTokenBound,
209 /// Frame > 64KB.
210 RetentionLimitExceeded,
211 /// Lease/attempt binding mismatch on suspend.
212 InvalidLeaseForSuspend,
213 /// Dependency edge not found / invalid dependency ref.
214 InvalidDependency,
215 /// Waitpoint/execution binding mismatch.
216 InvalidWaitpointForExecution,
217 /// Unrecognized blocking reason.
218 InvalidBlockingReason,
219 /// Invalid stream ID offset.
220 InvalidOffset,
221 /// Auth failed.
222 Unauthorized,
223 /// Budget scope malformed.
224 InvalidBudgetScope,
225 /// Operator privileges required.
226 BudgetOverrideNotAllowed,
227 /// Malformed quota definition.
228 InvalidQuotaSpec,
229 /// Rotation kid must be non-empty and dot-free.
230 InvalidKid,
231 /// Rotation secret must be non-empty even-length hex.
232 InvalidSecretHex,
233 /// Rotation grace_ms must be a non-negative integer.
234 InvalidGraceMs,
235 /// Tag key violates reserved-namespace rule.
236 InvalidTagKey,
237 /// Unrecognized stream frame type.
238 InvalidFrameType,
239 /// On-disk corruption or protocol drift: an engine-owned hash /
240 /// key returned a field shape the decoder could not parse (missing
241 /// required field, malformed timestamp, unknown extra field,
242 /// cross-field identity mismatch, etc.). `detail` carries the
243 /// decoder's diagnostic string — the specific field name and/or
244 /// offending value — in the form
245 /// `"<context>: <field?>: <message>"` so operators can locate the
246 /// bad key without reparsing.
247 ///
248 /// Classified as `Terminal`: a consumer retrying the read will
249 /// see the same bytes. Surface to the operator; do not loop.
250 Corruption,
251 /// The [`crate::backend::Handle`] presented to a backend op was
252 /// minted by a different backend (e.g. a Valkey-tagged handle
253 /// passed to the Postgres backend). RFC-v0.7 Wave 1c: cross-backend
254 /// migration tooling emits Handles from one backend that must not
255 /// decode as the other; backends detect the mismatch at op entry
256 /// and return this variant.
257 ///
258 /// `detail` carries `"expected=<tag> actual=<tag>"` for operator
259 /// diagnostics.
260 HandleFromOtherBackend,
261}
262
263/// Contention sub-kinds (retryable per RFC-010 §10.7). Caller should
264/// re-dispatch or re-read and retry.
265#[derive(Debug, Clone, PartialEq, Eq)]
266#[non_exhaustive]
267pub enum ContentionKind {
268 /// Re-dispatch to `claim_resumed_execution`.
269 UseClaimResumedExecution,
270 /// Re-dispatch to `claim_execution`.
271 NotAResumedExecution,
272 /// State changed since grant. Request new grant.
273 ExecutionNotLeaseable,
274 /// Another worker holds lease. Request a different execution.
275 LeaseConflict,
276 /// Grant missing/mismatched. Request new grant.
277 InvalidClaimGrant,
278 /// Grant TTL elapsed. Request new grant.
279 ClaimGrantExpired,
280 /// No execution currently available.
281 NoEligibleExecution,
282 /// Waitpoint may not exist yet. Retry with backoff.
283 WaitpointNotFound,
284 /// Route to buffer_signal_for_pending_waitpoint.
285 WaitpointPendingUseBufferScript,
286 /// Graph revision changed. Re-read adjacency, retry.
287 StaleGraphRevision,
288 /// Execution is not in `active` state (lease superseded, etc.)
289 /// Carries the Lua-side detail payload for replay reconciliation.
290 ExecutionNotActive {
291 terminal_outcome: String,
292 lease_epoch: String,
293 lifecycle_phase: String,
294 attempt_id: String,
295 },
296 /// State changed. Scheduler skips.
297 ExecutionNotEligible,
298 /// Removed by another scheduler.
299 ExecutionNotInEligibleSet,
300 /// Already reclaimed/cancelled. Skip.
301 ExecutionNotReclaimable,
302 /// Target has no active lease (already revoked/expired/unowned).
303 NoActiveLease,
304 /// Window full; caller should backoff `retry_after_ms`.
305 RateLimitExceeded,
306 /// Concurrency cap hit.
307 ConcurrencyLimitExceeded,
308 /// Returned after 3 attempts of a SERIALIZABLE transaction in
309 /// Postgres (`cancel_flow`, `deliver_signal`, `suspend`). Caller
310 /// falls back to the appropriate reconciler.
311 ///
312 /// Classified `Retryable` via the blanket `Contention(_)` arm so
313 /// consumer retry-loops don't treat it as terminal; the
314 /// reconciler backstop catches repeat exhaustion.
315 RetryExhausted,
316}
317
318/// Permanent conflict sub-kinds. Caller must reconcile rather than
319/// retry.
320#[derive(Debug, Clone, PartialEq, Eq)]
321#[non_exhaustive]
322pub enum ConflictKind {
323 /// Dependency edge already exists. Carries the pre-existing
324 /// [`EdgeSnapshot`] so callers implementing "409 on re-declare
325 /// with different kind/ref" don't need a follow-up read.
326 ///
327 /// Note: the plain `From<ScriptError> for EngineError` impl
328 /// cannot populate `existing` (that requires an async
329 /// `describe_edge` round trip), so it falls through to
330 /// `EngineError::Transport`. Callers on the `stage_dependency`
331 /// path use `ff_sdk::engine_error::enrich_dependency_conflict`
332 /// to perform the follow-up read and promote the error.
333 ///
334 /// [`EdgeSnapshot`]: crate::contracts::EdgeSnapshot
335 DependencyAlreadyExists {
336 existing: crate::contracts::EdgeSnapshot,
337 },
338 /// Edge would create a cycle.
339 CycleDetected,
340 /// Self-referencing edge (upstream == downstream).
341 SelfReferencingEdge,
342 /// Execution is already a member of another flow.
343 ExecutionAlreadyInFlow,
344 /// Waitpoint already exists (pending or active).
345 WaitpointAlreadyExists,
346 /// Budget already attached or conflicts.
347 BudgetAttachConflict,
348 /// Quota policy already attached.
349 QuotaAttachConflict,
350 /// Rotation: same kid already installed with a different secret.
351 /// String is the conflicting kid.
352 RotationConflict(String),
353 /// Invariant violation: active attempt already exists where one
354 /// was expected absent.
355 ActiveAttemptExists,
356}
357
358/// Legal-but-surprising state sub-kinds. Per-variant semantics vary
359/// (some are benign no-ops, some are terminal). Consult the RFC-010
360/// §10.7 classification table.
361#[derive(Debug, Clone, PartialEq, Eq)]
362#[non_exhaustive]
363pub enum StateKind {
364 /// Lease superseded by reclaim.
365 StaleLease,
366 /// Lease TTL elapsed.
367 LeaseExpired,
368 /// Operator revoked lease.
369 LeaseRevoked,
370 /// Already resumed/cancelled. No-op.
371 ExecutionNotSuspended,
372 /// Open suspension already active. No-op.
373 AlreadySuspended,
374 /// Signal too late — waitpoint already closed.
375 WaitpointClosed,
376 /// Execution not suspended; no valid signal target.
377 TargetNotSignalable,
378 /// Signal already delivered (dedup).
379 DuplicateSignal,
380 /// Resume conditions not satisfied.
381 ResumeConditionNotMet,
382 /// Waitpoint not in pending state.
383 WaitpointNotPending,
384 /// Pending waitpoint aged out before suspension committed.
385 PendingWaitpointExpired,
386 /// Waitpoint is not in an open state.
387 WaitpointNotOpen,
388 /// Cannot replay non-terminal execution.
389 ExecutionNotTerminal,
390 /// Replay limit reached.
391 MaxReplaysExhausted,
392 /// Attempt terminal; no appends.
393 StreamClosed,
394 /// Lease mismatch on stream append.
395 StaleOwnerCannotAppend,
396 /// Grant already issued. Skip.
397 GrantAlreadyExists,
398 /// Execution not in specified flow.
399 ExecutionNotInFlow,
400 /// Flow already in terminal state.
401 FlowAlreadyTerminal,
402 /// Dependencies not yet satisfied.
403 DepsNotSatisfied,
404 /// Not blocked by dependencies.
405 NotBlockedByDeps,
406 /// Execution not runnable.
407 NotRunnable,
408 /// Execution already terminal.
409 Terminal,
410 /// Hard budget limit reached.
411 BudgetExceeded,
412 /// Soft budget limit reached (warning; continue).
413 BudgetSoftExceeded,
414 /// Usage seq already processed. No-op.
415 OkAlreadyApplied,
416 /// Attempt not in started state.
417 AttemptNotStarted,
418 /// Attempt already ended. No-op.
419 AttemptAlreadyTerminal,
420 /// Wrong state for new attempt.
421 ExecutionNotEligibleForAttempt,
422 /// Execution not terminal or replay limit reached.
423 ReplayNotAllowed,
424 /// Retry limit reached.
425 MaxRetriesExhausted,
426 /// Already closed. No-op.
427 StreamAlreadyClosed,
428 /// RFC-013 Stage 1d — strict `suspend` path refuses the
429 /// early-satisfied branch. The underlying backend outcome is
430 /// [`crate::contracts::SuspendOutcome::AlreadySatisfied`]; only the
431 /// SDK's strict `ClaimedTask::suspend` wrapper maps it to this
432 /// error. `ClaimedTask::try_suspend` returns the outcome directly.
433 AlreadySatisfied,
434}
435
436/// FF-internal invariant-violation sub-kinds. Should not be reachable
437/// in a correctly-behaving deployment.
438#[derive(Debug, Clone, PartialEq, Eq)]
439#[non_exhaustive]
440pub enum BugKind {
441 /// `attempt_not_in_created_state`: internal sequencing error.
442 AttemptNotInCreatedState,
443}
444
445/// Backend-agnostic transport error carried across public
446/// ff-sdk / ff-server error surfaces (#88).
447///
448/// The `Valkey` variant is the only one populated today; additional
449/// variants (e.g. `Postgres`) will be added additively as other
450/// backends land. The enum is `#[non_exhaustive]` so consumers must
451/// include a wildcard arm.
452///
453/// Construction from the Valkey-native `ferriskey::Error` lives in
454/// `ff_backend_valkey::backend_error_from_ferriskey` — keeping that
455/// conversion outside ff-core preserves ff-core's ferriskey-free
456/// public surface.
457#[derive(Debug, Clone, thiserror::Error)]
458#[non_exhaustive]
459pub enum BackendError {
460 /// Valkey-backend transport failure. Carries a backend-agnostic
461 /// classification plus the backend-rendered message so downstream
462 /// consumers can inspect without depending on ferriskey.
463 #[error("valkey backend: {kind:?}: {message}")]
464 Valkey {
465 kind: BackendErrorKind,
466 message: String,
467 },
468}
469
470impl BackendError {
471 /// Returns the classified backend kind if this error is a Valkey
472 /// transport fault. Forward-compatible with future backends:
473 /// non-Valkey variants return `None` on a call that names only the
474 /// Valkey kind; code that wants a backend-specific view should
475 /// match directly on [`BackendError`].
476 pub fn kind(&self) -> BackendErrorKind {
477 match self {
478 Self::Valkey { kind, .. } => *kind,
479 }
480 }
481
482 /// Return the backend-rendered message payload.
483 pub fn message(&self) -> &str {
484 match self {
485 Self::Valkey { message, .. } => message.as_str(),
486 }
487 }
488}
489
490/// Classified backend transport errors, kept backend-agnostic on
491/// purpose (#88). Each variant maps a family of native backend error
492/// kinds into a stable, consumer-matchable shape.
493///
494/// Consumers requiring the exact native kind for a Valkey backend
495/// must go through `ff_backend_valkey` explicitly; ff-sdk/ff-server's
496/// public surface will only ever hand out [`BackendErrorKind`].
497#[derive(Debug, Clone, Copy, PartialEq, Eq)]
498#[non_exhaustive]
499pub enum BackendErrorKind {
500 /// Network / I/O failure: the request may or may not have been
501 /// processed. Typically retryable with backoff.
502 Transport,
503 /// Backend rejected the request on protocol / parse grounds. Not
504 /// retryable without a fix.
505 Protocol,
506 /// Backend timed out responding to the request. Retryable.
507 Timeout,
508 /// Authentication / authorization failure. Not retryable.
509 Auth,
510 /// Cluster topology churn (MOVED, ASK, CLUSTERDOWN, MasterDown,
511 /// CrossSlot, ConnectionNotFoundForRoute, AllConnectionsUnavailable).
512 /// Retryable after topology settles.
513 Cluster,
514 /// Backend is temporarily busy loading state (e.g. Valkey
515 /// `LOADING`). Retryable.
516 BusyLoading,
517 /// Backend indicates the referenced script/function does not
518 /// exist. Typically handled by the caller via re-load.
519 ScriptNotLoaded,
520 /// Any other classified error from the backend. Fallback bucket
521 /// for native kinds outside the curated set above.
522 Other,
523}
524
525impl BackendErrorKind {
526 /// Stable, lowercase-kebab label suitable for log fields / HTTP
527 /// `kind` body slots. Guaranteed not to change across releases
528 /// for the existing variants.
529 pub fn as_stable_str(&self) -> &'static str {
530 match self {
531 Self::Transport => "transport",
532 Self::Protocol => "protocol",
533 Self::Timeout => "timeout",
534 Self::Auth => "auth",
535 Self::Cluster => "cluster",
536 Self::BusyLoading => "busy_loading",
537 Self::ScriptNotLoaded => "script_not_loaded",
538 Self::Other => "other",
539 }
540 }
541
542 /// Whether a caller should consider this kind retryable with
543 /// backoff. Conservative — auth + protocol + other are terminal.
544 pub fn is_retryable(&self) -> bool {
545 matches!(
546 self,
547 Self::Transport | Self::Timeout | Self::Cluster | Self::BusyLoading
548 )
549 }
550}
551
552impl EngineError {
553 /// Classify an [`EngineError`] using the underlying
554 /// [`ErrorClass`] table.
555 ///
556 /// **Transport classification in ff-core:** the inner source is
557 /// `Box<dyn std::error::Error>` which ff-core cannot downcast
558 /// without naming `ScriptError`. ff-core returns `Terminal` for
559 /// every `Transport` variant by default. Callers needing the
560 /// Retryable-on-transient-Valkey-error classification use
561 /// `ff_script::engine_error_ext::class` which downcasts to
562 /// `ScriptError` and delegates to `ScriptError::class`. ff-sdk's
563 /// public `SdkError::is_retryable` / `backend_kind` methods wire
564 /// the ff-script helper in so consumers retain the Phase-1
565 /// behavior transparently. (`backend_kind` was renamed from
566 /// `valkey_kind` in #88.)
567 pub fn class(&self) -> ErrorClass {
568 match self {
569 Self::NotFound { .. } => ErrorClass::Terminal,
570 Self::Validation { .. } => ErrorClass::Terminal,
571 Self::Contention(_) => ErrorClass::Retryable,
572 Self::Conflict(_) => ErrorClass::Terminal,
573 Self::State(StateKind::BudgetExceeded) => ErrorClass::Cooperative,
574 Self::State(
575 StateKind::ExecutionNotSuspended
576 | StateKind::AlreadySuspended
577 | StateKind::AlreadySatisfied
578 | StateKind::WaitpointClosed
579 | StateKind::DuplicateSignal
580 | StateKind::GrantAlreadyExists
581 | StateKind::OkAlreadyApplied
582 | StateKind::AttemptAlreadyTerminal
583 | StateKind::StreamAlreadyClosed
584 | StateKind::BudgetSoftExceeded
585 | StateKind::WaitpointNotOpen
586 | StateKind::WaitpointNotPending
587 | StateKind::PendingWaitpointExpired
588 | StateKind::NotBlockedByDeps
589 | StateKind::DepsNotSatisfied,
590 ) => ErrorClass::Informational,
591 Self::State(_) => ErrorClass::Terminal,
592 Self::Bug(_) => ErrorClass::Bug,
593 // ff-core cannot name ScriptError. Safe default: Terminal.
594 // ff-script's engine_error_ext::class upgrades to
595 // ScriptError::class when the inner source is a
596 // ScriptError.
597 Self::Transport { .. } => ErrorClass::Terminal,
598 // Unavailable is terminal at the call site — the method is
599 // not implemented; the caller must either fall back to a
600 // different code path or surface to the user.
601 Self::Unavailable { .. } => ErrorClass::Terminal,
602 // Resource exhaustion is retryable — the ceiling is a
603 // transient server-side gate; callers back off and try
604 // again. Mirrors RFC-017 §6 and ServerError::is_retryable
605 // for the pre-migration `ConcurrencyLimitExceeded` arm.
606 Self::ResourceExhausted { .. } => ErrorClass::Retryable,
607 // Timeouts surface as terminal from the caller's POV —
608 // the specific op exceeded its budget; a retry is the
609 // caller's decision, not the error's classification.
610 Self::Timeout { .. } => ErrorClass::Terminal,
611 // Descend into the wrapped error — context is diagnostic;
612 // classification follows the inner cause.
613 Self::Contextual { source, .. } => source.class(),
614 }
615 }
616}
617
618#[cfg(test)]
619mod tests {
620 use super::*;
621
622 #[test]
623 fn class_contention_is_retryable() {
624 let err = EngineError::Contention(ContentionKind::LeaseConflict);
625 assert_eq!(err.class(), ErrorClass::Retryable);
626 }
627
628 #[test]
629 fn class_budget_exceeded_is_cooperative() {
630 let err = EngineError::State(StateKind::BudgetExceeded);
631 assert_eq!(err.class(), ErrorClass::Cooperative);
632 }
633
634 #[test]
635 fn class_duplicate_signal_is_informational() {
636 let err = EngineError::State(StateKind::DuplicateSignal);
637 assert_eq!(err.class(), ErrorClass::Informational);
638 }
639
640 #[test]
641 fn class_bug_variant() {
642 let err = EngineError::Bug(BugKind::AttemptNotInCreatedState);
643 assert_eq!(err.class(), ErrorClass::Bug);
644 }
645
646 #[test]
647 fn class_transport_defaults_terminal() {
648 // ff-core has no ScriptError downcast; Transport is Terminal
649 // until ff-script's engine_error_ext::class is called.
650 let raw = std::io::Error::other("simulated transport error");
651 let err = EngineError::Transport {
652 backend: "test",
653 source: Box::new(raw),
654 };
655 assert_eq!(err.class(), ErrorClass::Terminal);
656 }
657
658 #[test]
659 fn unavailable_is_terminal() {
660 assert_eq!(
661 EngineError::Unavailable { op: "foo" }.class(),
662 ErrorClass::Terminal
663 );
664 }
665
666 #[test]
667 fn backend_context_wraps_transport_and_preserves_typed() {
668 // Transport gets wrapped with the call-site label (issue #154).
669 let raw = std::io::Error::other("simulated transport error");
670 let wrapped = backend_context(
671 EngineError::Transport {
672 backend: "valkey",
673 source: Box::new(raw),
674 },
675 "renew: FCALL ff_renew_lease",
676 );
677 let rendered = format!("{wrapped}");
678 assert!(
679 rendered.starts_with("renew: FCALL ff_renew_lease: transport (valkey): "),
680 "expected context prefix, got: {rendered}"
681 );
682 // Unavailable also wraps so callers can still filter on the op.
683 let wrapped = backend_context(EngineError::Unavailable { op: "x" }, "ctx");
684 assert!(matches!(wrapped, EngineError::Contextual { .. }));
685
686 // Typed classifications pass through unchanged so existing
687 // `match` call sites keep working.
688 let inner = EngineError::Validation {
689 kind: ValidationKind::Corruption,
690 detail: "bad".into(),
691 };
692 let passthrough = backend_context(inner, "describe_edge: HGETALL edge");
693 match passthrough {
694 EngineError::Validation { kind, .. } => {
695 assert_eq!(kind, ValidationKind::Corruption);
696 }
697 other => panic!("expected Validation, got {other:?}"),
698 }
699 let inner = EngineError::Contention(ContentionKind::LeaseConflict);
700 assert_eq!(
701 backend_context(inner, "renew: FCALL ff_renew_lease").class(),
702 ErrorClass::Retryable
703 );
704 }
705
706 #[test]
707 fn backend_error_kind_round_trip() {
708 let be = BackendError::Valkey {
709 kind: BackendErrorKind::Transport,
710 message: "connection reset".into(),
711 };
712 assert_eq!(be.kind(), BackendErrorKind::Transport);
713 assert_eq!(be.message(), "connection reset");
714 }
715
716 #[test]
717 fn backend_kind_stable_strings_fixed() {
718 // Stability fence: these strings are part of the public
719 // contract (log field values, HTTP body `kind` slots). Adding
720 // a variant is additive; changing an existing string is a
721 // break.
722 assert_eq!(BackendErrorKind::Transport.as_stable_str(), "transport");
723 assert_eq!(BackendErrorKind::Protocol.as_stable_str(), "protocol");
724 assert_eq!(BackendErrorKind::Timeout.as_stable_str(), "timeout");
725 assert_eq!(BackendErrorKind::Auth.as_stable_str(), "auth");
726 assert_eq!(BackendErrorKind::Cluster.as_stable_str(), "cluster");
727 assert_eq!(
728 BackendErrorKind::BusyLoading.as_stable_str(),
729 "busy_loading"
730 );
731 assert_eq!(
732 BackendErrorKind::ScriptNotLoaded.as_stable_str(),
733 "script_not_loaded"
734 );
735 assert_eq!(BackendErrorKind::Other.as_stable_str(), "other");
736 }
737
738 #[test]
739 fn backend_kind_retryability() {
740 for k in [
741 BackendErrorKind::Transport,
742 BackendErrorKind::Timeout,
743 BackendErrorKind::Cluster,
744 BackendErrorKind::BusyLoading,
745 ] {
746 assert!(k.is_retryable(), "{k:?} should be retryable");
747 }
748 for k in [
749 BackendErrorKind::Protocol,
750 BackendErrorKind::Auth,
751 BackendErrorKind::ScriptNotLoaded,
752 BackendErrorKind::Other,
753 ] {
754 assert!(!k.is_retryable(), "{k:?} should NOT be retryable");
755 }
756 }
757}