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