1use crate::error::{AuditObligationReason, RuntimeError};
8use khive_storage::StorageError;
9
10#[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 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 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, .. }
163 | StorageError::WriterOwnerUnavailable { source, .. } => storage_class(source),
164 StorageError::NotFound { .. } => C::NotFoundOrNotAddressed,
165 StorageError::AlreadyExists { .. } | StorageError::Conflict { .. } => C::Conflict,
166 StorageError::InvalidInput { .. } | StorageError::BlobTooLarge { .. } => C::InvalidParams,
167 StorageError::Unsupported { .. } => C::Unsupported,
168 StorageError::Timeout { .. } | StorageError::ReadTransactionAgeEvicted { .. } => {
169 C::DeadlineExceeded
170 }
171 StorageError::AdmissionTimeout { .. }
172 | StorageError::WriteQueueFull { .. }
173 | StorageError::WriterTaskBusy { .. } => C::AdmissionExhausted,
174 StorageError::CapacityFloor { .. } | StorageError::SecretDetected { .. } => {
175 C::PolicyRefusal
176 }
177 StorageError::WriterTaskNoRuntime | StorageError::WriterRouteViolation { .. } => {
178 C::Configuration
179 }
180 StorageError::Driver { source, .. } => {
181 if matches!(
182 source.downcast_ref::<khive_db::SqliteError>(),
183 Some(khive_db::SqliteError::WriterPoolCheckoutTimeout { .. })
184 ) {
185 C::AdmissionExhausted
186 } else {
187 C::Storage
188 }
189 }
190 StorageError::BlobSizeMismatch { .. }
191 | StorageError::BlobDigestMismatch { .. }
192 | StorageError::Pool { .. }
193 | StorageError::Transaction { .. }
194 | StorageError::ReadTransactionAgeEvictionCleanupFailed { .. }
195 | StorageError::Serialization { .. }
196 | StorageError::IndexMaintenance { .. }
197 | StorageError::WriterTaskTerminated { .. }
198 | StorageError::WriteOutcomeUnknown { .. }
199 | StorageError::Internal(_)
200 | StorageError::CapacityUnavailable { .. } => C::Storage,
201 }
202}
203
204#[cfg(test)]
205mod tests {
206 use super::AuditErrorClass;
207 use crate::error::{BatchAdmissionReport, BatchRefusal, DomainDisposition, RuntimeError};
208 use khive_storage::{StorageError, WriterTaskRequestState};
209
210 #[test]
211 fn incoming_key_secret_is_a_policy_refusal_through_both_storage_routes() {
212 let key = format!("ghp_{}", "A".repeat(40));
213 for converted in [false, true] {
214 let storage =
215 khive_storage::note::validate_note_key_for_store(&key, "assign_note_key_if_unset")
216 .expect_err("the incoming key must be refused");
217 let runtime = if converted {
218 RuntimeError::from(storage)
219 } else {
220 RuntimeError::Storage(storage)
221 };
222 assert_eq!(
223 runtime.audit_error_class(),
224 AuditErrorClass::PolicyRefusal,
225 "a typed credential refusal is policy, not storage failure or invalid shape"
226 );
227 }
228 }
229
230 #[test]
231 fn batch_write_delegates_audit_class_without_changing_settlement() {
232 for (source, expected) in [
233 (
234 RuntimeError::InvalidInput("fixture input".into()),
235 AuditErrorClass::InvalidParams,
236 ),
237 (
238 RuntimeError::NotFound("fixture target".into()),
239 AuditErrorClass::NotFoundOrNotAddressed,
240 ),
241 (
242 RuntimeError::Internal("fixture internal".into()),
243 AuditErrorClass::Internal,
244 ),
245 ] {
246 assert_eq!(
247 source.audit_error_class(),
248 expected,
249 "unwrapped source control"
250 );
251 let refusal = source.before_requested_write();
252 assert_eq!(
253 refusal.audit_error_class(),
254 expected,
255 "BatchWrite must retain the source audit class"
256 );
257 assert_eq!(
258 refusal.batch_write_disposition(),
259 Some(DomainDisposition::NotCommitted)
260 );
261 }
262
263 let admission = RuntimeError::InvalidInput("fixture admission".into())
264 .with_batch_admission(BatchAdmissionReport {
265 refused: vec![BatchRefusal {
266 index: 0,
267 field: "content",
268 reason: "fixture-refusal",
269 }],
270 validation_complete: true,
271 unchecked_indices: vec![],
272 });
273 assert_eq!(
274 admission.audit_error_class(),
275 AuditErrorClass::InvalidParams
276 );
277 assert_eq!(
278 admission.batch_write_disposition(),
279 Some(DomainDisposition::NotCommitted)
280 );
281
282 for (state, expected) in [
283 (
284 WriterTaskRequestState::NotStarted,
285 DomainDisposition::NotCommitted,
286 ),
287 (
288 WriterTaskRequestState::TransactionRolledBack,
289 DomainDisposition::NotCommitted,
290 ),
291 (
292 WriterTaskRequestState::SideEffectsUnknown,
293 DomainDisposition::Unknown,
294 ),
295 ] {
296 let failure =
297 RuntimeError::atomic_write_failure(StorageError::WriterTaskRequestFailed {
298 request_state: state,
299 source: Box::new(StorageError::Internal("fixture write cause".into())),
300 });
301 assert_eq!(failure.audit_error_class(), AuditErrorClass::Storage);
302 assert_eq!(failure.batch_write_disposition(), Some(expected));
303 }
304
305 for (state, expected) in [
306 (
307 WriterTaskRequestState::NotStarted,
308 DomainDisposition::NotCommitted,
309 ),
310 (
311 WriterTaskRequestState::TransactionRolledBack,
312 DomainDisposition::NotCommitted,
313 ),
314 (
315 WriterTaskRequestState::SideEffectsUnknown,
316 DomainDisposition::Unknown,
317 ),
318 ] {
319 let failure =
320 RuntimeError::atomic_write_failure(StorageError::writer_task_terminated(state));
321 assert_eq!(failure.audit_error_class(), AuditErrorClass::Storage);
322 assert_eq!(failure.batch_write_disposition(), Some(expected));
323 }
324 }
325 fn search_context(source: RuntimeError) -> RuntimeError {
326 source.with_search_read_context(
327 crate::BackendId::parse("archive").unwrap(),
328 crate::error::SearchReadSubstrate::Note,
329 )
330 }
331
332 #[test]
333 fn search_read_preserves_projected_kinds_and_typed_classification() {
334 use khive_types::KhiveError;
335 type Factory = fn() -> RuntimeError;
336 let cases: &[(Factory, &str)] = &[
337 (
338 || RuntimeError::RemoteFetchError {
339 remote: "private remote".into(),
340 message: "private message".into(),
341 },
342 "remote_fetch_error",
343 ),
344 (
345 || RuntimeError::AuditObligation {
346 failure: Box::new(crate::error::AuditObligationFailure::new(
347 "search",
348 crate::audit_batch::AuditTerminalReason::StoreFailure,
349 )),
350 domain_result: serde_json::json!({"private": "ordinary domain canary"}),
351 },
352 "obligation",
353 ),
354 (
355 || {
356 StorageError::writer_task_terminated(WriterTaskRequestState::SideEffectsUnknown)
357 .into()
358 },
359 "storage",
360 ),
361 (
362 || {
363 StorageError::AdmissionTimeout {
364 operation: "metadata".into(),
365 timeout_ms: 7,
366 pool_identity: Some("private pool".into()),
367 }
368 .into()
369 },
370 "unavailable",
371 ),
372 (
373 || {
374 StorageError::Timeout {
375 operation: "metadata".into(),
376 }
377 .into()
378 },
379 "runtime_error",
380 ),
381 (
382 || RuntimeError::permission_denied("search", "private policy"),
383 "runtime_error",
384 ),
385 (
386 || KhiveError::not_found("record", "private id").into(),
387 "not_found",
388 ),
389 (
390 || KhiveError::invalid_input("private input").into(),
391 "invalid_input",
392 ),
393 (
394 || KhiveError::unauthorized("private identity").into(),
395 "unauthorized",
396 ),
397 (
398 || KhiveError::conflict("private conflict").into(),
399 "conflict",
400 ),
401 (
402 || KhiveError::unavailable("private availability").into(),
403 "unavailable",
404 ),
405 (
406 || KhiveError::internal("private internal").into(),
407 "internal",
408 ),
409 (
410 || RuntimeError::Internal("private internal".into()),
411 "runtime_error",
412 ),
413 (
414 || RuntimeError::CanonicalAdmission {
415 op_index: 3,
416 source: Box::new(KhiveError::not_found("record", "private id").into()),
417 },
418 "not_found",
419 ),
420 ];
421 for &(factory, expected_kind) in cases {
422 let source = factory();
423 let audit_class = source.audit_error_class();
424 let retry = source.retryable_failure_context();
425 let channel_class = source.channel_ingest_failure_class();
426 let raw =
427 crate::error_projection::runtime_error_value(source, DomainDisposition::Unknown);
428 assert_eq!(raw["kind"], expected_kind, "raw kind discriminator");
429 let wrapped = search_context(factory());
430 assert_eq!(wrapped.audit_error_class(), audit_class);
431 assert_eq!(wrapped.retryable_failure_context(), retry);
432 assert_eq!(wrapped.channel_ingest_failure_class(), channel_class);
433 let value =
434 crate::error_projection::runtime_error_value(wrapped, DomainDisposition::Unknown);
435 assert_eq!(value["kind"], raw["kind"]);
436 assert_eq!(value["domain_disposition"], raw["domain_disposition"]);
437 let mut expected = serde_json::json!({
438 "kind": expected_kind,
439 "code": "search_read_failed",
440 "message": "search metadata read failed on backend archive (note)",
441 "cause_class": audit_class.as_str(),
442 "domain_disposition": raw["domain_disposition"],
443 "search_context": {"backend": "archive", "substrate": "note"},
444 });
445 if retry.is_some() {
446 expected["retryable"] = serde_json::json!(true);
447 }
448 assert_eq!(value, expected);
449 }
450 let wrapped = search_context(
451 RuntimeError::InvalidInput("private input".into()).before_requested_write(),
452 );
453 assert_eq!(
454 wrapped.batch_write_disposition(),
455 Some(DomainDisposition::NotCommitted)
456 );
457 assert!(
458 matches!(wrapped.refusal_source(), RuntimeError::InvalidInput(text) if text == "private input")
459 );
460 }
461
462 #[test]
463 fn search_read_hides_raw_content_and_untrusted_retry_fields() {
464 fn receipt() -> RuntimeError {
465 RuntimeError::RefusedWithReceipt(Box::new(crate::error::ReceiptRefusal {
466 code: "ordinary-code-canary",
467 message: "ordinary-message-canary".into(),
468 receipt_id: "ordinary-receipt-canary".into(),
469 reason: "ordinary-reason-canary".into(),
470 detail: serde_json::json!({"detail": "ordinary-detail-canary", "kind": "spoofed-kind", "domain_disposition": "committed", "retryable": {"ordinary": "ordinary-retry-canary"}}),
471 }))
472 }
473 let raw =
474 crate::error_projection::runtime_error_value(receipt(), DomainDisposition::Unknown);
475 assert_eq!(raw["kind"], "runtime_error");
476 assert_eq!(raw["domain_disposition"], "not_committed");
477 let raw_text = raw.to_string();
478 let wrapped = search_context(receipt());
479 let RuntimeError::SearchRead { context } = &wrapped else {
480 panic!("typed context missing")
481 };
482 let RuntimeError::RefusedWithReceipt(source) = context.source() else {
483 panic!("original source missing")
484 };
485 assert_eq!(source.code, "ordinary-code-canary");
486 assert_eq!(source.message, "ordinary-message-canary");
487 assert_eq!(source.receipt_id, "ordinary-receipt-canary");
488 assert_eq!(source.reason, "ordinary-reason-canary");
489 assert_eq!(source.detail["detail"], "ordinary-detail-canary");
490 assert_eq!(
491 source.detail["retryable"]["ordinary"],
492 "ordinary-retry-canary"
493 );
494 let display = wrapped.to_string();
495 let value =
496 crate::error_projection::runtime_error_value(wrapped, DomainDisposition::Unknown);
497 for canary in [
498 "ordinary-code-canary",
499 "ordinary-message-canary",
500 "ordinary-receipt-canary",
501 "ordinary-reason-canary",
502 "ordinary-detail-canary",
503 "ordinary-retry-canary",
504 ] {
505 assert!(
506 raw_text.contains(canary),
507 "raw projection must expose this witness"
508 );
509 assert!(!display.contains(canary));
510 assert!(!value.to_string().contains(canary));
511 }
512 assert_eq!(
513 value,
514 serde_json::json!({
515 "kind": "runtime_error", "code": "search_read_failed",
516 "message": "search metadata read failed on backend archive (note)",
517 "cause_class": "policy_refusal", "domain_disposition": "not_committed",
518 "search_context": {"backend": "archive", "substrate": "note"},
519 })
520 );
521 fn detail() -> RuntimeError {
522 khive_types::KhiveError::invalid_input("ordinary-khive-message")
523 .with_details(khive_types::Details::new([(
524 "private",
525 "ordinary-khive-detail",
526 )]))
527 .into()
528 }
529 fn driver() -> RuntimeError {
530 StorageError::driver(
531 khive_storage::StorageCapability::Sql,
532 "ordinary-driver-operation",
533 std::io::Error::other("ordinary-driver-body"),
534 )
535 .into()
536 }
537 for (factory, canaries) in [
538 (
539 detail as fn() -> RuntimeError,
540 ["ordinary-khive-message", "ordinary-khive-detail"],
541 ),
542 (
543 driver as fn() -> RuntimeError,
544 ["ordinary-driver-operation", "ordinary-driver-body"],
545 ),
546 ] {
547 let raw =
548 crate::error_projection::runtime_error_value(factory(), DomainDisposition::Unknown)
549 .to_string();
550 let wrapped = search_context(factory());
551 let display = wrapped.to_string();
552 assert_eq!(wrapped.refusal_source().to_string(), factory().to_string());
553 match wrapped.refusal_source() {
554 RuntimeError::Khive(source) => assert_eq!(
555 source.details().unwrap().get("private"),
556 Some("ordinary-khive-detail")
557 ),
558 RuntimeError::Storage(StorageError::Driver {
559 operation, source, ..
560 }) => {
561 assert_eq!(operation.as_ref(), "ordinary-driver-operation");
562 assert_eq!(
563 source.downcast_ref::<std::io::Error>().unwrap().to_string(),
564 "ordinary-driver-body"
565 );
566 }
567 _ => panic!("private typed source changed"),
568 }
569 let safe =
570 crate::error_projection::runtime_error_value(wrapped, DomainDisposition::Unknown)
571 .to_string();
572 for canary in canaries {
573 assert!(raw.contains(canary));
574 assert!(!display.contains(canary));
575 assert!(!safe.contains(canary));
576 }
577 }
578 }
579 #[test]
580 fn search_read_preserves_nested_lint_retry_refusal() {
581 fn retryable() -> RuntimeError {
582 StorageError::AdmissionTimeout {
583 operation: "metadata".into(),
584 timeout_ms: 7,
585 pool_identity: None,
586 }
587 .into()
588 }
589 fn lint(source: RuntimeError) -> RuntimeError {
590 use crate::graph_lint::{
591 ActionIdentity, FixAction, LintFixFailureDetail, LintFixOutcome, LintReport,
592 };
593 RuntimeError::LintFix {
594 source: Box::new(source),
595 detail: Box::new(LintFixFailureDetail {
596 outcome: LintFixOutcome::Unknown,
597 failed_action: ActionIdentity {
598 violation_index: 0,
599 action: FixAction::SoftDeleteEdge,
600 },
601 confirmed_receipts: vec![],
602 report: LintReport {
603 violations: vec![],
604 summary: Default::default(),
605 stats: Default::default(),
606 },
607 }),
608 }
609 }
610 assert!(retryable().retryable_failure_context().is_some());
611 for error in [
612 search_context(lint(retryable())),
613 lint(search_context(retryable())),
614 ] {
615 assert!(error.retryable_failure_context().is_none());
616 assert!(matches!(
617 error.refusal_source(),
618 RuntimeError::Storage(StorageError::AdmissionTimeout { .. })
619 ));
620 assert_eq!(
621 error.audit_error_class(),
622 AuditErrorClass::AdmissionExhausted
623 );
624 }
625 let value = crate::error_projection::runtime_error_value(
626 search_context(lint(retryable().before_requested_write())),
627 DomainDisposition::Unknown,
628 );
629 assert_eq!(value["kind"], "unavailable");
630 assert_eq!(value["domain_disposition"], "unknown");
631 assert!(value.get("retryable").is_none());
632 }
633 #[test]
634 fn writer_outcomes_retain_audit_class_and_finality() {
635 for (error, class, disposition) in [
636 (
637 StorageError::WriteOutcomeUnknown {
638 source: Box::new(std::io::Error::other("lost COMMIT reply")),
639 },
640 AuditErrorClass::Storage,
641 DomainDisposition::Unknown,
642 ),
643 (
644 StorageError::WriterOwnerUnavailable {
645 operation: "write".into(),
646 source: Box::new(StorageError::WriterTaskNoRuntime),
647 },
648 AuditErrorClass::Configuration,
649 DomainDisposition::NotCommitted,
650 ),
651 (
652 StorageError::WriterOwnerUnavailable {
653 operation: "write".into(),
654 source: Box::new(StorageError::Pool {
655 operation: "owner".into(),
656 message: "stopped".into(),
657 }),
658 },
659 AuditErrorClass::Storage,
660 DomainDisposition::NotCommitted,
661 ),
662 (
663 StorageError::WriterRouteViolation {
664 operation: "write".into(),
665 },
666 AuditErrorClass::Configuration,
667 DomainDisposition::NotCommitted,
668 ),
669 ] {
670 let error = RuntimeError::atomic_write_failure(error);
671 assert_eq!(error.audit_error_class(), class);
672 assert_eq!(error.batch_write_disposition(), Some(disposition));
673 }
674 }
675}