Skip to main content

scientific_workflow/persistence/local/
error.rs

1//! Errors produced by scientific-workflow persistence.
2//!
3//! This module owns diagnostic context for the complete persistence boundary:
4//! versioned metadata, observation integration, record decoding, output directories,
5//! immutable chunk files, bounded writer queues, and worker lifecycle. It does
6//! not redefine errors that belong to the in-memory data model. Instead,
7//! [`PersistenceError`] wraps [`ObservationError`] or [`StateSeriesError`] when persistence adds stream,
8//! record, or filesystem context to one of those failures.
9//!
10//! # Context ownership
11//!
12//! Paths, stream names, field names, indices, and validation explanations are
13//! owned by each error. An error therefore remains useful after its encoder,
14//! reader, writer, decoder, or run coordinator has been dropped. These
15//! allocations occur only on failure paths.
16//!
17//! # Source preservation
18//!
19//! IO, JSON, state access, series collection, custom field decoding, and
20//! terminal worker failures preserve their underlying errors through
21//! [`std::error::Error::source`]. Semantic format and lifecycle failures record
22//! their complete conflicting values directly because they have no lower-level
23//! source.
24//!
25//! # Responsibility boundary
26//!
27//! `PersistenceError` contains no scientific payload. In particular, a decoded
28//! state that violates a series invariant is dropped before its
29//! [`StateSeriesError`] is wrapped. Writer-terminal errors are shared through `Arc`
30//! so every blocked or later submitter can observe one authoritative failure
31//! without requiring `PersistenceError: Clone`.
32
33use std::error::Error;
34use std::io;
35use std::path::PathBuf;
36use std::sync::Arc;
37
38use thiserror::Error;
39
40use crate::observation::advanced::ObservationError;
41use crate::state::advanced::StateSeriesError;
42
43/// A failure encountered while encoding, writing, reading, or decoding a run.
44///
45/// Variants are grouped by the boundary that detects them: configuration and
46/// lifecycle, persisted-format validation, field processing, filesystem and
47/// JSON mechanics, and asynchronous writer coordination.
48///
49/// The enum is non-exhaustive so future integrity checks or durability modes
50/// can add precise variants without forcing downstream crates to exhaustively
51/// match every persistence failure.
52#[derive(Debug, Error)]
53#[non_exhaustive]
54pub enum PersistenceError {
55    /// The scientific observation layer rejected a plan or live observation.
56    #[error("scientific observation rejected the recording operation: {source}")]
57    Observation {
58        /// Original observation-layer failure.
59        #[source]
60        source: ObservationError,
61    },
62
63    // ---------------------------------------------------------------------
64    // Configuration and lifecycle
65    // ---------------------------------------------------------------------
66    /// A new recording refused to replace an existing path.
67    ///
68    /// Persistence never silently overwrites a previous recording. This crate
69    /// exposes no continuation or resume path for an existing directory.
70    #[error("recording directory `{path}` already exists")]
71    RecordingDirectoryExists {
72        /// Existing path that prevented recording creation.
73        path: PathBuf,
74    },
75
76    /// One persistence setting violates a constructor invariant.
77    ///
78    /// Settings represented by `NonZero*` types are rejected before this
79    /// point. This variant covers relationships between values, unsafe relative
80    /// paths, unsupported names, and similar semantic configuration failures.
81    #[error("invalid persistence setting `{setting}`: {reason}")]
82    InvalidConfiguration {
83        /// Stable setting name used by documentation and diagnostics.
84        setting: &'static str,
85        /// Concise explanation of the violated invariant.
86        reason: String,
87    },
88
89    /// Two logical output streams were configured with the same name.
90    #[error("output stream `{stream}` is configured more than once")]
91    DuplicateStateStream {
92        /// Repeated normalized stream name.
93        stream: String,
94    },
95
96    /// A caller selected a stream absent from the recording declaration.
97    #[error("recording does not declare state stream `{stream}`")]
98    UnknownStateStream {
99        /// Requested stream name.
100        stream: String,
101    },
102
103    /// The recording-wide writer has stopped accepting new work.
104    #[error("system-state writer has stopped accepting records")]
105    StateWriterClosed,
106
107    /// A caller repeated a recording operation after successful termination.
108    #[error("state recording has already finished")]
109    RecordingFinished,
110
111    /// Another writer currently owns the recording directory.
112    #[error("state recording `{path}` is already owned by another writer")]
113    RecordingDirectoryInUse {
114        /// Output root whose advisory exclusive lease could not be acquired.
115        path: PathBuf,
116    },
117
118    /// A completed stream contains no record to reconstruct.
119    #[error("stream `{stream}` contains no recorded state")]
120    NoRecordedState {
121        /// Logical completed stream searched for its latest state.
122        stream: String,
123    },
124
125    /// The host UTC clock could not be represented in the canonical metadata
126    /// timestamp format.
127    #[error("failed to format the operational timestamp while attempting to {operation}")]
128    OperationalTimestamp {
129        /// Lifecycle action requesting the timestamp.
130        operation: &'static str,
131        /// Timestamp-formatting failure.
132        #[source]
133        source: time::error::Format,
134    },
135
136    /// A monotonic writer session exceeded the exact persisted duration range.
137    #[error("active recording duration exceeds the supported u64 nanosecond range")]
138    OperationalDurationOverflow,
139
140    // ---------------------------------------------------------------------
141    // Persisted format and integrity
142    // ---------------------------------------------------------------------
143    /// `metadata.json` declares a format version this crate cannot read.
144    #[error(
145        "metadata file `{path}` uses format version {found}, but this crate supports version {supported}"
146    )]
147    UnsupportedVersion {
148        /// Metadata file containing the unsupported declaration.
149        path: PathBuf,
150        /// Version found in the file.
151        found: u32,
152        /// Version implemented by this crate.
153        supported: u32,
154    },
155
156    /// Syntactically valid metadata violates a semantic persistence invariant.
157    #[error("invalid recording metadata in `{path}`: {reason}")]
158    InvalidMetadata {
159        /// Authoritative metadata file that failed validation.
160        path: PathBuf,
161        /// Concise invariant violation.
162        reason: String,
163    },
164
165    /// A reader requiring a completed recording encountered terminally
166    /// unsuitable metadata.
167    #[error("recording metadata `{path}` does not declare successful completion")]
168    RecordingNotComplete {
169        /// Metadata file whose lifecycle state is incomplete or failed.
170        path: PathBuf,
171    },
172
173    /// A committed chunk named by metadata is absent from the filesystem.
174    #[error("committed chunk `{path}` is missing")]
175    MissingChunk {
176        /// Expected chunk path.
177        path: PathBuf,
178    },
179
180    /// A committed chunk's actual length differs from its metadata descriptor.
181    #[error("chunk `{path}` has {actual} bytes, but metadata declares {expected}")]
182    ChunkSizeMismatch {
183        /// Chunk path whose filesystem length was checked.
184        path: PathBuf,
185        /// Authoritative encoded byte length from metadata.
186        expected: u64,
187        /// Encoded byte length reported by the filesystem.
188        actual: u64,
189    },
190
191    /// A committed chunk's checksum differs from its metadata descriptor.
192    #[error("chunk `{path}` checksum is `{actual}`, but metadata declares `{expected}`")]
193    ChecksumMismatch {
194        /// Chunk path whose contents were checked.
195        path: PathBuf,
196        /// Authoritative checksum encoded in metadata.
197        expected: String,
198        /// Checksum computed from the chunk contents.
199        actual: String,
200    },
201
202    /// One syntactically readable JSONL record violates record invariants.
203    #[error("invalid record at line {line} of `{path}`: {reason}")]
204    InvalidRecord {
205        /// Chunk file containing the invalid record.
206        path: PathBuf,
207        /// One-based JSONL line number.
208        line: u64,
209        /// Concise framing or semantic invariant violation.
210        reason: String,
211    },
212
213    // ---------------------------------------------------------------------
214    // State borrowing, encoding, and decoding
215    // ---------------------------------------------------------------------
216    /// A decoder registration attempted to reuse one field key.
217    #[error("a payload decoder is already registered for field `{field}`")]
218    DuplicateDecoder {
219        /// Repeated state field key.
220        field: String,
221    },
222
223    /// No concrete payload decoder was declared for a persisted field key.
224    #[error("no payload decoder is registered for field `{field}`")]
225    MissingDecoder {
226        /// Persisted state field key requiring reconstruction.
227        field: String,
228    },
229
230    /// A user-supplied field decoder failed to reconstruct its concrete value.
231    #[error("failed to decode field `{field}` for stream `{stream}` at iteration {iteration}")]
232    DecodeField {
233        /// Logical stream being reconstructed.
234        stream: String,
235        /// Iteration of the raw record.
236        iteration: u64,
237        /// Field whose registered decoder failed.
238        field: String,
239        /// Decoder-specific failure retained behind an object-safe boundary.
240        #[source]
241        source: Box<dyn Error + Send + Sync + 'static>,
242    },
243
244    /// A reconstructed state violated its destination series invariant.
245    ///
246    /// The rejected state is intentionally not retained in this error: it was
247    /// created from persisted input and is dropped on failed reconstruction,
248    /// preventing an error value from pinning arbitrarily large payloads.
249    #[error("decoded state for stream `{stream}` at iteration {iteration} cannot enter its series")]
250    StateSeriesInvariant {
251        /// Logical stream being reconstructed.
252        stream: String,
253        /// Iteration of the rejected decoded state.
254        iteration: u64,
255        /// Original in-memory collection invariant failure.
256        #[source]
257        source: StateSeriesError,
258    },
259
260    // ---------------------------------------------------------------------
261    // Filesystem and JSON mechanics
262    // ---------------------------------------------------------------------
263    /// A filesystem operation failed.
264    #[error("failed to {operation} at `{path}`")]
265    Io {
266        /// Stable action description such as `create chunk` or `sync metadata`.
267        operation: &'static str,
268        /// Filesystem path involved in the failed operation.
269        path: PathBuf,
270        /// Underlying operating-system error.
271        #[source]
272        source: io::Error,
273    },
274
275    /// JSON framing, metadata serialization, or raw record parsing failed.
276    #[error("failed to {operation} JSON at `{path}`")]
277    Json {
278        /// Stable action description such as `parse metadata`.
279        operation: &'static str,
280        /// Metadata or chunk path associated with the JSON operation.
281        path: PathBuf,
282        /// Underlying Serde JSON failure.
283        #[source]
284        source: serde_json::Error,
285    },
286
287    /// Exact byte accounting overflowed its `u64` persisted representation.
288    #[error("encoded byte count overflowed while processing stream `{stream}`")]
289    ByteCountOverflow {
290        /// Logical stream whose accounting could not be represented.
291        stream: String,
292    },
293
294    /// One indivisible record exceeds the stream's strict queue-byte budget.
295    ///
296    /// Returning immediately is essential: waiting for capacity can never
297    /// make a record larger than the complete budget admissible.
298    #[error(
299        "encoded record for stream `{stream}` has {bytes} bytes, exceeding the queue limit of {limit}"
300    )]
301    RecordTooLarge {
302        /// Logical stream that rejected the encoded record.
303        stream: String,
304        /// Exact framed size of the rejected record.
305        bytes: u64,
306        /// Configured strict queue-byte limit.
307        limit: u64,
308    },
309
310    /// A stream submission did not advance its iteration.
311    #[error(
312        "record iteration {iteration} for stream `{stream}` does not follow previously accepted iteration {previous}"
313    )]
314    OutOfOrderIteration {
315        /// Logical stream receiving the record.
316        stream: String,
317        /// Rejected iteration.
318        iteration: u64,
319        /// Most recently accepted iteration.
320        previous: u64,
321    },
322
323    // ---------------------------------------------------------------------
324    // Queue and writer-worker lifecycle
325    // ---------------------------------------------------------------------
326    /// The bounded recording queue disconnected before shutdown completed.
327    #[error("system-state writer queue disconnected before shutdown completed")]
328    WriterQueueDisconnected,
329
330    /// The recording worker terminated with an authoritative persistence failure.
331    ///
332    /// The shared source lets multiple blocked submitters observe the same
333    /// terminal failure without cloning an IO or JSON error.
334    #[error("system-state writer terminated: {source}")]
335    StateWriterTerminated {
336        /// Shared authoritative worker failure.
337        #[source]
338        source: Arc<PersistenceError>,
339    },
340
341    /// Joining a writer thread revealed an unexpected panic.
342    #[error("system-state writer worker panicked")]
343    StateWriterPanicked,
344}