Skip to main content

khive_db/
error.rs

1//! Error types for the SQLite storage layer.
2
3use std::time::Duration;
4
5use khive_storage::error::{SqliteWriteFailure, SqliteWriteStage};
6use khive_storage::{StorageCapability, StorageError, WriterTaskRequestState};
7use thiserror::Error;
8
9// Inspect only owned error shapes. User callbacks may supply cyclic or effectful
10// source() implementations; attaching evidence must not invoke those again.
11pub(crate) fn native_write_failure(
12    error: &(dyn std::error::Error + 'static),
13    stage: SqliteWriteStage,
14) -> Option<SqliteWriteFailure> {
15    if let Some(error) = error.downcast_ref::<StorageError>() {
16        return match error {
17            StorageError::SqliteWrite { failure, .. } => Some(*failure),
18            StorageError::Driver { source, .. } => native_write_failure(source.as_ref(), stage),
19            StorageError::WriterTaskRequestFailed { source, .. } => {
20                native_write_failure(source.as_ref(), stage)
21            }
22            _ => None,
23        };
24    }
25    if let Some(error) = error.downcast_ref::<SqliteError>() {
26        return match error {
27            SqliteError::Write { stage, source } => native_write_failure(source, *stage),
28            SqliteError::WriteSettlementUnknown { failure } => Some(*failure),
29            SqliteError::Rusqlite(source) => native_write_failure(source, stage),
30            _ => None,
31        };
32    }
33    if let Some(
34        rusqlite::Error::SqliteFailure(code, _)
35        | rusqlite::Error::SqlInputError { error: code, .. },
36    ) = error.downcast_ref::<rusqlite::Error>()
37    {
38        return Some(SqliteWriteFailure {
39            stage,
40            primary_code: code.extended_code & 0xff,
41            extended_code: code.extended_code,
42            settlement_unknown: false,
43        });
44    }
45    None
46}
47
48pub(crate) fn with_write_stage(error: StorageError, stage: SqliteWriteStage) -> StorageError {
49    match native_write_failure(&error, stage) {
50        Some(failure) => error.with_sqlite_write_failure(failure),
51        None => error,
52    }
53}
54
55pub(crate) fn statement_failure(error: StorageError) -> StorageError {
56    with_write_stage(error, SqliteWriteStage::Statement)
57}
58
59pub(crate) fn unknown_write_settlement(mut error: StorageError) -> StorageError {
60    if let StorageError::SqliteWrite { failure, .. } = &mut error {
61        failure.settlement_unknown = true;
62    }
63    error
64}
65
66/// Stable ADR-194 capacity stages. The refusal stage is reserved for the WAL
67/// I/O limiter; this configuration-only slice emits only unavailable.
68pub const SQLITE_WAL_CAPACITY_REFUSED_STAGE: &str = "sqlite_wal_capacity_refused";
69pub const SQLITE_WAL_CAPACITY_UNAVAILABLE_STAGE: &str = "sqlite_wal_capacity_unavailable";
70
71/// Errors produced by the SQLite storage backend.
72#[derive(Debug, Error)]
73pub enum SqliteError {
74    #[error("strict writer routing refused a direct logical write: {operation}")]
75    WriterRouteViolation { operation: &'static str },
76
77    #[error("sqlite error: {source}")]
78    Write {
79        stage: SqliteWriteStage,
80        #[source]
81        source: rusqlite::Error,
82    },
83    /// A request-scoped read or store acquisition stopped, or read cleanup failed.
84    #[error(transparent)]
85    RequestReadStopped(khive_storage::StorageError),
86
87    /// Underlying rusqlite driver error.
88    #[error("sqlite error: {0}")]
89    Rusqlite(#[from] rusqlite::Error),
90
91    /// Data invariant violation (corrupt row, unexpected schema state).
92    #[error("invalid data: {0}")]
93    InvalidData(String),
94
95    /// A pooled connection contained a transaction from an earlier owner.
96    /// Its prior side effects cannot be attributed to the new request.
97    #[error("pooled writer contains an inherited transaction; prior side effects are unknown")]
98    InheritedWriterTransaction,
99
100    /// The writer could not prove transaction settlement before retirement.
101    #[error("writer transaction settlement is unknown; connection retired")]
102    WriterSettlementUnknown,
103
104    /// Source-free native evidence retained when cleanup cannot prove settlement.
105    #[error("writer transaction settlement is unknown; connection retired")]
106    WriteSettlementUnknown { failure: SqliteWriteFailure },
107
108    /// An earlier write on this database could not prove its settlement, so
109    /// every later write is refused before it starts. Only the write whose
110    /// settlement failed reports an unknown outcome; this one never ran.
111    #[error("writer refused: an earlier write's settlement is unknown; this write did not start")]
112    WriterPoisoned,
113
114    /// The process-local writer mutex was not acquired within the pool's
115    /// configured finite checkout deadline. This stage happens before SQLite
116    /// executes, so callers must not conflate it with SQLite busy/locked or
117    /// checkpoint starvation.
118    ///
119    /// The display text intentionally retains the historical `InvalidData`
120    /// prefix for compatibility while the variant supplies stable structural
121    /// classification (ADR-135 F6).
122    #[error("invalid data: timed out after {timeout:?} waiting for sqlite writer connection")]
123    WriterPoolCheckoutTimeout {
124        /// Pool checkout deadline that elapsed.
125        timeout: Duration,
126    },
127
128    /// A file-backed writer was refused before SQLite began the operation
129    /// because the volume's free space had reached its configured reserve.
130    #[error(
131        "refusing sqlite write on {volume}: {available_bytes} bytes available, \
132         at or below the {floor_bytes}-byte free-space floor plus \
133         {required_headroom_bytes} bytes of operation headroom"
134    )]
135    CapacityFloor {
136        volume: String,
137        available_bytes: u64,
138        floor_bytes: u64,
139        required_headroom_bytes: u64,
140    },
141
142    /// A new logical write could not resolve its volume, acquire its lease,
143    /// or sample available space.
144    #[error("sqlite capacity admission unavailable in {phase} phase: {message}")]
145    CapacityUnavailable {
146        phase: khive_storage::CapacityUnavailablePhase,
147        message: String,
148    },
149
150    /// The thread asking for a volume's write lease already holds it, so
151    /// waiting could never succeed. This is a nested write, not lock
152    /// contention, and it is refused at once instead of at the deadline.
153    #[error(
154        "volume lease re-entry: this thread already holds the lease for this volume \
155         (held at {holder_site}, requested again at {requester_site})"
156    )]
157    VolumeLeaseReentry {
158        holder_site: String,
159        requester_site: String,
160    },
161
162    /// A configured WAL ceiling cannot be represented by SQLite's signed
163    /// file-offset arithmetic.
164    #[error("invalid WAL ceiling {bytes} bytes: exceeds supported SQLite file offsets")]
165    WalCeilingOffsetOverflow { bytes: u64 },
166
167    /// A WAL ceiling was enabled for a backend that cannot produce a WAL.
168    #[error("invalid WAL ceiling {bytes} bytes: {backend_kind} does not support WAL enforcement")]
169    WalCeilingUnsupported {
170        bytes: u64,
171        backend_kind: &'static str,
172    },
173
174    /// One committed WAL frame cannot fit, even immediately after reset.
175    #[error(
176        "invalid WAL ceiling {bytes} bytes: page size {page_size} requires at least {minimum_bytes} bytes for one WAL frame"
177    )]
178    WalCeilingBelowMinimum {
179        bytes: u64,
180        page_size: u64,
181        minimum_bytes: u64,
182    },
183
184    /// A valid enabled policy cannot run until its WAL I/O limiter exists.
185    #[error(
186        "{stage}: WAL ceiling {bytes} bytes cannot be enforced: missing {capability}",
187        stage = SQLITE_WAL_CAPACITY_UNAVAILABLE_STAGE
188    )]
189    WalCapacityUnavailable {
190        bytes: u64,
191        capability: &'static str,
192    },
193
194    /// A `PoolConfig` value violated a validated invariant at configuration
195    /// load time (e.g. ADR-131 Decision 2's `write_admission_deadline_ms`
196    /// range). Fires before any connection is opened, and is never silently
197    /// clamped into range.
198    #[error("invalid config: {0}")]
199    InvalidConfig(String),
200
201    /// Filesystem I/O error.
202    #[error("io error: {0}")]
203    Io(#[from] std::io::Error),
204
205    /// A versioned migration failed to apply.
206    #[error("migration v{version} failed: {error}")]
207    Migration {
208        /// The migration version number that failed.
209        version: u32,
210        /// Human-readable description of the failure.
211        error: String,
212        /// The typed cause, when the failure came from an error value. It keeps
213        /// the native result code and write-stage evidence that `error` renders
214        /// as text.
215        #[source]
216        source: Option<Box<SqliteError>>,
217    },
218}
219
220impl SqliteError {
221    /// Attach a known write boundary while retaining the original native driver error.
222    pub fn write(error: rusqlite::Error, stage: SqliteWriteStage) -> Self {
223        if matches!(
224            error,
225            rusqlite::Error::SqliteFailure(..) | rusqlite::Error::SqlInputError { .. }
226        ) {
227            Self::Write {
228                stage,
229                source: error,
230            }
231        } else {
232            Self::Rusqlite(error)
233        }
234    }
235
236    pub(crate) fn settlement_with_cause(
237        error: &(dyn std::error::Error + 'static),
238        stage: SqliteWriteStage,
239    ) -> Self {
240        match native_write_failure(error, stage) {
241            Some(mut failure) => {
242                failure.settlement_unknown = true;
243                Self::WriteSettlementUnknown { failure }
244            }
245            None => Self::WriterSettlementUnknown,
246        }
247    }
248
249    pub fn write_failure(&self) -> Option<SqliteWriteFailure> {
250        match self {
251            Self::Write { stage, source } => native_write_failure(source, *stage),
252            Self::WriteSettlementUnknown { failure } => Some(*failure),
253            _ => None,
254        }
255    }
256    /// A migration failure that keeps its typed cause.
257    ///
258    /// The message is the cause's own display text, read before the cause is
259    /// converted into a `SqliteError`, so it reads exactly as it did when only
260    /// the text was kept. A driver error therefore keeps its bare driver text
261    /// instead of gaining the `sqlite error:` prefix of its wrapped form.
262    pub fn migration(version: u32, cause: impl std::fmt::Display + Into<SqliteError>) -> Self {
263        let error = cause.to_string();
264        Self::Migration {
265            version,
266            error,
267            source: Some(Box::new(cause.into())),
268        }
269    }
270
271    /// A migration failure with a message of its own that still keeps its
272    /// typed cause.
273    pub fn migration_with_cause(
274        version: u32,
275        message: impl Into<String>,
276        cause: impl Into<SqliteError>,
277    ) -> Self {
278        Self::Migration {
279            version,
280            error: message.into(),
281            source: Some(Box::new(cause.into())),
282        }
283    }
284
285    /// A migration failure that has no underlying error value.
286    pub fn migration_message(version: u32, message: impl Into<String>) -> Self {
287        Self::Migration {
288            version,
289            error: message.into(),
290            source: None,
291        }
292    }
293
294    /// The typed cause of a failed migration, when one was kept.
295    pub fn migration_cause(&self) -> Option<&SqliteError> {
296        match self {
297            Self::Migration { source, .. } => source.as_deref(),
298            _ => None,
299        }
300    }
301
302    /// The SQLite extended result code behind this error, when it carries one.
303    ///
304    /// Reads only owned shapes (the driver error, the write evidence and a
305    /// migration's kept cause) and never calls into `source()`, for the same
306    /// reason as `native_write_failure`.
307    pub fn native_extended_code(&self) -> Option<i32> {
308        match self {
309            Self::Rusqlite(source) | Self::Write { source, .. } => {
310                Self::driver_extended_code(source)
311            }
312            Self::WriteSettlementUnknown { failure } => Some(failure.extended_code),
313            Self::Migration { source, .. } => source
314                .as_deref()
315                .and_then(|cause| cause.native_extended_code()),
316            _ => None,
317        }
318    }
319
320    fn driver_extended_code(error: &rusqlite::Error) -> Option<i32> {
321        match error {
322            rusqlite::Error::SqliteFailure(code, _)
323            | rusqlite::Error::SqlInputError { error: code, .. } => Some(code.extended_code),
324            _ => None,
325        }
326    }
327
328    /// Stable structured stage for an ADR-194 WAL-capacity failure.
329    pub fn wal_capacity_stage(&self) -> Option<&'static str> {
330        match self {
331            Self::WalCapacityUnavailable { .. } => Some(SQLITE_WAL_CAPACITY_UNAVAILABLE_STAGE),
332            _ => None,
333        }
334    }
335
336    /// Capacity admission is a property of the SQLite file, so its refusals
337    /// carry `StorageCapability::Sql` whichever store requested the write.
338    /// Concrete backend callers use the same mapping as trait implementations:
339    /// capacity and writer-settlement failures retain their storage taxonomy,
340    /// and other failures remain typed sources of `StorageError::Driver`.
341    pub fn into_storage_error(
342        self,
343        capability: StorageCapability,
344        operation: &'static str,
345    ) -> StorageError {
346        match self {
347            Self::WriterRouteViolation { operation } => StorageError::WriterRouteViolation {
348                operation: operation.into(),
349            },
350            error @ Self::Write { stage, .. } => {
351                with_write_stage(StorageError::driver(capability, operation, error), stage)
352            }
353            Self::CapacityFloor {
354                volume,
355                available_bytes,
356                floor_bytes,
357                required_headroom_bytes,
358            } => StorageError::CapacityFloor {
359                capability: StorageCapability::Sql,
360                volume,
361                available_bytes,
362                floor_bytes,
363                required_headroom_bytes,
364            },
365            Self::CapacityUnavailable { phase, message } => StorageError::CapacityUnavailable {
366                capability: StorageCapability::Sql,
367                phase,
368                message,
369            },
370            Self::WriteSettlementUnknown { failure } => {
371                StorageError::writer_task_terminated(WriterTaskRequestState::SideEffectsUnknown)
372                    .with_sqlite_write_failure(failure)
373            }
374            Self::InheritedWriterTransaction | Self::WriterSettlementUnknown => {
375                StorageError::writer_task_terminated(WriterTaskRequestState::SideEffectsUnknown)
376            }
377            Self::WriterPoisoned => {
378                StorageError::writer_task_terminated(WriterTaskRequestState::NotStarted)
379            }
380            other => StorageError::driver(capability, operation, other),
381        }
382    }
383}
384
385#[cfg(test)]
386mod tests {
387    use super::*;
388    use khive_storage::CapacityUnavailablePhase;
389
390    #[test]
391    fn capacity_and_settlement_errors_keep_their_meaning_from_any_store() {
392        for capability in [StorageCapability::Entities, StorageCapability::Sql] {
393            let refused = SqliteError::CapacityFloor {
394                volume: "/volume".to_string(),
395                available_bytes: 99,
396                floor_bytes: 100,
397                required_headroom_bytes: 12,
398            }
399            .into_storage_error(capability, "write");
400            assert!(
401                matches!(
402                    refused,
403                    StorageError::CapacityFloor {
404                        capability: StorageCapability::Sql,
405                        available_bytes: 99,
406                        floor_bytes: 100,
407                        required_headroom_bytes: 12,
408                        ..
409                    }
410                ),
411                "{capability:?}: {refused:?}"
412            );
413
414            let unavailable = SqliteError::CapacityUnavailable {
415                phase: CapacityUnavailablePhase::LockContended,
416                message: "lease timed out".to_string(),
417            }
418            .into_storage_error(capability, "write");
419            assert!(
420                matches!(
421                    unavailable,
422                    StorageError::CapacityUnavailable {
423                        capability: StorageCapability::Sql,
424                        phase: CapacityUnavailablePhase::LockContended,
425                        ..
426                    }
427                ),
428                "{capability:?}: {unavailable:?}"
429            );
430
431            for unsettled in [
432                SqliteError::InheritedWriterTransaction,
433                SqliteError::WriterSettlementUnknown,
434            ] {
435                let mapped = unsettled.into_storage_error(capability, "write");
436                assert!(
437                    matches!(
438                        mapped,
439                        StorageError::WriterTaskTerminated {
440                            request_state: WriterTaskRequestState::SideEffectsUnknown,
441                            ..
442                        }
443                    ),
444                    "{capability:?}: {mapped:?}"
445                );
446            }
447
448            let refused = SqliteError::WriterPoisoned.into_storage_error(capability, "write");
449            assert!(
450                matches!(
451                    refused,
452                    StorageError::WriterTaskTerminated {
453                        request_state: WriterTaskRequestState::NotStarted,
454                        ..
455                    }
456                ),
457                "{capability:?}: {refused:?}"
458            );
459        }
460    }
461}