qubit_fs_testkit/contract_failure.rs
1// =============================================================================
2// Copyright (c) 2026 Haixing Hu.
3//
4// SPDX-License-Identifier: Apache-2.0
5//
6// Licensed under the Apache License, Version 2.0.
7// =============================================================================
8//! Preserved diagnostics from contract execution and cleanup.
9
10use std::any::Any;
11use std::error::Error;
12use std::fmt::Debug;
13use std::fmt::Display;
14use std::fmt::Formatter;
15use std::fmt::Result as FmtResult;
16use std::sync::Mutex;
17
18use crate::ContractCheckId;
19
20/// A failure with safe context and its original typed cause.
21///
22/// Formatting never invokes the provider's arbitrary `Debug` implementation.
23/// A panic payload remains available for explicit caller inspection.
24///
25/// # Examples
26///
27/// ```
28/// # mod support { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/common/rustdoc_support.rs")); }
29/// # use support::RustdocSyncFixture;
30/// use qubit_fs_testkit::{ContractFailure, FileSystemContract, FileSystemContractSuite};
31///
32/// let fixture = RustdocSyncFixture::new();
33/// let mut suite = FileSystemContractSuite::new(&fixture);
34/// suite.run_contract(FileSystemContract::Properties);
35/// suite.run_contract(FileSystemContract::Stat);
36/// let report = suite.run();
37/// assert!(!report.failures().is_empty());
38/// let failure: &ContractFailure = &report.failures()[0];
39/// assert!(failure.message().contains("session already started"));
40/// ```
41#[must_use]
42pub struct ContractFailure {
43 /// The execution entry associated with this failure, when known.
44 check: Option<ContractCheckId>,
45 /// Safe context that can be displayed without formatting the cause.
46 message: String,
47 /// The original typed error, retained for standard error-chain inspection.
48 source: Option<Box<dyn Error + Send + Sync>>,
49 /// The original panic payload, available for one-time ownership transfer.
50 panic: Mutex<Option<Box<dyn Any + Send>>>,
51}
52
53impl ContractFailure {
54 /// Returns the check identity when execution could attribute the failure.
55 ///
56 /// # Returns
57 ///
58 /// The execution check identity, or `None` when no check was associated
59 /// with the failure.
60 #[inline]
61 pub const fn check(&self) -> Option<ContractCheckId> {
62 self.check
63 }
64
65 /// Returns the diagnostic context without formatting its underlying cause.
66 ///
67 /// # Returns
68 ///
69 /// The safe diagnostic context stored with this failure.
70 #[must_use]
71 #[inline]
72 pub fn message(&self) -> &str {
73 &self.message
74 }
75
76 /// Takes the original panic payload, preserving its concrete type.
77 ///
78 /// This transfers ownership through a borrowed run. Returns `None` when
79 /// the failure was not a panic or another caller already took its payload.
80 /// Taking the payload does not remove the failure from the run's history.
81 ///
82 /// # Returns
83 ///
84 /// The original panic payload when one is retained and has not already
85 /// been taken; otherwise, `None`.
86 pub fn take_panic_payload(&self) -> Option<Box<dyn Any + Send>> {
87 self.panic.lock().unwrap_or_else(|poison| poison.into_inner()).take()
88 }
89
90 /// Constructs a failure without an underlying provider cause.
91 ///
92 /// # Parameters
93 ///
94 /// - `message`: Safe diagnostic context describing the failure.
95 pub(crate) fn message_only(message: impl Into<String>) -> Self {
96 Self {
97 check: None,
98 message: message.into(),
99 source: None,
100 panic: Mutex::new(None),
101 }
102 }
103
104 /// Retains the typed source separately from safe diagnostic context.
105 ///
106 /// # Parameters
107 ///
108 /// - `message`: Safe diagnostic context that may be displayed.
109 /// - `source`: The typed error retained for source-chain inspection.
110 pub(crate) fn with_source(message: impl Into<String>, source: impl Error + Send + Sync + 'static) -> Self {
111 Self {
112 check: None,
113 message: message.into(),
114 source: Some(Box::new(source)),
115 panic: Mutex::new(None),
116 }
117 }
118
119 /// Retains errors that own a non-Sync recovery handle without discarding
120 /// it.
121 ///
122 /// # Parameters
123 ///
124 /// - `message`: Safe diagnostic context that may be displayed.
125 /// - `source`: The error and non-`Sync` recovery handle to retain.
126 pub(crate) fn with_owned_source(message: impl Into<String>, source: impl Error + Send + 'static) -> Self {
127 Self::with_source(message, crate::ContractSource::new(source))
128 }
129
130 /// Preserves an unexpected panic at the external execution boundary.
131 ///
132 /// # Parameters
133 ///
134 /// - `context`: Safe operation context included in the diagnostic message.
135 /// - `payload`: The original panic payload, retained for caller inspection.
136 pub(crate) fn panicked(context: &str, payload: Box<dyn Any + Send>) -> Self {
137 let detail = payload
138 .downcast_ref::<String>()
139 .map(String::as_str)
140 .or_else(|| payload.downcast_ref::<&str>().copied());
141 let message = match detail {
142 Some(detail) => format!("{context}: {detail}"),
143 None => format!("{context}: non-string panic payload retained"),
144 };
145 Self {
146 check: None,
147 message,
148 source: None,
149 panic: Mutex::new(Some(payload)),
150 }
151 }
152
153 /// Attributes a preserved failure to its typed execution entry.
154 ///
155 /// # Parameters
156 ///
157 /// - `check`: The contract check responsible for the failure.
158 pub(crate) fn at(mut self, check: ContractCheckId) -> Self {
159 self.check = Some(check);
160 self
161 }
162}
163
164impl Debug for ContractFailure {
165 /// Formats safe context without invoking the retained cause formatter.
166 ///
167 /// # Parameters
168 ///
169 /// - `formatter`: Destination for the safe failure summary.
170 fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
171 formatter
172 .debug_struct("ContractFailure")
173 .field("check", &self.check)
174 .field("message", &self.message)
175 .finish_non_exhaustive()
176 }
177}
178
179impl Display for ContractFailure {
180 /// Formats the check identity and safe diagnostic context.
181 ///
182 /// # Parameters
183 ///
184 /// - `formatter`: Destination for the diagnostic description.
185 fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
186 if let Some(check) = self.check {
187 write!(formatter, "{check}: ")?;
188 }
189 formatter.write_str(&self.message)
190 }
191}
192
193impl Error for ContractFailure {
194 /// Returns the typed cause retained for standard error-chain inspection.
195 fn source(&self) -> Option<&(dyn Error + 'static)> {
196 self.source.as_deref().map(|source| source as &(dyn Error + 'static))
197 }
198}
199
200#[cfg(test)]
201mod tests {
202 use std::panic::AssertUnwindSafe;
203
204 use super::ContractFailure;
205
206 #[test]
207 fn test_poisoned_panic_lock_still_allows_payload_transfer() {
208 let failure = ContractFailure::panicked("contract", Box::new(String::from("retained panic")));
209 let _ = std::panic::catch_unwind(AssertUnwindSafe(|| {
210 let _guard = failure.panic.lock().unwrap();
211 panic!("poison panic lock");
212 }));
213 assert_eq!(
214 failure
215 .take_panic_payload()
216 .unwrap()
217 .downcast::<String>()
218 .unwrap()
219 .as_str(),
220 "retained panic"
221 );
222 assert!(failure.take_panic_payload().is_none());
223 }
224}