1use std::fmt;
4use std::time::Duration;
5
6use thiserror::Error;
7use uuid::Uuid;
8
9pub type RuntimeResult<T> = Result<T, RuntimeError>;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
14#[serde(rename_all = "snake_case")]
15pub enum DomainDisposition {
16 Committed,
18 NotCommitted,
21 Unknown,
23}
24
25impl DomainDisposition {
26 pub const fn as_str(self) -> &'static str {
28 match self {
29 Self::Committed => "committed",
30 Self::NotCommitted => "not_committed",
31 Self::Unknown => "unknown",
32 }
33 }
34}
35
36#[derive(Debug, Error)]
38#[error("{source}")]
39pub struct DispatchError {
40 #[source]
41 source: RuntimeError,
42 disposition: DomainDisposition,
43}
44
45impl DispatchError {
46 pub(crate) fn new(source: RuntimeError, disposition: DomainDisposition) -> Self {
47 Self {
48 source,
49 disposition,
50 }
51 }
52
53 pub(crate) fn before_dispatch(source: RuntimeError) -> Self {
54 Self::new(source, DomainDisposition::NotCommitted)
55 }
56
57 pub(crate) fn after_handler(source: RuntimeError, domain_succeeded: bool) -> Self {
58 let disposition = if domain_succeeded {
59 DomainDisposition::Committed
60 } else {
61 source
62 .batch_write_disposition()
63 .unwrap_or(DomainDisposition::Unknown)
64 };
65 Self::new(source, disposition)
66 }
67
68 pub fn source(&self) -> &RuntimeError {
70 &self.source
71 }
72
73 pub fn disposition(&self) -> DomainDisposition {
75 self.disposition
76 }
77
78 pub fn into_parts(self) -> (RuntimeError, DomainDisposition) {
80 (self.source, self.disposition)
81 }
82
83 pub fn into_source(self) -> RuntimeError {
85 self.source
86 }
87}
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub enum AuditObligationReason {
92 Terminal(crate::audit_batch::AuditTerminalReason),
94 GitDigestReceiptFailure,
96}
97
98#[derive(Debug, Error)]
100#[error("{message}")]
101pub struct AuditObligationFailure {
102 pub reason: AuditObligationReason,
104 pub verb: String,
106 pub message: String,
108 #[source]
109 source: Option<khive_storage::StorageError>,
110}
111
112impl AuditObligationFailure {
113 pub fn new(verb: impl Into<String>, reason: crate::audit_batch::AuditTerminalReason) -> Self {
115 let verb = verb.into();
116 Self {
117 message: format!("audit obligation commit failed for verb {verb:?}: {reason:?}"),
118 verb,
119 reason: AuditObligationReason::Terminal(reason),
120 source: None,
121 }
122 }
123
124 pub(crate) fn from_store(verb: &str, source: khive_storage::StorageError) -> Self {
125 let mut failure = Self::new(verb, crate::audit_batch::AuditTerminalReason::StoreFailure);
126 failure.message = format!("audit obligation commit failed for verb {verb:?}: {source}");
127 failure.source = Some(source);
128 failure
129 }
130
131 pub(crate) fn git_digest_receipt(branch: &'static str) -> Self {
132 Self {
133 reason: AuditObligationReason::GitDigestReceiptFailure,
134 verb: "git.digest".into(),
135 message: format!(
136 "git_digest_receipt_persist_failed: {branch}; git.digest writes may have committed, but no durable success receipt was confirmed; inspect ingest state before retrying"
137 ),
138 source: None,
139 }
140 }
141
142 pub const fn wire_code(&self) -> &'static str {
144 use crate::audit_batch::AuditTerminalReason;
145 match self.reason {
146 AuditObligationReason::Terminal(reason) => match reason {
147 AuditTerminalReason::PreflightRejected => "preflight_rejected",
148 AuditTerminalReason::AdmissionClosed => "admission_closed",
149 AuditTerminalReason::QueueAdmissionExhausted => "queue_admission_exhausted",
150 AuditTerminalReason::AdmissionDeadlineExpired => "admission_deadline_expired",
151 AuditTerminalReason::ResolutionDeadlineExpired => "resolution_deadline_expired",
152 AuditTerminalReason::IdentityConflict => "identity_conflict",
153 AuditTerminalReason::StoreFailure => "store_failure",
154 AuditTerminalReason::RetryExhausted => "retry_exhausted",
155 AuditTerminalReason::IdempotencyUnsupported => "idempotency_unsupported",
156 AuditTerminalReason::DriverPanicked => "driver_panicked",
157 AuditTerminalReason::DriverCancelled => "driver_cancelled",
158 AuditTerminalReason::DriverJoinLost => "driver_join_lost",
159 AuditTerminalReason::DriverExitedInconsistent => "driver_exited_inconsistent",
160 AuditTerminalReason::DriverAppendAbandoned => "driver_append_abandoned",
161 AuditTerminalReason::StoreWedged => "store_wedged",
162 },
163 AuditObligationReason::GitDigestReceiptFailure => "git_digest_receipt_failure",
164 }
165 }
166}
167
168pub const WRITER_POOL_CHECKOUT_TIMEOUT_STAGE: &str = "writer_pool_checkout_timeout";
171
172pub use khive_db::{SQLITE_WAL_CAPACITY_REFUSED_STAGE, SQLITE_WAL_CAPACITY_UNAVAILABLE_STAGE};
174
175pub const WRITER_QUEUE_SATURATED_STAGE: &str = "writer_queue_saturated";
178
179pub const WRITER_TASK_BEGIN_BUSY_STAGE: &str = "writer_task_begin_busy";
182
183pub const WRITER_TASK_REQUEST_FAILED_STAGE: &str = "writer_task_request_failed";
186
187pub const WRITER_TASK_TERMINATED_STAGE: &str = "writer_task_terminated";
190
191pub const WRITE_OUTCOME_UNKNOWN_STAGE: &str = "write_outcome_unknown";
193pub const WRITER_OWNER_UNAVAILABLE_STAGE: &str = "writer_owner_unavailable";
195pub const WRITER_ROUTE_VIOLATION_STAGE: &str = "writer_route_violation";
197
198pub const STORAGE_ADMISSION_TIMEOUT_STAGE: &str = "storage_admission_timeout";
203
204pub const READ_TX_AGE_EVICTED_STAGE: &str = "read_tx_age_evicted";
215
216pub const WRITER_ADMISSION_SCOPE: &str = "writer_admission";
223
224#[derive(Debug, Clone, PartialEq, Eq)]
231pub struct AdmissionFailureContext {
232 pub stage: &'static str,
236 pub timeout: Duration,
238 pub capability: Option<khive_storage::StorageCapability>,
242 pub operation: Option<String>,
244 pub pool_identity: Option<String>,
246 pub scope: Option<&'static str>,
251 pub retry_after_ms: Option<u64>,
257}
258
259#[derive(Debug, Clone, PartialEq, Eq)]
266pub struct RetryableFailureContext {
267 pub stage: &'static str,
269 pub timeout: Duration,
271 pub capability: Option<khive_storage::StorageCapability>,
273 pub operation: Option<String>,
275 pub pool_identity: Option<String>,
277 pub scope: Option<&'static str>,
279 pub retry_after_ms: Option<u64>,
281}
282
283#[derive(Debug, Clone, Copy, PartialEq, Eq)]
290pub struct WriterTaskFailureContext {
291 pub stage: &'static str,
293 pub request_state: khive_storage::WriterTaskRequestState,
295 pub task_terminated: bool,
297 pub retryable: bool,
299}
300
301impl From<AdmissionFailureContext> for RetryableFailureContext {
302 fn from(context: AdmissionFailureContext) -> Self {
303 Self {
304 stage: context.stage,
305 timeout: context.timeout,
306 capability: context.capability,
307 operation: context.operation,
308 pool_identity: context.pool_identity,
309 scope: context.scope,
310 retry_after_ms: context.retry_after_ms,
311 }
312 }
313}
314
315#[derive(Debug, Clone, Copy, PartialEq, Eq)]
321pub enum ChannelIngestFailureClass {
322 Retryable { reason: &'static str },
324 Permanent { reason: &'static str },
326 Unknown { reason: &'static str },
328}
329
330impl ChannelIngestFailureClass {
331 pub const fn name(self) -> &'static str {
333 match self {
334 Self::Retryable { .. } => "retryable",
335 Self::Permanent { .. } => "permanent",
336 Self::Unknown { .. } => "unknown",
337 }
338 }
339
340 pub const fn reason(self) -> &'static str {
342 match self {
343 Self::Retryable { reason } | Self::Permanent { reason } | Self::Unknown { reason } => {
344 reason
345 }
346 }
347 }
348}
349
350#[derive(Debug, Clone, PartialEq, Eq)]
353pub struct WriterPoolCheckoutTimeoutContext {
354 pub timeout: Duration,
357 pub capability: Option<khive_storage::StorageCapability>,
359 pub operation: Option<String>,
361}
362
363#[derive(Debug, Clone, PartialEq, Eq)]
368pub struct GuardedWriteFailure {
369 pub entry_index: Option<usize>,
372 pub missing_source: Option<Uuid>,
375 pub missing_target: Option<Uuid>,
378}
379
380impl fmt::Display for GuardedWriteFailure {
381 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
382 let mut missing = Vec::new();
383 if let Some(source) = self.missing_source {
384 missing.push(format!("source {source}"));
385 }
386 if let Some(target) = self.missing_target {
387 missing.push(format!("target {target}"));
388 }
389 let missing = if missing.is_empty() {
390 "endpoint(s)".to_string()
391 } else {
392 missing.join(" and ")
393 };
394 match self.entry_index {
395 Some(index) => write!(
396 f,
397 "batch entry {index}: {missing} no longer exist at write time"
398 ),
399 None => write!(f, "{missing} no longer exist at write time"),
400 }
401 }
402}
403
404impl std::error::Error for GuardedWriteFailure {}
405
406#[derive(Debug, Clone, PartialEq, Eq)]
408pub struct MissingPackDependency {
409 pub from: String,
410 pub requires: String,
411}
412
413impl fmt::Display for MissingPackDependency {
414 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
415 write!(
416 f,
417 "pack '{}' requires '{}', but '{}' is not in the loaded pack set",
418 self.from, self.requires, self.requires
419 )
420 }
421}
422
423impl std::error::Error for MissingPackDependency {}
424
425#[derive(Debug, Clone, PartialEq, Eq)]
427pub struct MissingPackDependencies {
428 pub missing: Vec<MissingPackDependency>,
429}
430
431impl fmt::Display for MissingPackDependencies {
432 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433 let parts: Vec<String> = self.missing.iter().map(ToString::to_string).collect();
434 write!(f, "{}", parts.join("; "))
435 }
436}
437
438impl std::error::Error for MissingPackDependencies {}
439
440#[derive(Debug, Clone, PartialEq, Eq)]
442pub struct CircularPackDependency {
443 pub cycle: Vec<String>,
444}
445
446impl fmt::Display for CircularPackDependency {
447 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
448 write!(
449 f,
450 "circular dependency detected among packs: {}",
451 self.cycle.join(" -> ")
452 )
453 }
454}
455
456impl std::error::Error for CircularPackDependency {}
457
458#[derive(Debug, Clone, Copy, PartialEq, Eq)]
465pub enum DenialAuditOutcome {
466 Committed,
469 NotCommitted(&'static str),
472 NoStore,
474 NotAudited,
477}
478
479impl DenialAuditOutcome {
480 pub fn wire_code(&self) -> String {
483 match self {
484 Self::Committed => "committed".to_string(),
485 Self::NotCommitted(code) => format!("not_committed:{code}"),
486 Self::NoStore => "no_store".to_string(),
487 Self::NotAudited => "not_audited".to_string(),
488 }
489 }
490}
491
492#[derive(Debug, Clone, PartialEq, Eq)]
496pub struct DenialReceipt {
497 pub audit_event_id: Option<uuid::Uuid>,
499 pub audit_outcome: DenialAuditOutcome,
501}
502
503impl DenialReceipt {
504 pub fn not_audited() -> Self {
506 Self {
507 audit_event_id: None,
508 audit_outcome: DenialAuditOutcome::NotAudited,
509 }
510 }
511
512 pub fn no_store() -> Self {
514 Self {
515 audit_event_id: None,
516 audit_outcome: DenialAuditOutcome::NoStore,
517 }
518 }
519}
520
521#[derive(Debug, Clone)]
523pub struct ReceiptRefusal {
524 pub code: &'static str,
526 pub message: String,
528 pub receipt_id: String,
530 pub reason: String,
532 pub detail: serde_json::Value,
534}
535
536#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
538#[serde(rename_all = "snake_case")]
539pub enum RefusalRecordingErrorClass {
540 EventStoreUnavailable,
541 EventAppendFailed,
542}
543
544impl RefusalRecordingErrorClass {
545 pub const fn as_str(self) -> &'static str {
546 match self {
547 Self::EventStoreUnavailable => "event_store_unavailable",
548 Self::EventAppendFailed => "event_append_failed",
549 }
550 }
551}
552
553#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
556#[serde(untagged)]
557pub enum RefusalEventRecording {
558 Recorded {
559 item_index: usize,
560 subject: Uuid,
561 event_id: Uuid,
562 },
563 Failed {
564 item_index: usize,
565 subject: Uuid,
566 error_class: RefusalRecordingErrorClass,
567 },
568}
569
570#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
572pub struct BatchRefusal {
573 pub index: usize,
574 pub field: &'static str,
575 pub reason: &'static str,
576}
577
578#[derive(Debug)]
580pub struct BatchAdmissionReport {
581 pub refused: Vec<BatchRefusal>,
582 pub validation_complete: bool,
583 pub unchecked_indices: Vec<usize>,
584}
585
586#[derive(Debug)]
588pub struct BatchWriteContext {
589 pub source: Box<RuntimeError>,
590 pub disposition: DomainDisposition,
591 pub admission: Option<BatchAdmissionReport>,
592}
593
594impl fmt::Display for BatchWriteContext {
595 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
596 fmt::Display::fmt(self.source.as_ref(), formatter)
597 }
598}
599
600impl std::error::Error for BatchWriteContext {
601 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
602 Some(self.source.as_ref())
603 }
604}
605
606#[derive(Debug)]
612pub struct RefusalEventContext {
613 pub source: Box<RuntimeError>,
614 pub recordings: Vec<RefusalEventRecording>,
615}
616
617impl std::fmt::Display for RefusalEventContext {
618 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
619 std::fmt::Display::fmt(self.source.as_ref(), formatter)
620 }
621}
622
623impl std::error::Error for RefusalEventContext {
624 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
625 Some(self.source.as_ref())
626 }
627}
628
629#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
631pub struct ResolutionFacts {
632 pub project_id: Uuid,
633 pub duplicate_anchor_ids: Vec<Uuid>,
634 pub slug_backfilled: bool,
635 pub project_created: bool,
636 pub orphaned_project_id: Option<Uuid>,
637 pub orphaned_note_count: u64,
638}
639
640#[derive(Debug)]
642pub struct ResolutionFailureContext {
643 pub source: Box<RuntimeError>,
644 pub resolution: ResolutionFacts,
645}
646
647impl std::fmt::Display for ResolutionFailureContext {
648 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
649 std::fmt::Display::fmt(self.source.as_ref(), formatter)
650 }
651}
652
653impl std::error::Error for ResolutionFailureContext {
654 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
655 Some(self.source.as_ref())
656 }
657}
658
659#[derive(Debug, Clone, Copy, PartialEq, Eq)]
661pub enum SearchReadSubstrate {
662 Entity,
663 Note,
664}
665
666impl SearchReadSubstrate {
667 pub const fn as_str(self) -> &'static str {
668 match self {
669 Self::Entity => "entity",
670 Self::Note => "note",
671 }
672 }
673}
674
675#[derive(Debug)]
677pub struct SearchReadContext {
678 backend: crate::BackendId,
679 substrate: SearchReadSubstrate,
680 source: Box<RuntimeError>,
681}
682
683impl SearchReadContext {
684 pub fn backend(&self) -> &crate::BackendId {
685 &self.backend
686 }
687
688 pub fn substrate(&self) -> SearchReadSubstrate {
689 self.substrate
690 }
691
692 pub fn source(&self) -> &RuntimeError {
693 &self.source
694 }
695
696 pub(crate) fn into_source(self) -> RuntimeError {
697 *self.source
698 }
699}
700
701impl fmt::Display for SearchReadContext {
702 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
703 write!(
704 formatter,
705 "search metadata read failed on backend {} ({})",
706 self.backend,
707 self.substrate.as_str()
708 )
709 }
710}
711
712impl std::error::Error for SearchReadContext {
713 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
714 Some(self.source.as_ref())
715 }
716}
717
718#[derive(Debug, Error)]
722pub enum RuntimeError {
723 #[error(transparent)]
725 SearchRead { context: SearchReadContext },
726 #[error(
728 "canonical operation {op_index}: {operation} is KnownUnimplemented for canonical apply"
729 )]
730 CanonicalUnsupportedOperation {
731 op_index: usize,
732 operation: &'static str,
733 },
734 #[error("canonical operation {op_index} refused")]
737 CanonicalAdmission {
738 op_index: usize,
739 #[source]
740 source: Box<RuntimeError>,
741 },
742 #[error("{source}")]
744 LintFix {
745 #[source]
746 source: Box<RuntimeError>,
747 detail: Box<crate::graph_lint::LintFixFailureDetail>,
748 },
749
750 #[error("{failure}")]
752 AuditObligation {
753 #[source]
755 failure: Box<AuditObligationFailure>,
756 domain_result: serde_json::Value,
758 },
759
760 #[error("storage: {0}")]
761 Storage(#[source] khive_storage::StorageError),
762
763 #[error("query: {0}")]
764 Query(#[from] khive_query::QueryError),
765
766 #[error("not found: {0}")]
767 NotFound(String),
768
769 #[error("invalid input: {0}")]
770 InvalidInput(String),
771
772 #[error("invalid input: {0}")]
773 UnknownVerb(String),
774
775 #[error("unconfigured: {0} is not set")]
776 Unconfigured(String),
777
778 #[error("unknown embedding model: {0}")]
779 UnknownModel(String),
780
781 #[error("embedding: {0}")]
782 Embedding(#[from] lattice_embed::EmbedError),
783
784 #[error("ambiguous: {0}")]
785 Ambiguous(String),
786
787 #[error("fusion: {0}")]
788 Fusion(#[from] khive_fusion::FuseError),
789
790 #[error("unknown fusion strategy: {0}")]
794 UnknownFusionStrategy(String),
795
796 #[error("internal: {0}")]
797 Internal(String),
798
799 #[error("audit batch incompatible event store: {0}")]
805 IncompatibleEventStore(String),
806
807 #[error("guarded edge write refused: {0}")]
808 GuardedWriteFailed(GuardedWriteFailure),
809
810 #[error("missing pack dependency: {0}")]
811 MissingPackDependency(MissingPackDependency),
812
813 #[error("missing pack dependencies: {0}")]
814 MissingPackDependencies(MissingPackDependencies),
815
816 #[error("{0}")]
817 CircularPackDependency(CircularPackDependency),
818
819 #[error("pack '{name}' registered twice (indices {first_idx} and {second_idx})")]
820 PackRedeclared {
821 name: String,
822 first_idx: usize,
823 second_idx: usize,
824 },
825
826 #[error(
830 "verb collision: verb {verb:?} declared by both pack {first_pack:?} and pack \
831 {second_pack:?}; rename one handler or use Visibility::Subhandler for internal verbs"
832 )]
833 VerbCollision {
834 verb: String,
835 first_pack: String,
836 second_pack: String,
837 },
838
839 #[error(
841 "pack {pack:?} handler {verb:?} declares request-envelope parameter {param:?}; rename the verb argument"
842 )]
843 ReservedEnvelopeParam {
844 pack: String,
845 verb: String,
846 param: String,
847 },
848
849 #[error("{}", .0.message)]
867 RefusedWithReceipt(Box<ReceiptRefusal>),
868
869 #[error(transparent)]
873 RefusedWithEvents { context: RefusalEventContext },
874
875 #[error(transparent)]
877 BatchWrite { context: Box<BatchWriteContext> },
878
879 #[error(transparent)]
882 WithResolution { context: ResolutionFailureContext },
883
884 #[error("permission denied for verb {verb:?}: {reason}")]
894 PermissionDenied {
895 verb: String,
896 reason: String,
897 receipt: Box<DenialReceipt>,
898 },
899
900 #[error("gate unavailable for verb {verb:?}: {reason}")]
906 GateUnavailable { verb: String, reason: String },
907
908 #[error("{0}")]
912 Khive(khive_types::KhiveError),
913
914 #[error("not found in this namespace")]
919 NamespaceMismatch { id: uuid::Uuid },
920
921 #[error("ambiguous prefix {prefix:?}: matches {}", format_uuid_list(matches))]
927 AmbiguousPrefix {
928 prefix: String,
929 matches: Vec<uuid::Uuid>,
930 },
931
932 #[error(
937 "cross-backend merge is not supported: \
938 into_id {into_id} is on backend '{into_backend}', \
939 from_id {from_id} is on backend '{from_backend}'. \
940 Both entities must be on the same backend to merge."
941 )]
942 CrossBackendMergeUnsupported {
943 into_id: uuid::Uuid,
944 from_id: uuid::Uuid,
945 into_backend: String,
946 from_backend: String,
947 },
948
949 #[error("unknown remote: {name:?}")]
952 UnknownRemote { name: String },
953
954 #[error("remote cache missing for remote={remote:?} namespace={namespace:?}")]
956 RemoteCacheMissing { remote: String, namespace: String },
957
958 #[error("ambiguous id {id:?}: matched {count} records")]
960 AmbiguousId { id: String, count: usize },
961
962 #[error("cross-namespace write denied: cannot write to remote namespace {namespace:?}")]
964 CrossNamespaceWrite { namespace: String },
965
966 #[error("remote fetch error for remote={remote:?}: {message}")]
969 RemoteFetchError { remote: String, message: String },
970
971 #[error(
977 "write budget exceeded: max_new_entries={max_new_entries}, \
978 attempted_new_entries={attempted_new_entries}"
979 )]
980 WriteBudgetExceeded {
981 max_new_entries: u64,
982 attempted_new_entries: u64,
983 },
984
985 #[error("write blocked: {0}")]
991 SecretDetected(crate::secret_gate::SecretMatch),
992
993 #[error("{operation} exceeded its {budget_ms}ms deadline (elapsed {elapsed_ms}ms)")]
1007 DeadlineExceeded {
1008 operation: String,
1009 budget_ms: u64,
1010 elapsed_ms: u64,
1011 },
1012
1013 #[error(
1024 "database is at schema V{schema_version} and requires the V{required_version} attachment \
1025 cutover; run khive_runtime::coordinate_attachment_cutover before constructing \
1026 KhiveRuntime"
1027 )]
1028 AttachmentCutoverRequired {
1029 schema_version: u32,
1031 required_version: u32,
1033 },
1034}
1035
1036impl From<khive_storage::StorageError> for RuntimeError {
1037 fn from(error: khive_storage::StorageError) -> Self {
1038 match error {
1039 khive_storage::StorageError::SecretDetected { matched, .. } => {
1040 Self::SecretDetected(*matched)
1041 }
1042 other => Self::Storage(other),
1043 }
1044 }
1045}
1046
1047#[cfg(test)]
1048mod secret_storage_conversion_tests {
1049 use super::RuntimeError;
1050 use khive_storage::{StorageCapability, StorageError};
1051 use std::error::Error;
1052
1053 #[test]
1054 fn storage_secret_conversion_preserves_safe_match_and_runtime_refusal() {
1055 let key = format!("ghp_{}", "A".repeat(40));
1056 let storage =
1057 khive_storage::note::validate_note_key_for_store(&key, "assign_note_key_if_unset")
1058 .expect_err("storage must refuse the incoming key");
1059 let display = storage.to_string();
1060 let runtime: RuntimeError = storage.into();
1061 let RuntimeError::SecretDetected(matched) = &runtime else {
1062 panic!("typed storage secret must become the existing runtime refusal: {runtime:?}");
1063 };
1064 assert_eq!(matched.detector, "github-token");
1065 assert_eq!(matched.trigger, None);
1066 assert_eq!(matched.masked, "ghp_AA...44chars");
1067 assert_eq!(matched.location.as_deref(), Some("note.key"));
1068 assert_eq!(runtime.to_string(), display);
1069 let direct = crate::secret_gate::check_at(&key, "note", "key").unwrap_err();
1070 let RuntimeError::SecretDetected(direct_match) = direct else {
1071 panic!("runtime scanner must retain its typed refusal");
1072 };
1073 assert_eq!(matched, &direct_match);
1074 assert!(!runtime.to_string().contains(&key));
1075 assert!(!format!("{runtime:?}").contains(&key));
1076 assert!(runtime.source().is_none());
1077 }
1078
1079 #[test]
1080 fn ordinary_storage_conversion_and_direct_wrapper_keep_the_typed_source() {
1081 for converted in [false, true] {
1082 let storage = StorageError::InvalidInput {
1083 capability: StorageCapability::Notes,
1084 operation: "source-chain-fixture".into(),
1085 message: "ordinary refusal".into(),
1086 };
1087 let expected = storage.to_string();
1088 let runtime = if converted {
1089 RuntimeError::from(storage)
1090 } else {
1091 RuntimeError::Storage(storage)
1092 };
1093 assert_eq!(runtime.to_string(), format!("storage: {expected}"));
1094 let source = runtime
1095 .source()
1096 .expect("ordinary storage wrapper must retain Error::source");
1097 assert!(
1098 matches!(source.downcast_ref::<StorageError>(),
1099 Some(StorageError::InvalidInput { capability: StorageCapability::Notes, operation, message })
1100 if operation == "source-chain-fixture" && message == "ordinary refusal"),
1101 "the source must be the original typed StorageError"
1102 );
1103 }
1104 }
1105}
1106
1107impl From<khive_db::SqliteError> for RuntimeError {
1111 fn from(error: khive_db::SqliteError) -> Self {
1112 Self::Storage(match error {
1113 khive_db::SqliteError::RequestReadStopped(error) => error,
1114 error => error.into_storage_error(khive_storage::StorageCapability::Sql, "runtime"),
1115 })
1116 }
1117}
1118
1119impl RuntimeError {
1120 pub fn with_search_read_context(
1122 self,
1123 backend: crate::BackendId,
1124 substrate: SearchReadSubstrate,
1125 ) -> Self {
1126 Self::SearchRead {
1127 context: SearchReadContext {
1128 backend,
1129 substrate,
1130 source: Box::new(self),
1131 },
1132 }
1133 }
1134
1135 pub fn before_requested_write(self) -> Self {
1137 Self::BatchWrite {
1138 context: Box::new(BatchWriteContext {
1139 source: Box::new(self),
1140 disposition: DomainDisposition::NotCommitted,
1141 admission: None,
1142 }),
1143 }
1144 }
1145
1146 pub fn with_batch_admission(self, admission: BatchAdmissionReport) -> Self {
1148 Self::BatchWrite {
1149 context: Box::new(BatchWriteContext {
1150 source: Box::new(self),
1151 disposition: DomainDisposition::NotCommitted,
1152 admission: Some(admission),
1153 }),
1154 }
1155 }
1156
1157 pub fn atomic_write_failure(error: khive_storage::StorageError) -> Self {
1159 use khive_storage::{StorageError, WriterTaskRequestState};
1160 let disposition = match error.writer_request_state() {
1161 Some(request_state) => match request_state {
1162 WriterTaskRequestState::NotStarted
1163 | WriterTaskRequestState::TransactionRolledBack => DomainDisposition::NotCommitted,
1164 WriterTaskRequestState::SideEffectsUnknown => DomainDisposition::Unknown,
1165 },
1166 None => match error.without_sqlite_write_stage() {
1167 StorageError::WriterTaskBusy { .. }
1168 | StorageError::WriteQueueFull { .. }
1169 | StorageError::AdmissionTimeout { .. } => DomainDisposition::NotCommitted,
1170 _ => DomainDisposition::Unknown,
1171 },
1172 };
1173 Self::BatchWrite {
1174 context: Box::new(BatchWriteContext {
1175 source: Box::new(Self::Storage(error)),
1176 disposition,
1177 admission: None,
1178 }),
1179 }
1180 }
1181
1182 pub fn batch_write_disposition(&self) -> Option<DomainDisposition> {
1184 match self {
1185 Self::BatchWrite { context } => Some(context.disposition),
1186 Self::RefusedWithEvents { context } => context.source.batch_write_disposition(),
1187 Self::SearchRead { context } => context.source.batch_write_disposition(),
1188 _ => None,
1189 }
1190 }
1191
1192 pub fn with_resolution(self, resolution: ResolutionFacts) -> Self {
1194 Self::WithResolution {
1195 context: ResolutionFailureContext {
1196 source: Box::new(self),
1197 resolution,
1198 },
1199 }
1200 }
1201
1202 pub fn with_refusal_events(self, mut recordings: Vec<RefusalEventRecording>) -> Self {
1205 if recordings.is_empty() {
1206 return self;
1207 }
1208 match self {
1209 Self::RefusedWithEvents { mut context } => {
1210 context.recordings.append(&mut recordings);
1211 Self::RefusedWithEvents { context }
1212 }
1213 source => Self::RefusedWithEvents {
1214 context: RefusalEventContext {
1215 source: Box::new(source),
1216 recordings,
1217 },
1218 },
1219 }
1220 }
1221
1222 pub fn refusal_source(&self) -> &Self {
1225 let mut error = self;
1226 loop {
1227 error = match error {
1228 Self::RefusedWithEvents { context } => &context.source,
1229 Self::BatchWrite { context } => &context.source,
1230 Self::WithResolution { context } => context.source.as_ref(),
1231 Self::SearchRead { context } => context.source.as_ref(),
1232 Self::LintFix { source, .. } => source.as_ref(),
1233 Self::CanonicalAdmission { source, .. } => source.as_ref(),
1234 _ => return error,
1235 };
1236 }
1237 }
1238
1239 pub fn is_stream_policy_refusal(&self) -> bool {
1246 matches!(self.refusal_source(), Self::Khive(error)
1247 if error.kind() == khive_types::ErrorKind::Conflict
1248 && error.details().and_then(|details| details.get("reason"))
1249 == Some("stream_member"))
1250 }
1251
1252 pub fn permission_denied(verb: impl Into<String>, reason: impl Into<String>) -> Self {
1254 Self::PermissionDenied {
1255 verb: verb.into(),
1256 reason: reason.into(),
1257 receipt: Box::new(DenialReceipt::not_audited()),
1258 }
1259 }
1260
1261 pub fn internal_with_context(context: impl fmt::Display, source: impl fmt::Display) -> Self {
1266 Self::Internal(format!("{context}: {source}"))
1267 }
1268
1269 pub fn channel_ingest_failure_class(&self) -> ChannelIngestFailureClass {
1277 let source = self.refusal_source();
1278 let reason = source.variant_name();
1279 if source.retryable_failure_context().is_some() {
1280 ChannelIngestFailureClass::Retryable { reason }
1281 } else if matches!(source, Self::SecretDetected(_)) {
1282 ChannelIngestFailureClass::Permanent { reason }
1283 } else {
1284 ChannelIngestFailureClass::Unknown { reason }
1285 }
1286 }
1287
1288 fn variant_name(&self) -> &'static str {
1290 match self {
1291 Self::AuditObligation { .. } => "AuditObligation",
1292 Self::Storage(_) => "Storage",
1293 Self::Query(_) => "Query",
1294 Self::NotFound(_) => "NotFound",
1295 Self::InvalidInput(_) => "InvalidInput",
1296 Self::UnknownVerb(_) => "UnknownVerb",
1297 Self::Unconfigured(_) => "Unconfigured",
1298 Self::UnknownModel(_) => "UnknownModel",
1299 Self::Embedding(_) => "Embedding",
1300 Self::Ambiguous(_) => "Ambiguous",
1301 Self::Fusion(_) => "Fusion",
1302 Self::UnknownFusionStrategy(_) => "UnknownFusionStrategy",
1303 Self::Internal(_) => "Internal",
1304 Self::GuardedWriteFailed(_) => "GuardedWriteFailed",
1305 Self::MissingPackDependency(_) => "MissingPackDependency",
1306 Self::MissingPackDependencies(_) => "MissingPackDependencies",
1307 Self::CircularPackDependency(_) => "CircularPackDependency",
1308 Self::PackRedeclared { .. } => "PackRedeclared",
1309 Self::VerbCollision { .. } => "VerbCollision",
1310 Self::ReservedEnvelopeParam { .. } => "ReservedEnvelopeParam",
1311 Self::PermissionDenied { .. } => "PermissionDenied",
1312 Self::GateUnavailable { .. } => "GateUnavailable",
1313 Self::Khive(_) => "Khive",
1314 Self::NamespaceMismatch { .. } => "NamespaceMismatch",
1315 Self::AmbiguousPrefix { .. } => "AmbiguousPrefix",
1316 Self::CrossBackendMergeUnsupported { .. } => "CrossBackendMergeUnsupported",
1317 Self::UnknownRemote { .. } => "UnknownRemote",
1318 Self::RemoteCacheMissing { .. } => "RemoteCacheMissing",
1319 Self::AmbiguousId { .. } => "AmbiguousId",
1320 Self::CrossNamespaceWrite { .. } => "CrossNamespaceWrite",
1321 Self::RemoteFetchError { .. } => "RemoteFetchError",
1322 Self::WriteBudgetExceeded { .. } => "WriteBudgetExceeded",
1323 Self::SecretDetected(_) => "SecretDetected",
1324 Self::DeadlineExceeded { .. } => "DeadlineExceeded",
1325 Self::AttachmentCutoverRequired { .. } => "AttachmentCutoverRequired",
1326 Self::IncompatibleEventStore(_) => "IncompatibleEventStore",
1327 Self::RefusedWithReceipt { .. } => "RefusedWithReceipt",
1328 Self::RefusedWithEvents { context } => context.source.variant_name(),
1329 Self::BatchWrite { context } => context.source.variant_name(),
1330 Self::WithResolution { context } => context.source.variant_name(),
1331 Self::SearchRead { context } => context.source.variant_name(),
1332 Self::LintFix { source, .. } => source.variant_name(),
1333 Self::CanonicalAdmission { source, .. } => source.variant_name(),
1334 Self::CanonicalUnsupportedOperation { .. } => "CanonicalUnsupportedOperation",
1335 }
1336 }
1337
1338 pub fn writer_pool_checkout_timeout_context(&self) -> Option<WriterPoolCheckoutTimeoutContext> {
1345 let (sqlite_error, capability, operation) = match self.refusal_source() {
1346 Self::Storage(khive_storage::StorageError::Driver {
1347 capability,
1348 operation,
1349 source,
1350 }) => (
1351 source.downcast_ref::<khive_db::SqliteError>()?,
1352 Some(*capability),
1353 Some(operation.to_string()),
1354 ),
1355 _ => return None,
1356 };
1357
1358 let khive_db::SqliteError::WriterPoolCheckoutTimeout { timeout } = sqlite_error else {
1359 return None;
1360 };
1361 Some(WriterPoolCheckoutTimeoutContext {
1362 timeout: *timeout,
1363 capability,
1364 operation,
1365 })
1366 }
1367
1368 pub fn admission_failure_context(&self) -> Option<AdmissionFailureContext> {
1373 let source = self.refusal_source();
1374 if let Some(context) = self.writer_pool_checkout_timeout_context() {
1375 return Some(AdmissionFailureContext {
1376 stage: WRITER_POOL_CHECKOUT_TIMEOUT_STAGE,
1377 timeout: context.timeout,
1378 capability: context.capability,
1379 operation: context.operation,
1380 pool_identity: None,
1381 scope: None,
1382 retry_after_ms: None,
1383 });
1384 }
1385 if let Self::Storage(khive_storage::StorageError::WriteQueueFull { timeout_ms }) = source {
1386 return Some(AdmissionFailureContext {
1387 stage: WRITER_QUEUE_SATURATED_STAGE,
1388 timeout: Duration::from_millis(*timeout_ms),
1389 capability: None,
1390 operation: None,
1391 pool_identity: None,
1392 scope: Some(WRITER_ADMISSION_SCOPE),
1393 retry_after_ms: Some(*timeout_ms),
1394 });
1395 }
1396 if let Self::Storage(khive_storage::StorageError::AdmissionTimeout {
1397 operation,
1398 timeout_ms,
1399 pool_identity,
1400 }) = source
1401 {
1402 return Some(AdmissionFailureContext {
1403 stage: STORAGE_ADMISSION_TIMEOUT_STAGE,
1404 timeout: Duration::from_millis(*timeout_ms),
1405 capability: None,
1406 operation: Some(operation.to_string()),
1407 pool_identity: pool_identity.clone(),
1408 scope: None,
1409 retry_after_ms: None,
1410 });
1411 }
1412 None
1413 }
1414
1415 pub fn writer_task_failure_context(&self) -> Option<WriterTaskFailureContext> {
1419 let Self::Storage(error) = self.refusal_source() else {
1420 return None;
1421 };
1422 match error.without_sqlite_write_stage() {
1423 khive_storage::StorageError::WriteOutcomeUnknown { .. } => {
1424 Some(WriterTaskFailureContext {
1425 stage: WRITE_OUTCOME_UNKNOWN_STAGE,
1426 request_state: khive_storage::WriterTaskRequestState::SideEffectsUnknown,
1427 task_terminated: false,
1428 retryable: false,
1429 })
1430 }
1431 khive_storage::StorageError::WriterOwnerUnavailable { source, .. } => {
1432 Some(WriterTaskFailureContext {
1433 stage: WRITER_OWNER_UNAVAILABLE_STAGE,
1434 request_state: khive_storage::WriterTaskRequestState::NotStarted,
1435 task_terminated: false,
1436 retryable: source.is_retryable(),
1437 })
1438 }
1439 khive_storage::StorageError::WriterRouteViolation { .. } => {
1440 Some(WriterTaskFailureContext {
1441 stage: WRITER_ROUTE_VIOLATION_STAGE,
1442 request_state: khive_storage::WriterTaskRequestState::NotStarted,
1443 task_terminated: false,
1444 retryable: false,
1445 })
1446 }
1447 khive_storage::StorageError::WriterTaskRequestFailed {
1448 request_state,
1449 source,
1450 } => Some(WriterTaskFailureContext {
1451 stage: WRITER_TASK_REQUEST_FAILED_STAGE,
1452 request_state: *request_state,
1453 task_terminated: false,
1454 retryable: source.is_retryable(),
1455 }),
1456 khive_storage::StorageError::WriterTaskTerminated { request_state, .. } => {
1457 Some(WriterTaskFailureContext {
1458 stage: WRITER_TASK_TERMINATED_STAGE,
1459 request_state: *request_state,
1460 task_terminated: true,
1461 retryable: false,
1462 })
1463 }
1464 _ => None,
1465 }
1466 }
1467
1468 pub fn retryable_failure_context(&self) -> Option<RetryableFailureContext> {
1471 let mut enclosing = self;
1472 loop {
1473 match enclosing {
1474 Self::LintFix { .. } => return None,
1475 Self::RefusedWithEvents { context } => enclosing = &context.source,
1476 Self::BatchWrite { context } => enclosing = &context.source,
1477 Self::WithResolution { context } => enclosing = &context.source,
1478 Self::SearchRead { context } => enclosing = &context.source,
1479 _ => break,
1480 }
1481 }
1482
1483 let source = self.refusal_source();
1484 if let Some(context) = self.admission_failure_context() {
1485 return Some(context.into());
1486 }
1487 if let Self::Storage(error) = source {
1488 if let khive_storage::StorageError::WriterOwnerUnavailable { operation, source } =
1489 error.without_sqlite_write_stage()
1490 {
1491 if source.is_retryable() {
1492 return Some(RetryableFailureContext {
1493 stage: WRITER_OWNER_UNAVAILABLE_STAGE,
1494 timeout: Duration::ZERO,
1495 capability: source.capability(),
1496 operation: Some(operation.to_string()),
1497 pool_identity: None,
1498 scope: None,
1499 retry_after_ms: None,
1500 });
1501 }
1502 }
1503 if let khive_storage::StorageError::WriterTaskBusy { timeout_ms } =
1504 error.without_sqlite_write_stage()
1505 {
1506 return Some(RetryableFailureContext {
1507 stage: WRITER_TASK_BEGIN_BUSY_STAGE,
1508 timeout: Duration::from_millis(*timeout_ms),
1509 capability: None,
1510 operation: Some("writer_task_begin".to_string()),
1511 pool_identity: None,
1512 scope: None,
1513 retry_after_ms: None,
1514 });
1515 }
1516 }
1517 if let Self::Storage(khive_storage::StorageError::ReadTransactionAgeEvicted {
1518 operation,
1519 max_age_secs,
1520 }) = source
1521 {
1522 return Some(RetryableFailureContext {
1523 stage: READ_TX_AGE_EVICTED_STAGE,
1524 timeout: Duration::from_secs(*max_age_secs),
1525 capability: Some(khive_storage::StorageCapability::Sql),
1526 operation: Some(operation.to_string()),
1527 pool_identity: None,
1528 scope: None,
1529 retry_after_ms: None,
1530 });
1531 }
1532 if let Self::Storage(
1533 khive_storage::StorageError::ReadTransactionAgeEvictionCleanupFailed {
1534 operation,
1535 max_age_secs,
1536 ..
1537 },
1538 ) = source
1539 {
1540 return Some(RetryableFailureContext {
1541 stage: READ_TX_AGE_EVICTED_STAGE,
1542 timeout: Duration::from_secs(*max_age_secs),
1543 capability: Some(khive_storage::StorageCapability::Sql),
1544 operation: Some(operation.to_string()),
1545 pool_identity: None,
1546 scope: None,
1547 retry_after_ms: None,
1548 });
1549 }
1550 None
1551 }
1552}
1553
1554pub fn fts_text_leg_or_err<T>(
1561 result: Result<Vec<T>, RuntimeError>,
1562 context: &'static str,
1563 query: &str,
1564) -> RuntimeResult<Vec<T>> {
1565 match result {
1566 Ok(hits) => Ok(hits),
1567 Err(RuntimeError::Storage(se)) if se.is_fts5_syntax_error() => {
1568 tracing::warn!(
1569 error = %se,
1570 query = %query,
1571 context,
1572 "FTS text leg failed on a parser syntax error; failing loud (#569)"
1573 );
1574 Err(RuntimeError::InvalidInput(format!(
1575 "{context}: FTS query could not be parsed: {se}"
1576 )))
1577 }
1578 Err(e) => Err(e),
1579 }
1580}
1581
1582fn format_uuid_list(uuids: &[uuid::Uuid]) -> String {
1583 uuids
1584 .iter()
1585 .map(uuid::Uuid::to_string)
1586 .collect::<Vec<_>>()
1587 .join(", ")
1588}
1589
1590impl From<khive_types::EntityTypeError> for RuntimeError {
1594 fn from(e: khive_types::EntityTypeError) -> Self {
1595 Self::InvalidInput(e.to_string())
1596 }
1597}
1598
1599impl From<khive_types::KhiveError> for RuntimeError {
1600 fn from(e: khive_types::KhiveError) -> Self {
1601 Self::Khive(e)
1602 }
1603}
1604
1605#[cfg(test)]
1606#[path = "error_refusal_event_context_tests.rs"]
1607mod refusal_event_context_tests;
1608
1609#[cfg(test)]
1610#[path = "error_stream_policy_refusal_tests.rs"]
1611mod stream_policy_refusal_tests;
1612
1613#[cfg(test)]
1614#[path = "error_channel_ingest_failure_class_tests.rs"]
1615mod channel_ingest_failure_class_tests;
1616
1617#[cfg(test)]
1618mod batch_write_proof_tests {
1619 use super::*;
1620 use crate::runtime_error_value;
1621
1622 fn proof() -> RuntimeError {
1623 RuntimeError::InvalidInput("fixture-prewrite-refusal".into()).before_requested_write()
1624 }
1625
1626 fn project_failed(source: RuntimeError) -> (DomainDisposition, serde_json::Value) {
1627 let error = DispatchError::after_handler(source, false);
1628 let borrowed = error.disposition();
1629 let (source, disposition) = error.into_parts();
1630 assert_eq!(borrowed, disposition);
1631 let value = runtime_error_value(source, disposition);
1632 assert_eq!(value["domain_disposition"], disposition.as_str());
1633 (disposition, value)
1634 }
1635
1636 #[test]
1637 fn rejected_before_write_preserves_enclosing_disposition_and_error_class() {
1638 let message = "decoding refused";
1639 let (disposition, value) =
1640 project_failed(RuntimeError::InvalidInput(message.into()).before_requested_write());
1641 assert_eq!(disposition, DomainDisposition::NotCommitted);
1642 assert_eq!(value["kind"], "runtime_error");
1643 assert_eq!(value["message"], format!("invalid input: {message}"));
1644 assert_eq!(
1645 RuntimeError::InvalidInput(message.into())
1646 .before_requested_write()
1647 .audit_error_class(),
1648 crate::audit_error::AuditErrorClass::InvalidParams
1649 );
1650 let (ordinary, _) = project_failed(RuntimeError::InvalidInput(message.into()));
1651 assert_eq!(ordinary, DomainDisposition::Unknown);
1652
1653 let enclosing = RuntimeError::InvalidInput(message.into())
1654 .before_requested_write()
1655 .with_resolution(ResolutionFacts {
1656 project_id: Uuid::new_v4(),
1657 duplicate_anchor_ids: vec![],
1658 slug_backfilled: false,
1659 project_created: true,
1660 orphaned_project_id: None,
1661 orphaned_note_count: 0,
1662 });
1663 let (disposition, _) = project_failed(enclosing);
1664 assert_eq!(disposition, DomainDisposition::Unknown);
1665 let committed = DispatchError::after_handler(
1666 RuntimeError::InvalidInput(message.into()).before_requested_write(),
1667 true,
1668 );
1669 assert_eq!(committed.disposition(), DomainDisposition::Committed);
1670 let (source, disposition) = committed.into_parts();
1671 assert_eq!(
1672 runtime_error_value(source, disposition)["domain_disposition"],
1673 "committed"
1674 );
1675 }
1676
1677 #[test]
1678 fn batch_proof_reaches_dispatch_owned_parts_and_projection() {
1679 let (disposition, value) = project_failed(proof());
1680 assert_eq!(disposition, DomainDisposition::NotCommitted);
1681 assert!(value["message"]
1682 .as_str()
1683 .unwrap()
1684 .contains("fixture-prewrite-refusal"));
1685 for source in [
1686 RuntimeError::InvalidInput("ordinary".into()),
1687 RuntimeError::Storage(khive_storage::StorageError::Internal(
1688 "ordinary-storage".into(),
1689 )),
1690 ] {
1691 assert_eq!(project_failed(source).0, DomainDisposition::Unknown);
1692 }
1693 }
1694
1695 #[test]
1696 fn enclosing_success_and_unknown_contexts_protect_prior_effects() {
1697 let error = DispatchError::after_handler(proof(), true);
1698 assert_eq!(error.disposition(), DomainDisposition::Committed);
1699 let (source, disposition) = error.into_parts();
1700 assert_eq!(
1701 runtime_error_value(source, disposition)["domain_disposition"],
1702 "committed"
1703 );
1704 assert_eq!(
1705 runtime_error_value(proof(), DomainDisposition::Committed)["domain_disposition"],
1706 "committed"
1707 );
1708 let source = proof().with_resolution(ResolutionFacts {
1709 project_id: Uuid::nil(),
1710 duplicate_anchor_ids: vec![],
1711 slug_backfilled: false,
1712 project_created: true,
1713 orphaned_project_id: None,
1714 orphaned_note_count: 0,
1715 });
1716 assert_eq!(
1717 source.batch_write_disposition(),
1718 None,
1719 "enclosing earlier work blocks an inner no-write proof"
1720 );
1721 let (disposition, value) = project_failed(source);
1722 assert_eq!(disposition, DomainDisposition::Unknown);
1723 assert_eq!(value["details"]["resolution"]["project_created"], true);
1724 }
1725
1726 #[test]
1727 fn batch_evidence_preserves_original_source_and_writer_finality() {
1728 let source = RuntimeError::atomic_write_failure(
1729 khive_storage::StorageError::WriterTaskRequestFailed {
1730 request_state: khive_storage::WriterTaskRequestState::TransactionRolledBack,
1731 source: Box::new(khive_storage::StorageError::Internal(
1732 "fixture-original-cause".into(),
1733 )),
1734 },
1735 )
1736 .with_refusal_events(vec![RefusalEventRecording::Recorded {
1737 item_index: 0,
1738 subject: Uuid::nil(),
1739 event_id: Uuid::nil(),
1740 }]);
1741 assert!(matches!(source.refusal_source(), RuntimeError::Storage(_)));
1742 assert_eq!(
1743 source.writer_task_failure_context().unwrap().request_state,
1744 khive_storage::WriterTaskRequestState::TransactionRolledBack
1745 );
1746 let mut cause: &(dyn std::error::Error + 'static) = &source;
1747 let mut retained = false;
1748 while let Some(next) = cause.source() {
1749 retained |= next.to_string().contains("fixture-original-cause");
1750 cause = next;
1751 }
1752 assert!(retained, "typed cause remains below the outer error");
1753 let (disposition, value) = project_failed(source);
1754 assert_eq!(disposition, DomainDisposition::NotCommitted);
1755 assert_eq!(value["request_state"], "transaction_rolled_back");
1756 assert_eq!(value["refusal_recorded"], true);
1757 let source = RuntimeError::atomic_write_failure(
1758 khive_storage::StorageError::writer_task_terminated(
1759 khive_storage::WriterTaskRequestState::SideEffectsUnknown,
1760 ),
1761 );
1762 assert_eq!(project_failed(source).0, DomainDisposition::Unknown);
1763 }
1764}