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::SearchRead { context } => context.source().audit_error_class(),
78            Self::Storage(error) => storage_class(error),
79            Self::Query(error) => match error {
80                khive_query::QueryError::Parse { .. }
81                | khive_query::QueryError::Compile(_)
82                | khive_query::QueryError::Validation(_)
83                | khive_query::QueryError::InvalidInput(_) => C::InvalidParams,
84                khive_query::QueryError::Unsupported(_) => C::Unsupported,
85            },
86            Self::NotFound(_)
87            | Self::NamespaceMismatch { .. }
88            | Self::RemoteCacheMissing { .. } => C::NotFoundOrNotAddressed,
89            Self::InvalidInput(_)
90            | Self::UnknownVerb(_)
91            | Self::UnknownModel(_)
92            | Self::Ambiguous(_)
93            | Self::UnknownFusionStrategy(_)
94            | Self::AmbiguousPrefix { .. }
95            | Self::AmbiguousId { .. }
96            | Self::UnknownRemote { .. } => C::InvalidParams,
97            Self::Unconfigured(_)
98            | Self::IncompatibleEventStore(_)
99            | Self::MissingPackDependency(_)
100            | Self::MissingPackDependencies(_)
101            | Self::CircularPackDependency(_)
102            | Self::PackRedeclared { .. }
103            | Self::VerbCollision { .. }
104            | Self::ReservedEnvelopeParam { .. }
105            | Self::AttachmentCutoverRequired { .. } => C::Configuration,
106            Self::CanonicalUnsupportedOperation { .. }
107            | Self::CrossBackendMergeUnsupported { .. } => C::Unsupported,
108            Self::PermissionDenied { .. }
109            | Self::SecretDetected(_)
110            | Self::CrossNamespaceWrite { .. }
111            | Self::WriteBudgetExceeded { .. }
112            | Self::RefusedWithReceipt(_) => C::PolicyRefusal,
113            Self::GuardedWriteFailed(_) => C::Conflict,
114            Self::DeadlineExceeded { .. } => C::DeadlineExceeded,
115            Self::GateUnavailable { .. } | Self::RemoteFetchError { .. } | Self::Embedding(_) => {
116                C::Unavailable
117            }
118            Self::Fusion(_) | Self::Internal(_) => C::Internal,
119            Self::Khive(error) => match error.kind() {
120                khive_types::ErrorKind::NotFound => C::NotFoundOrNotAddressed,
121                khive_types::ErrorKind::InvalidInput => C::InvalidParams,
122                khive_types::ErrorKind::Unauthorized => C::PolicyRefusal,
123                khive_types::ErrorKind::Conflict => {
124                    if self.is_stream_policy_refusal() {
125                        C::PolicyRefusal
126                    } else {
127                        C::Conflict
128                    }
129                }
130                khive_types::ErrorKind::Unavailable => C::Unavailable,
131                khive_types::ErrorKind::Internal => C::Internal,
132            },
133            Self::AuditObligation { failure, .. } => match failure.reason {
134                AuditObligationReason::GitDigestReceiptFailure => C::Internal,
135                AuditObligationReason::Terminal(reason) => {
136                    use crate::audit_batch::AuditTerminalReason as R;
137                    match reason {
138                        R::PreflightRejected => C::InvalidParams,
139                        R::AdmissionClosed | R::QueueAdmissionExhausted => C::AdmissionExhausted,
140                        R::AdmissionDeadlineExpired | R::ResolutionDeadlineExpired => {
141                            C::DeadlineExceeded
142                        }
143                        R::IdentityConflict => C::Conflict,
144                        R::StoreFailure | R::RetryExhausted | R::StoreWedged => C::Storage,
145                        R::IdempotencyUnsupported => C::Unsupported,
146                        R::DriverPanicked
147                        | R::DriverCancelled
148                        | R::DriverJoinLost
149                        | R::DriverExitedInconsistent
150                        | R::DriverAppendAbandoned => C::Internal,
151                    }
152                }
153            },
154        }
155    }
156}
157
158fn storage_class(error: &StorageError) -> AuditErrorClass {
159    use AuditErrorClass as C;
160    match error {
161        StorageError::SqliteWrite { source, .. }
162        | StorageError::WriterTaskRequestFailed { source, .. } => storage_class(source),
163        StorageError::NotFound { .. } => C::NotFoundOrNotAddressed,
164        StorageError::AlreadyExists { .. } | StorageError::Conflict { .. } => C::Conflict,
165        StorageError::InvalidInput { .. } | StorageError::BlobTooLarge { .. } => C::InvalidParams,
166        StorageError::Unsupported { .. } => C::Unsupported,
167        StorageError::Timeout { .. } | StorageError::ReadTransactionAgeEvicted { .. } => {
168            C::DeadlineExceeded
169        }
170        StorageError::AdmissionTimeout { .. }
171        | StorageError::WriteQueueFull { .. }
172        | StorageError::WriterTaskBusy { .. } => C::AdmissionExhausted,
173        StorageError::CapacityFloor { .. } => C::PolicyRefusal,
174        StorageError::WriterTaskNoRuntime => C::Configuration,
175        StorageError::Driver { source, .. } => {
176            if matches!(
177                source.downcast_ref::<khive_db::SqliteError>(),
178                Some(khive_db::SqliteError::WriterPoolCheckoutTimeout { .. })
179            ) {
180                C::AdmissionExhausted
181            } else {
182                C::Storage
183            }
184        }
185        StorageError::BlobSizeMismatch { .. }
186        | StorageError::BlobDigestMismatch { .. }
187        | StorageError::Pool { .. }
188        | StorageError::Transaction { .. }
189        | StorageError::ReadTransactionAgeEvictionCleanupFailed { .. }
190        | StorageError::Serialization { .. }
191        | StorageError::IndexMaintenance { .. }
192        | StorageError::WriterTaskTerminated { .. }
193        | StorageError::Internal(_)
194        | StorageError::CapacityUnavailable { .. } => C::Storage,
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    use super::AuditErrorClass;
201    use crate::error::{BatchAdmissionReport, BatchRefusal, DomainDisposition, RuntimeError};
202    use khive_storage::{StorageError, WriterTaskRequestState};
203
204    #[test]
205    fn batch_write_delegates_audit_class_without_changing_settlement() {
206        for (source, expected) in [
207            (
208                RuntimeError::InvalidInput("fixture input".into()),
209                AuditErrorClass::InvalidParams,
210            ),
211            (
212                RuntimeError::NotFound("fixture target".into()),
213                AuditErrorClass::NotFoundOrNotAddressed,
214            ),
215            (
216                RuntimeError::Internal("fixture internal".into()),
217                AuditErrorClass::Internal,
218            ),
219        ] {
220            assert_eq!(
221                source.audit_error_class(),
222                expected,
223                "unwrapped source control"
224            );
225            let refusal = source.before_requested_write();
226            assert_eq!(
227                refusal.audit_error_class(),
228                expected,
229                "BatchWrite must retain the source audit class"
230            );
231            assert_eq!(
232                refusal.batch_write_disposition(),
233                Some(DomainDisposition::NotCommitted)
234            );
235        }
236
237        let admission = RuntimeError::InvalidInput("fixture admission".into())
238            .with_batch_admission(BatchAdmissionReport {
239                refused: vec![BatchRefusal {
240                    index: 0,
241                    field: "content",
242                    reason: "fixture-refusal",
243                }],
244                validation_complete: true,
245                unchecked_indices: vec![],
246            });
247        assert_eq!(
248            admission.audit_error_class(),
249            AuditErrorClass::InvalidParams
250        );
251        assert_eq!(
252            admission.batch_write_disposition(),
253            Some(DomainDisposition::NotCommitted)
254        );
255
256        for (state, expected) in [
257            (
258                WriterTaskRequestState::NotStarted,
259                DomainDisposition::NotCommitted,
260            ),
261            (
262                WriterTaskRequestState::TransactionRolledBack,
263                DomainDisposition::NotCommitted,
264            ),
265            (
266                WriterTaskRequestState::SideEffectsUnknown,
267                DomainDisposition::Unknown,
268            ),
269        ] {
270            let failure =
271                RuntimeError::atomic_write_failure(StorageError::WriterTaskRequestFailed {
272                    request_state: state,
273                    source: Box::new(StorageError::Internal("fixture write cause".into())),
274                });
275            assert_eq!(failure.audit_error_class(), AuditErrorClass::Storage);
276            assert_eq!(failure.batch_write_disposition(), Some(expected));
277        }
278
279        for (state, expected) in [
280            (
281                WriterTaskRequestState::NotStarted,
282                DomainDisposition::NotCommitted,
283            ),
284            (
285                WriterTaskRequestState::TransactionRolledBack,
286                DomainDisposition::NotCommitted,
287            ),
288            (
289                WriterTaskRequestState::SideEffectsUnknown,
290                DomainDisposition::Unknown,
291            ),
292        ] {
293            let failure =
294                RuntimeError::atomic_write_failure(StorageError::writer_task_terminated(state));
295            assert_eq!(failure.audit_error_class(), AuditErrorClass::Storage);
296            assert_eq!(failure.batch_write_disposition(), Some(expected));
297        }
298    }
299    fn search_context(source: RuntimeError) -> RuntimeError {
300        source.with_search_read_context(
301            crate::BackendId::parse("archive").unwrap(),
302            crate::error::SearchReadSubstrate::Note,
303        )
304    }
305
306    #[test]
307    fn search_read_preserves_projected_kinds_and_typed_classification() {
308        use khive_types::KhiveError;
309        type Factory = fn() -> RuntimeError;
310        let cases: &[(Factory, &str)] = &[
311            (
312                || RuntimeError::RemoteFetchError {
313                    remote: "private remote".into(),
314                    message: "private message".into(),
315                },
316                "remote_fetch_error",
317            ),
318            (
319                || RuntimeError::AuditObligation {
320                    failure: Box::new(crate::error::AuditObligationFailure::new(
321                        "search",
322                        crate::audit_batch::AuditTerminalReason::StoreFailure,
323                    )),
324                    domain_result: serde_json::json!({"private": "ordinary domain canary"}),
325                },
326                "obligation",
327            ),
328            (
329                || {
330                    StorageError::writer_task_terminated(WriterTaskRequestState::SideEffectsUnknown)
331                        .into()
332                },
333                "storage",
334            ),
335            (
336                || {
337                    StorageError::AdmissionTimeout {
338                        operation: "metadata".into(),
339                        timeout_ms: 7,
340                        pool_identity: Some("private pool".into()),
341                    }
342                    .into()
343                },
344                "unavailable",
345            ),
346            (
347                || {
348                    StorageError::Timeout {
349                        operation: "metadata".into(),
350                    }
351                    .into()
352                },
353                "runtime_error",
354            ),
355            (
356                || RuntimeError::permission_denied("search", "private policy"),
357                "runtime_error",
358            ),
359            (
360                || KhiveError::not_found("record", "private id").into(),
361                "not_found",
362            ),
363            (
364                || KhiveError::invalid_input("private input").into(),
365                "invalid_input",
366            ),
367            (
368                || KhiveError::unauthorized("private identity").into(),
369                "unauthorized",
370            ),
371            (
372                || KhiveError::conflict("private conflict").into(),
373                "conflict",
374            ),
375            (
376                || KhiveError::unavailable("private availability").into(),
377                "unavailable",
378            ),
379            (
380                || KhiveError::internal("private internal").into(),
381                "internal",
382            ),
383            (
384                || RuntimeError::Internal("private internal".into()),
385                "runtime_error",
386            ),
387            (
388                || RuntimeError::CanonicalAdmission {
389                    op_index: 3,
390                    source: Box::new(KhiveError::not_found("record", "private id").into()),
391                },
392                "not_found",
393            ),
394        ];
395        for &(factory, expected_kind) in cases {
396            let source = factory();
397            let audit_class = source.audit_error_class();
398            let retry = source.retryable_failure_context();
399            let channel_class = source.channel_ingest_failure_class();
400            let raw =
401                crate::error_projection::runtime_error_value(source, DomainDisposition::Unknown);
402            assert_eq!(raw["kind"], expected_kind, "raw kind discriminator");
403            let wrapped = search_context(factory());
404            assert_eq!(wrapped.audit_error_class(), audit_class);
405            assert_eq!(wrapped.retryable_failure_context(), retry);
406            assert_eq!(wrapped.channel_ingest_failure_class(), channel_class);
407            let value =
408                crate::error_projection::runtime_error_value(wrapped, DomainDisposition::Unknown);
409            assert_eq!(value["kind"], raw["kind"]);
410            assert_eq!(value["domain_disposition"], raw["domain_disposition"]);
411            let mut expected = serde_json::json!({
412                "kind": expected_kind,
413                "code": "search_read_failed",
414                "message": "search metadata read failed on backend archive (note)",
415                "cause_class": audit_class.as_str(),
416                "domain_disposition": raw["domain_disposition"],
417                "search_context": {"backend": "archive", "substrate": "note"},
418            });
419            if retry.is_some() {
420                expected["retryable"] = serde_json::json!(true);
421            }
422            assert_eq!(value, expected);
423        }
424        let wrapped = search_context(
425            RuntimeError::InvalidInput("private input".into()).before_requested_write(),
426        );
427        assert_eq!(
428            wrapped.batch_write_disposition(),
429            Some(DomainDisposition::NotCommitted)
430        );
431        assert!(
432            matches!(wrapped.refusal_source(), RuntimeError::InvalidInput(text) if text == "private input")
433        );
434    }
435
436    #[test]
437    fn search_read_hides_raw_content_and_untrusted_retry_fields() {
438        fn receipt() -> RuntimeError {
439            RuntimeError::RefusedWithReceipt(Box::new(crate::error::ReceiptRefusal {
440                code: "ordinary-code-canary",
441                message: "ordinary-message-canary".into(),
442                receipt_id: "ordinary-receipt-canary".into(),
443                reason: "ordinary-reason-canary".into(),
444                detail: serde_json::json!({"detail": "ordinary-detail-canary", "kind": "spoofed-kind", "domain_disposition": "committed", "retryable": {"ordinary": "ordinary-retry-canary"}}),
445            }))
446        }
447        let raw =
448            crate::error_projection::runtime_error_value(receipt(), DomainDisposition::Unknown);
449        assert_eq!(raw["kind"], "runtime_error");
450        assert_eq!(raw["domain_disposition"], "not_committed");
451        let raw_text = raw.to_string();
452        let wrapped = search_context(receipt());
453        let RuntimeError::SearchRead { context } = &wrapped else {
454            panic!("typed context missing")
455        };
456        let RuntimeError::RefusedWithReceipt(source) = context.source() else {
457            panic!("original source missing")
458        };
459        assert_eq!(source.code, "ordinary-code-canary");
460        assert_eq!(source.message, "ordinary-message-canary");
461        assert_eq!(source.receipt_id, "ordinary-receipt-canary");
462        assert_eq!(source.reason, "ordinary-reason-canary");
463        assert_eq!(source.detail["detail"], "ordinary-detail-canary");
464        assert_eq!(
465            source.detail["retryable"]["ordinary"],
466            "ordinary-retry-canary"
467        );
468        let display = wrapped.to_string();
469        let value =
470            crate::error_projection::runtime_error_value(wrapped, DomainDisposition::Unknown);
471        for canary in [
472            "ordinary-code-canary",
473            "ordinary-message-canary",
474            "ordinary-receipt-canary",
475            "ordinary-reason-canary",
476            "ordinary-detail-canary",
477            "ordinary-retry-canary",
478        ] {
479            assert!(
480                raw_text.contains(canary),
481                "raw projection must expose this witness"
482            );
483            assert!(!display.contains(canary));
484            assert!(!value.to_string().contains(canary));
485        }
486        assert_eq!(
487            value,
488            serde_json::json!({
489                "kind": "runtime_error", "code": "search_read_failed",
490                "message": "search metadata read failed on backend archive (note)",
491                "cause_class": "policy_refusal", "domain_disposition": "not_committed",
492                "search_context": {"backend": "archive", "substrate": "note"},
493            })
494        );
495        fn detail() -> RuntimeError {
496            khive_types::KhiveError::invalid_input("ordinary-khive-message")
497                .with_details(khive_types::Details::new([(
498                    "private",
499                    "ordinary-khive-detail",
500                )]))
501                .into()
502        }
503        fn driver() -> RuntimeError {
504            StorageError::driver(
505                khive_storage::StorageCapability::Sql,
506                "ordinary-driver-operation",
507                std::io::Error::other("ordinary-driver-body"),
508            )
509            .into()
510        }
511        for (factory, canaries) in [
512            (
513                detail as fn() -> RuntimeError,
514                ["ordinary-khive-message", "ordinary-khive-detail"],
515            ),
516            (
517                driver as fn() -> RuntimeError,
518                ["ordinary-driver-operation", "ordinary-driver-body"],
519            ),
520        ] {
521            let raw =
522                crate::error_projection::runtime_error_value(factory(), DomainDisposition::Unknown)
523                    .to_string();
524            let wrapped = search_context(factory());
525            let display = wrapped.to_string();
526            assert_eq!(wrapped.refusal_source().to_string(), factory().to_string());
527            match wrapped.refusal_source() {
528                RuntimeError::Khive(source) => assert_eq!(
529                    source.details().unwrap().get("private"),
530                    Some("ordinary-khive-detail")
531                ),
532                RuntimeError::Storage(StorageError::Driver {
533                    operation, source, ..
534                }) => {
535                    assert_eq!(operation.as_ref(), "ordinary-driver-operation");
536                    assert_eq!(
537                        source.downcast_ref::<std::io::Error>().unwrap().to_string(),
538                        "ordinary-driver-body"
539                    );
540                }
541                _ => panic!("private typed source changed"),
542            }
543            let safe =
544                crate::error_projection::runtime_error_value(wrapped, DomainDisposition::Unknown)
545                    .to_string();
546            for canary in canaries {
547                assert!(raw.contains(canary));
548                assert!(!display.contains(canary));
549                assert!(!safe.contains(canary));
550            }
551        }
552    }
553    #[test]
554    fn search_read_preserves_nested_lint_retry_refusal() {
555        fn retryable() -> RuntimeError {
556            StorageError::AdmissionTimeout {
557                operation: "metadata".into(),
558                timeout_ms: 7,
559                pool_identity: None,
560            }
561            .into()
562        }
563        fn lint(source: RuntimeError) -> RuntimeError {
564            use crate::graph_lint::{
565                ActionIdentity, FixAction, LintFixFailureDetail, LintFixOutcome, LintReport,
566            };
567            RuntimeError::LintFix {
568                source: Box::new(source),
569                detail: Box::new(LintFixFailureDetail {
570                    outcome: LintFixOutcome::Unknown,
571                    failed_action: ActionIdentity {
572                        violation_index: 0,
573                        action: FixAction::SoftDeleteEdge,
574                    },
575                    confirmed_receipts: vec![],
576                    report: LintReport {
577                        violations: vec![],
578                        summary: Default::default(),
579                        stats: Default::default(),
580                    },
581                }),
582            }
583        }
584        assert!(retryable().retryable_failure_context().is_some());
585        for error in [
586            search_context(lint(retryable())),
587            lint(search_context(retryable())),
588        ] {
589            assert!(error.retryable_failure_context().is_none());
590            assert!(matches!(
591                error.refusal_source(),
592                RuntimeError::Storage(StorageError::AdmissionTimeout { .. })
593            ));
594            assert_eq!(
595                error.audit_error_class(),
596                AuditErrorClass::AdmissionExhausted
597            );
598        }
599        let value = crate::error_projection::runtime_error_value(
600            search_context(lint(retryable().before_requested_write())),
601            DomainDisposition::Unknown,
602        );
603        assert_eq!(value["kind"], "unavailable");
604        assert_eq!(value["domain_disposition"], "unknown");
605        assert!(value.get("retryable").is_none());
606    }
607}