Skip to main content

khive_runtime/
audit_error.rs

1//! Closed, content-free classes on failed dispatch audit rows.
2//!
3//! This classification does not change retryability or domain disposition.
4//! Registry gate denials use `GateRefusal`; a handler's `PermissionDenied`
5//! uses `PolicyRefusal`. Historical rows without a class remain unclassified.
6
7use crate::error::{AuditObligationReason, RuntimeError};
8use khive_storage::StorageError;
9
10/// Stable additive audit vocabulary; unknown stored tokens are never internal errors.
11#[derive(Clone, Copy, Debug, Eq, PartialEq)]
12pub enum AuditErrorClass {
13    PolicyRefusal,
14    GateRefusal,
15    InvalidParams,
16    NotFoundOrNotAddressed,
17    DeadlineExceeded,
18    AdmissionExhausted,
19    Conflict,
20    Unsupported,
21    Configuration,
22    Storage,
23    Unavailable,
24    Internal,
25}
26
27impl AuditErrorClass {
28    pub const fn as_str(self) -> &'static str {
29        match self {
30            Self::PolicyRefusal => "policy_refusal",
31            Self::GateRefusal => "gate_refusal",
32            Self::InvalidParams => "invalid_params",
33            Self::NotFoundOrNotAddressed => "not_found_or_not_addressed",
34            Self::DeadlineExceeded => "deadline_exceeded",
35            Self::AdmissionExhausted => "admission_exhausted",
36            Self::Conflict => "conflict",
37            Self::Unsupported => "unsupported",
38            Self::Configuration => "configuration",
39            Self::Storage => "storage",
40            Self::Unavailable => "unavailable",
41            Self::Internal => "internal",
42        }
43    }
44
45    /// Read one exact known token. Absence and future/invalid tokens have no class.
46    pub fn from_token(token: &str) -> Option<Self> {
47        Some(match token {
48            "policy_refusal" => Self::PolicyRefusal,
49            "gate_refusal" => Self::GateRefusal,
50            "invalid_params" => Self::InvalidParams,
51            "not_found_or_not_addressed" => Self::NotFoundOrNotAddressed,
52            "deadline_exceeded" => Self::DeadlineExceeded,
53            "admission_exhausted" => Self::AdmissionExhausted,
54            "conflict" => Self::Conflict,
55            "unsupported" => Self::Unsupported,
56            "configuration" => Self::Configuration,
57            "storage" => Self::Storage,
58            "unavailable" => Self::Unavailable,
59            "internal" => Self::Internal,
60            _ => return None,
61        })
62    }
63}
64
65impl RuntimeError {
66    /// Classify an error returned by a handler, without rendering it.
67    /// Every runtime variant is named: adding a variant requires a classification.
68    pub fn audit_error_class(&self) -> AuditErrorClass {
69        use AuditErrorClass as C;
70        match self {
71            Self::CanonicalAdmission { source, .. } | Self::LintFix { source, .. } => {
72                source.audit_error_class()
73            }
74            Self::RefusedWithEvents { context } => context.source.audit_error_class(),
75            Self::BatchWrite { context } => context.source.audit_error_class(),
76            Self::WithResolution { context } => context.source.audit_error_class(),
77            Self::Storage(error) => storage_class(error),
78            Self::Query(error) => match error {
79                khive_query::QueryError::Parse { .. }
80                | khive_query::QueryError::Compile(_)
81                | khive_query::QueryError::Validation(_)
82                | khive_query::QueryError::InvalidInput(_) => C::InvalidParams,
83                khive_query::QueryError::Unsupported(_) => C::Unsupported,
84            },
85            Self::NotFound(_)
86            | Self::NamespaceMismatch { .. }
87            | Self::RemoteCacheMissing { .. } => C::NotFoundOrNotAddressed,
88            Self::InvalidInput(_)
89            | Self::UnknownVerb(_)
90            | Self::UnknownModel(_)
91            | Self::Ambiguous(_)
92            | Self::UnknownFusionStrategy(_)
93            | Self::AmbiguousPrefix { .. }
94            | Self::AmbiguousId { .. }
95            | Self::UnknownRemote { .. } => C::InvalidParams,
96            Self::Unconfigured(_)
97            | Self::IncompatibleEventStore(_)
98            | Self::MissingPackDependency(_)
99            | Self::MissingPackDependencies(_)
100            | Self::CircularPackDependency(_)
101            | Self::PackRedeclared { .. }
102            | Self::VerbCollision { .. }
103            | Self::ReservedEnvelopeParam { .. } => C::Configuration,
104            Self::CanonicalUnsupportedOperation { .. }
105            | Self::CrossBackendMergeUnsupported { .. } => C::Unsupported,
106            Self::PermissionDenied { .. }
107            | Self::SecretDetected(_)
108            | Self::CrossNamespaceWrite { .. }
109            | Self::WriteBudgetExceeded { .. }
110            | Self::RefusedWithReceipt(_) => C::PolicyRefusal,
111            Self::GuardedWriteFailed(_) => C::Conflict,
112            Self::DeadlineExceeded { .. } => C::DeadlineExceeded,
113            Self::GateUnavailable { .. } | Self::RemoteFetchError { .. } | Self::Embedding(_) => {
114                C::Unavailable
115            }
116            Self::Fusion(_) | Self::Internal(_) => C::Internal,
117            Self::Khive(error) => match error.kind() {
118                khive_types::ErrorKind::NotFound => C::NotFoundOrNotAddressed,
119                khive_types::ErrorKind::InvalidInput => C::InvalidParams,
120                khive_types::ErrorKind::Unauthorized => C::PolicyRefusal,
121                khive_types::ErrorKind::Conflict => {
122                    if self.is_stream_policy_refusal() {
123                        C::PolicyRefusal
124                    } else {
125                        C::Conflict
126                    }
127                }
128                khive_types::ErrorKind::Unavailable => C::Unavailable,
129                khive_types::ErrorKind::Internal => C::Internal,
130            },
131            Self::AuditObligation { failure, .. } => match failure.reason {
132                AuditObligationReason::GitDigestReceiptFailure => C::Internal,
133                AuditObligationReason::Terminal(reason) => {
134                    use crate::audit_batch::AuditTerminalReason as R;
135                    match reason {
136                        R::PreflightRejected => C::InvalidParams,
137                        R::AdmissionClosed | R::QueueAdmissionExhausted => C::AdmissionExhausted,
138                        R::AdmissionDeadlineExpired | R::ResolutionDeadlineExpired => {
139                            C::DeadlineExceeded
140                        }
141                        R::IdentityConflict => C::Conflict,
142                        R::StoreFailure | R::RetryExhausted | R::StoreWedged => C::Storage,
143                        R::IdempotencyUnsupported => C::Unsupported,
144                        R::DriverPanicked
145                        | R::DriverCancelled
146                        | R::DriverJoinLost
147                        | R::DriverExitedInconsistent
148                        | R::DriverAppendAbandoned => C::Internal,
149                    }
150                }
151            },
152        }
153    }
154}
155
156fn storage_class(error: &StorageError) -> AuditErrorClass {
157    use AuditErrorClass as C;
158    match error {
159        StorageError::SqliteWrite { source, .. }
160        | StorageError::WriterTaskRequestFailed { source, .. } => storage_class(source),
161        StorageError::NotFound { .. } => C::NotFoundOrNotAddressed,
162        StorageError::AlreadyExists { .. } | StorageError::Conflict { .. } => C::Conflict,
163        StorageError::InvalidInput { .. } | StorageError::BlobTooLarge { .. } => C::InvalidParams,
164        StorageError::Unsupported { .. } => C::Unsupported,
165        StorageError::Timeout { .. } | StorageError::ReadTransactionAgeEvicted { .. } => {
166            C::DeadlineExceeded
167        }
168        StorageError::AdmissionTimeout { .. }
169        | StorageError::WriteQueueFull { .. }
170        | StorageError::WriterTaskBusy { .. } => C::AdmissionExhausted,
171        StorageError::CapacityFloor { .. } => C::PolicyRefusal,
172        StorageError::WriterTaskNoRuntime => C::Configuration,
173        StorageError::Driver { source, .. } => {
174            if matches!(
175                source.downcast_ref::<khive_db::SqliteError>(),
176                Some(khive_db::SqliteError::WriterPoolCheckoutTimeout { .. })
177            ) {
178                C::AdmissionExhausted
179            } else {
180                C::Storage
181            }
182        }
183        StorageError::BlobSizeMismatch { .. }
184        | StorageError::BlobDigestMismatch { .. }
185        | StorageError::Pool { .. }
186        | StorageError::Transaction { .. }
187        | StorageError::ReadTransactionAgeEvictionCleanupFailed { .. }
188        | StorageError::Serialization { .. }
189        | StorageError::IndexMaintenance { .. }
190        | StorageError::WriterTaskTerminated { .. }
191        | StorageError::Internal(_)
192        | StorageError::CapacityUnavailable { .. } => C::Storage,
193    }
194}
195
196#[cfg(test)]
197mod tests {
198    use super::AuditErrorClass;
199    use crate::error::{BatchAdmissionReport, BatchRefusal, DomainDisposition, RuntimeError};
200    use khive_storage::{StorageError, WriterTaskRequestState};
201
202    #[test]
203    fn batch_write_delegates_audit_class_without_changing_settlement() {
204        for (source, expected) in [
205            (
206                RuntimeError::InvalidInput("fixture input".into()),
207                AuditErrorClass::InvalidParams,
208            ),
209            (
210                RuntimeError::NotFound("fixture target".into()),
211                AuditErrorClass::NotFoundOrNotAddressed,
212            ),
213            (
214                RuntimeError::Internal("fixture internal".into()),
215                AuditErrorClass::Internal,
216            ),
217        ] {
218            assert_eq!(
219                source.audit_error_class(),
220                expected,
221                "unwrapped source control"
222            );
223            let refusal = source.before_requested_write();
224            assert_eq!(
225                refusal.audit_error_class(),
226                expected,
227                "BatchWrite must retain the source audit class"
228            );
229            assert_eq!(
230                refusal.batch_write_disposition(),
231                Some(DomainDisposition::NotCommitted)
232            );
233        }
234
235        let admission = RuntimeError::InvalidInput("fixture admission".into())
236            .with_batch_admission(BatchAdmissionReport {
237                refused: vec![BatchRefusal {
238                    index: 0,
239                    field: "content",
240                    reason: "fixture-refusal",
241                }],
242                validation_complete: true,
243                unchecked_indices: vec![],
244            });
245        assert_eq!(
246            admission.audit_error_class(),
247            AuditErrorClass::InvalidParams
248        );
249        assert_eq!(
250            admission.batch_write_disposition(),
251            Some(DomainDisposition::NotCommitted)
252        );
253
254        for (state, expected) in [
255            (
256                WriterTaskRequestState::NotStarted,
257                DomainDisposition::NotCommitted,
258            ),
259            (
260                WriterTaskRequestState::TransactionRolledBack,
261                DomainDisposition::NotCommitted,
262            ),
263            (
264                WriterTaskRequestState::SideEffectsUnknown,
265                DomainDisposition::Unknown,
266            ),
267        ] {
268            let failure =
269                RuntimeError::atomic_write_failure(StorageError::WriterTaskRequestFailed {
270                    request_state: state,
271                    source: Box::new(StorageError::Internal("fixture write cause".into())),
272                });
273            assert_eq!(failure.audit_error_class(), AuditErrorClass::Storage);
274            assert_eq!(failure.batch_write_disposition(), Some(expected));
275        }
276
277        for (state, expected) in [
278            (
279                WriterTaskRequestState::NotStarted,
280                DomainDisposition::NotCommitted,
281            ),
282            (
283                WriterTaskRequestState::TransactionRolledBack,
284                DomainDisposition::NotCommitted,
285            ),
286            (
287                WriterTaskRequestState::SideEffectsUnknown,
288                DomainDisposition::Unknown,
289            ),
290        ] {
291            let failure =
292                RuntimeError::atomic_write_failure(StorageError::writer_task_terminated(state));
293            assert_eq!(failure.audit_error_class(), AuditErrorClass::Storage);
294            assert_eq!(failure.batch_write_disposition(), Some(expected));
295        }
296    }
297}