ktstr/assert/
detail.rs

1use super::*;
2
3/// Category tag for an [`AssertDetail`]. Enables structural filtering
4/// (e.g. by `AssertPlan`) without matching on substrings of
5/// human-readable messages, which is fragile if wording changes.
6///
7/// Notes previously lived as a `DetailKind::Note` variant on
8/// [`AssertDetail`]; they now live on [`AssertResult::info_notes`] as
9/// [`InfoNote`] values. See [`AssertResult::note`] /
10/// [`AssertResult::with_note`] for the producer-side migration and
11/// [`InfoNote`] for the rationale (structurally-separate context
12/// stream so sidecar consumers iterating `details` count only real
13/// failures without a "forgot to filter `kind == Note`" miscount
14/// class of bug).
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
16pub enum DetailKind {
17    /// A worker made zero progress.
18    NoProgress,
19    /// A worker was stuck off-CPU longer than the gap threshold.
20    Stuck,
21    /// Spread between best and worst worker exceeded the fairness threshold.
22    Unfair,
23    /// A worker ran on a CPU outside its expected cpuset.
24    Isolation,
25    /// Throughput / benchmarking threshold failure (p99, CV, rate).
26    Benchmark,
27    /// Migration-ratio threshold failure (migrations per iteration).
28    Migration,
29    /// NUMA page locality threshold failure.
30    PageLocality,
31    /// Cross-node migration threshold failure.
32    CrossNodeMigration,
33    /// Slow-tier (memory tier) threshold failure.
34    SlowTier,
35    /// Monitor-subsystem anomaly (imbalance, DSQ depth, rq_clock stuck).
36    /// Use one of [`DetailKind::SchedulerCrashed`] /
37    /// [`DetailKind::SchedulerExitedCleanly`] /
38    /// [`DetailKind::SchedulerDiedUnknownReason`] for scheduler-liveness failures.
39    Monitor,
40    /// Scheduler process observed to have died (via `sched_pid`
41    /// probe returning ESRCH or wait on the leader) AND the BPF
42    /// probe observed a non-clean scheduler exit through the
43    /// kernel-selected trigger
44    /// before the liveness check fired. The crash classification
45    /// covers SCX_EXIT_ERROR, SCX_EXIT_ERROR_STALL, watchdog kick,
46    /// and BPF-side error paths — every kernel exit that latches
47    /// `ktstr_err_exit_detected` in the probe BSS.
48    ///
49    /// Distinguished from [`DetailKind::SchedulerExitedCleanly`]
50    /// (`SCX_EXIT_NONE` clean teardown) so the console-dump gate
51    /// and downstream triage can tell a real crash from a benign
52    /// completion. Consumers wanting to gate on "any scheduler
53    /// exit" should match both variants via
54    /// `matches!(d.kind, SchedulerCrashed | SchedulerExitedCleanly)`.
55    SchedulerCrashed,
56    /// Scheduler process observed to have died with the probe BSS
57    /// `ktstr_err_exit_detected` latch unset — the kernel ran the
58    /// `SCX_EXIT_NONE` clean-teardown path (sysrq, explicit
59    /// unregister) without latching an error. Surfaces alongside
60    /// `SchedulerCrashed` because both are "scheduler exited"
61    /// signals; splitting them lets the operator distinguish a
62    /// benign shutdown from a real fault without re-parsing
63    /// console output.
64    SchedulerExitedCleanly,
65    /// Scheduler process observed to have died but the BPF probe
66    /// has no classification yet — either the probe never armed
67    /// for this run (no scheduler attached, host-only test) or
68    /// the poll thread has not completed a first iteration since
69    /// the prior reset. Operators triaging this variant should
70    /// check whether the probe pipeline was wired before
71    /// concluding "scheduler-exit classification is broken".
72    SchedulerDiedUnknownReason,
73    /// SCX event-counter threshold failure. An error-class
74    /// `SCX_EV_*` counter (e.g. `enq_skip_exiting`,
75    /// `enq_skip_migration_disabled`, `dispatch_local_dsq_offline`) crossed
76    /// the configured bound. Distinct from the process-liveness
77    /// variants ([`DetailKind::SchedulerCrashed`] /
78    /// [`DetailKind::SchedulerExitedCleanly`] /
79    /// [`DetailKind::SchedulerDiedUnknownReason`]) and
80    /// [`DetailKind::Monitor`] (imbalance / DSQ-depth /
81    /// rq_clock-stuck): this kind flags individual event-counter
82    /// regressions surfaced by [`assert_scx_events_clean`]. The
83    /// counters themselves originate in the kernel's per-task
84    /// `scx_event_stats` (see `kernel/sched/ext.c` —
85    /// `SCX_EV_*` macros); ktstr reads aggregated deltas via
86    /// `monitor::ScxEventDeltas` and presents them to the
87    /// assertion as `(name, count)` pairs.
88    SchedulerEvent,
89    /// Temporal assertion failure on a periodic-capture
90    /// [`SampleSeries`](crate::scenario::sample::SampleSeries).
91    /// One of the seven built-in patterns
92    /// (`nondecreasing` / `strictly_increasing`, `rate_within`,
93    /// `steady_within`, `converges_to`, `always_true`,
94    /// `ratio_within`) or a per-sample scalar comparator
95    /// invoked via `.each(...)` reported a violation. The
96    /// detail message names the pattern, the offending sample
97    /// tag(s), and the observed-vs-expected values; the
98    /// stdout `--- temporal assertions ---` summary in
99    /// `test_support::output` aggregates the same kind into
100    /// per-assertion pass/fail rows.
101    Temporal,
102    /// Host-mode stuck worker detected by
103    /// [`crate::scenario::host_stuck`]. The polling thread
104    /// observed `Δnr_switches == 0` AND `Δsum_exec_runtime == 0`
105    /// across the configured window for a worker pid — the task
106    /// neither got picked nor preempted for at least
107    /// `STUCK_WINDOW * poll_interval` ms. Distinct from
108    /// [`DetailKind::Stuck`] (worker-side report: a worker was
109    /// off-CPU longer than the in-test gap threshold): this kind
110    /// fires from the host-side polling thread when running
111    /// host-mode (no VM boot) and is the only stuck-worker signal
112    /// available in that mode.
113    WorkerStuck,
114    /// Skip notification (scenario could not run under this topology/flags).
115    Skip,
116    /// Uncategorized — falls through when a detail has no specific kind.
117    Other,
118    /// Performance-mode host-isolation fault: a `performance_mode` cell's
119    /// Body-phase dilation `D` exceeded the perf-isolation ceiling
120    /// (`PERF_ISOLATION_D_MAX`, in `vmm::freeze_coord::latency_verdict`),
121    /// so its 1:1-pinned vCPUs lost their dedicated host CPUs. Recorded
122    /// HOST-side at the eval seam (never crosses the guest→host wire), so
123    /// its postcard variant index is unobserved; still appended LAST to
124    /// preserve the append-only wire ordering the other variants rely on.
125    /// This is an infra/isolation fault (the run's timing verdicts are
126    /// untrustworthy), NOT a scheduler-under-test fault.
127    PerfIsolation,
128}
129
130/// Message prefix emitted by every scenario-runner site that
131/// detects the scheduler process has died — whether through a
132/// post-ops liveness probe or an inter-step liveness check. Both
133/// paths share this single prefix as the operator-visible
134/// message format so someone grepping stderr for the canonical
135/// "scheduler process died" string hits every emission site.
136/// Structural routing (the console-dump gate in
137/// `test_support::eval`) goes through the `DetailKind::Scheduler*`
138/// variants ([`DetailKind::SchedulerCrashed`] /
139/// [`DetailKind::SchedulerExitedCleanly`] /
140/// [`DetailKind::SchedulerDiedUnknownReason`]),
141/// NOT this prefix — the prefix is a human-readability contract,
142/// not a detection mechanism. Exposed as `pub(crate)` so emitters
143/// reference the same literal; renaming the prefix is a one-site
144/// edit instead of a grep-and-hope across `scenario::*`.
145///
146/// Vocabulary history: prior versions of this module used two
147/// prefixes (`SCHED_EXITED_PREFIX` = "scheduler process exited"
148/// and `SCHED_NO_LONGER_RUNNING_PREFIX` = "scheduler process no
149/// longer running") for in-workload vs post-ops detection. The
150/// distinction carried no downstream semantics — every consumer
151/// treated both as equivalent scheduler-death signals — so the
152/// wording was unified onto "died" (shorter, matches the prior
153/// `SchedulerDied` variant name, and closes a class of "which
154/// wording does this site use?" drift bugs).
155pub(crate) const SCHED_DIED_PREFIX: &str = "scheduler process died";
156
157/// Format the scheduler-died detail message for an inter-step
158/// liveness-probe failure (the scheduler was alive after step
159/// `step_idx - 1` but ESRCH'd before step `step_idx` ran).
160///
161/// Begins with [`SCHED_DIED_PREFIX`] verbatim, followed by
162/// "unexpectedly after completing step N of M (X.Xs into test)".
163/// The prefix is the operator-visible stderr anchor (see the
164/// prefix doc); structural routing is via one of
165/// [`DetailKind::SchedulerCrashed`] /
166/// [`DetailKind::SchedulerExitedCleanly`] /
167/// [`DetailKind::SchedulerDiedUnknownReason`] on the emitted `AssertDetail`.
168/// Centralized so ops.rs and any future emitter share a single
169/// format.
170pub(crate) fn format_sched_died_after_step(
171    step_idx: usize,
172    total_steps: usize,
173    elapsed_s: f64,
174) -> String {
175    format!(
176        "{SCHED_DIED_PREFIX} unexpectedly after completing step {step_idx} of {total_steps} ({elapsed_s:.1}s into test)",
177    )
178}
179
180/// Format the scheduler-died detail message for the post-loop
181/// liveness probe (the scheduler was alive throughout the step loop
182/// but ESRCH'd after the last step completed).
183///
184/// Begins with [`SCHED_DIED_PREFIX`] verbatim; shares the prefix
185/// invariant documented on [`format_sched_died_after_step`].
186/// Structural routing is via one of [`DetailKind::SchedulerCrashed`] /
187/// [`DetailKind::SchedulerExitedCleanly`] /
188/// [`DetailKind::SchedulerDiedUnknownReason`] on the emitted detail.
189pub(crate) fn format_sched_died_after_all_steps(total_steps: usize, elapsed_s: f64) -> String {
190    format!(
191        "{SCHED_DIED_PREFIX} unexpectedly (detected after all {total_steps} steps completed, {elapsed_s:.1}s elapsed)",
192    )
193}
194
195/// Format the scheduler-died detail message for the in-step
196/// liveness probe (the scheduler ESRCH'd during a step's hold-period
197/// sleep, before the step completed).
198///
199/// Begins with [`SCHED_DIED_PREFIX`] verbatim; shares the prefix
200/// invariant documented on [`format_sched_died_after_step`].
201/// Structural routing is via one of [`DetailKind::SchedulerCrashed`] /
202/// [`DetailKind::SchedulerExitedCleanly`] /
203/// [`DetailKind::SchedulerDiedUnknownReason`] on the emitted detail. Emitted by `run_scenario` when the
204/// liveness-poll inside `run_step`'s hold sleep observes
205/// `process_alive(sched_pid) == false`, replacing the prior
206/// behavior that waited for the post-loop probe to fire (which
207/// stamped the message with the full scenario duration even when
208/// the scheduler had died seconds earlier).
209pub(crate) fn format_sched_died_during_workload(elapsed_s: f64) -> String {
210    format!("{SCHED_DIED_PREFIX} unexpectedly during workload ({elapsed_s:.1}s into test)")
211}
212
213/// Format the scheduler-died message for the guest-side `survives_storm`
214/// post-function liveness probe: the test asserted the scheduler survives, but
215/// after the test function returned it was found dead or down (the leader pid
216/// ESRCH'd, or the scx state went `disabling`/`disabled`) while still expected
217/// to run. Fires for scenarios that do NOT drive an `execute_*` in-hold probe
218/// (which records its own scheduler-death detail via the `format_sched_died_*`
219/// helpers above). Begins with [`SCHED_DIED_PREFIX`] verbatim; structural
220/// routing is via one of [`DetailKind::SchedulerCrashed`] /
221/// [`DetailKind::SchedulerExitedCleanly`] /
222/// [`DetailKind::SchedulerDiedUnknownReason`] on the emitted detail.
223pub(crate) fn format_sched_died_survives_storm() -> String {
224    format!(
225        "{SCHED_DIED_PREFIX} during a survives_storm workload (detected after the test function returned)"
226    )
227}
228
229/// Structured wall-latency-gate evidence carried on a failing
230/// [`AssertDetail`] so the host-side seam can re-run the
231/// contention-aware tri-state verdict (the `latency_verdict` core in
232/// `vmm::freeze_coord`).
233///
234/// The wall-latency ceilings fire IN-GUEST (`assert_benchmarks` runs
235/// inside the VM), but the per-phase contention witness — the Body
236/// dilation `D` and the peak-window host-contention series that bound
237/// `W(measured)` — is measured HOST-side (in `vmm::freeze_coord`) and is
238/// not available where the gate tripped. This struct rides the failing
239/// detail across the wire so the host can pair the guest's `measured_ns`
240/// / `threshold_ns` with its own witness and decide Pass / FailConfirmed
241/// / ContentionIndeterminate.
242///
243/// Set ONLY on ns-denominated latency ceilings where the tri-state is
244/// sound (`max_p99_wake_latency_ns`): the p99 exemplar is a single
245/// guest-wall interval whose contamination `W` bounds. NOT set on the CV
246/// or off-CPU-spread gates — those are dimensionless (a ratio / a
247/// percentage), not ns intervals, so the ns-denominated `W` bound cannot
248/// score them; they stay annotate-only via `dilation_annotation`.
249#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
250pub struct LatencyGate {
251    /// The guest-measured wall-latency exemplar that tripped the gate (ns).
252    pub measured_ns: u64,
253    /// The ceiling it exceeded (ns).
254    pub threshold_ns: u64,
255}
256
257/// A single diagnostic message from an assertion, paired with a
258/// structural [`DetailKind`] so filtering is robust to wording changes.
259///
260/// Access the message text via `detail.message`; format-string probes
261/// (`format!("{detail}")`) work via the `Display` impl. New code that
262/// needs to filter by category should match on `kind` rather than
263/// substring-match the message text — wording can change without
264/// notice but the variant tag is the structural contract.
265#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
266pub struct AssertDetail {
267    pub kind: DetailKind,
268    pub message: String,
269    /// Structured wall-latency-gate evidence for the host contention
270    /// seam ([`LatencyGate`]); `None` on every detail that is not an
271    /// in-scope ns-latency-ceiling failure. Stamped at the gate site via
272    /// [`Self::with_latency_gate`].
273    ///
274    /// `#[serde(default)]` keeps sidecar JSON written before this field
275    /// existed readable (an absent field deserializes to `None`). NO
276    /// `skip_serializing_if`: [`AssertDetail`] crosses the guest→host
277    /// boundary via postcard, which is not self-describing and always
278    /// expects every field in declaration order — a conditionally-elided
279    /// field would desync the decoder. The `Option` is encoded as its
280    /// 1-byte tag either way, matching the sibling `phase` field.
281    #[serde(default)]
282    pub latency_gate: Option<LatencyGate>,
283    /// Scenario phase the detail was emitted under. Mirrors
284    /// [`PassDetail::phase`]: `None` outside any [`PhaseGuard`] scope
285    /// (boot, BASELINE settle, non-scenario test fixtures), `Some`
286    /// when an active guard has installed a label. Carried on every
287    /// detail so consumers (auto-repro renderer, sidecar parsers)
288    /// see a uniform phase field across pass + fail records.
289    /// Producers that already know the active phase can stamp via
290    /// [`Self::with_phase`].
291    ///
292    /// [`Cow`](std::borrow::Cow)`<'static, str>` mirrors [`PassDetail::phase`] for the
293    /// same zero-allocation reason: the common case is the per-step
294    /// RAII guard's static `&'static str` label staying as
295    /// `Cow::Borrowed` (zero alloc); runtime-built `String`s become
296    /// `Cow::Owned`.
297    pub phase: Option<std::borrow::Cow<'static, str>>,
298}
299
300impl AssertDetail {
301    pub fn new(kind: DetailKind, message: impl Into<String>) -> Self {
302        Self {
303            kind,
304            message: message.into(),
305            phase: current_phase_label(),
306            latency_gate: None,
307        }
308    }
309
310    /// Builder-style setter for [`Self::latency_gate`]. Consumes self,
311    /// attaches the guest-measured `measured_ns` / `threshold_ns` so the
312    /// host seam can re-run the contention-aware tri-state verdict, and
313    /// returns the updated detail. Chain at the ns-latency-ceiling gate
314    /// sites: `AssertDetail::new(Benchmark, msg).with_latency_gate(p99,
315    /// limit)`. Only the in-scope wall-latency ceilings set this — see
316    /// [`LatencyGate`] for why CV / spread do not.
317    #[must_use = "builder methods consume self; bind the result"]
318    pub fn with_latency_gate(mut self, measured_ns: u64, threshold_ns: u64) -> Self {
319        self.latency_gate = Some(LatencyGate {
320            measured_ns,
321            threshold_ns,
322        });
323        self
324    }
325
326    /// Builder-style setter for [`Self::phase`]. Consumes self,
327    /// stamps the phase label, returns the updated value. Matches
328    /// the [`PassDetail::with_phase`] shape so producers can chain
329    /// `AssertDetail::new(...).with_phase(...)` uniformly across
330    /// pass and fail records.
331    #[must_use = "builder methods consume self; bind the result"]
332    pub fn with_phase(mut self, phase: impl Into<std::borrow::Cow<'static, str>>) -> Self {
333        self.phase = Some(phase.into());
334        self
335    }
336
337    /// Borrow this detail as a kind-prefixed [`std::fmt::Display`]
338    /// adapter. The default [`Display`](std::fmt::Display) impl on
339    /// `AssertDetail` writes only `message` so terminal output reads
340    /// as bare prose; structured-log consumers that want to bucket
341    /// failures by category without re-checking [`Self::kind`] reach
342    /// for this helper instead.
343    ///
344    /// Renders as `[<DetailKind variant name>] <message>` — debug-form
345    /// for the kind so the variant token is grep-stable across renames
346    /// (a regression that drops a `DetailKind` variant breaks the
347    /// match arms that produce it; the rendered token follows). Zero-
348    /// allocation: the wrapper holds a `&AssertDetail` and writes
349    /// straight into the formatter.
350    ///
351    /// ```
352    /// # use ktstr::assert::{AssertDetail, DetailKind};
353    /// let d = AssertDetail::new(DetailKind::Stuck, "tid 7 stuck 1500ms on cpu3");
354    /// assert_eq!(d.to_string(), "tid 7 stuck 1500ms on cpu3");
355    /// assert_eq!(
356    ///     d.display_with_kind().to_string(),
357    ///     "[Stuck] tid 7 stuck 1500ms on cpu3",
358    /// );
359    /// ```
360    pub fn display_with_kind(&self) -> AssertDetailWithKind<'_> {
361        AssertDetailWithKind { detail: self }
362    }
363}
364
365/// Structured record of a single passing claim — the positive
366/// counterpart to [`AssertDetail`]. Populated by [`Verdict`]'s
367/// `record_pass_unary` / `record_pass_binary` helpers at every
368/// comparator's pass arm so the auto-repro renderer (and any other
369/// consumer that wants per-claim fidelity) can iterate passes
370/// alongside fails.
371///
372/// Carries the same shape primitives every comparator naturally has
373/// at the pass site: the claim's `name`, a short `comparator`
374/// token (`"eq"`, `"ge"`, `"is_finite"`, …), the `value` that was
375/// compared (formatted via the comparator's `Display`), and an
376/// optional `expected` for binary comparators. Unary comparators
377/// (e.g. `is_finite`, `set_is_empty`) leave `expected = None`.
378///
379/// `comparator` is a **wire-canonical token** from
380/// [`COMPARATOR_VOCABULARY`], NOT a string derived from the builder
381/// method name. Operator-named comparators map to operator-canonical
382/// tokens (`eq`/`ne`/`ge`/`le`/`lt`/`gt`) regardless of whether the
383/// invoking builder method is `eq` or `at_least` — tokens are the
384/// stable wire vocabulary, methods are the ergonomic surface. A
385/// renderer that wants pretty operators can map `ge → >=` on output.
386///
387/// Container-bound comparators prefix their tokens with the
388/// container type name (`set_*`, `sequence_*`) to disambiguate same-
389/// named operations across surfaces (`contains` is ambiguous between
390/// sets and sequences, so prefix; `is_finite` is scalar-only, so
391/// bare). The prefix policy is part of the vocabulary contract.
392///
393/// `comparator` is a [`Cow`](std::borrow::Cow)`<'static, str>` so call sites passing a
394/// `&'static str` literal — the universal case for built-in
395/// comparators — pay zero allocation; runtime-built comparator
396/// labels store as `Cow::Owned`. The same `Cow` shape applies to
397/// `phase` (set by the per-step RAII guard's static label in the
398/// common case).
399///
400/// **Structurally distinct from [`AssertDetail`]**: PassDetail
401/// carries a uniform per-claim shape (every comparator emits
402/// `name + comparator + value + expected`), while AssertDetail
403/// uses a `kind: DetailKind` category enum because failure /
404/// note / warning shapes diverge. Forcing them to one mold would
405/// either lose comparator-typed slots (collapse to kind+message)
406/// or invent a Pass variant of DetailKind that doesn't carry the
407/// typed slots cleanly. Keeping them separate is a deliberate
408/// design choice, not an inconsistency.
409///
410/// Distinct from a one-line tracing log — the structured form is
411/// the data path the auto-repro renderer reads to compose the
412/// bracketed phase output that surfaces passing context alongside
413/// failing assertions. The tracing log path remains the
414/// operator-facing surface for `--nocapture` runs.
415#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
416pub struct PassDetail {
417    pub name: String,
418    pub comparator: std::borrow::Cow<'static, str>,
419    pub value: String,
420    pub expected: Option<String>,
421    /// Scenario phase the claim was made under. `None` outside any
422    /// [`PhaseGuard`] scope; `Some(label)` when the active-phase
423    /// thread-local has been installed at the scenario-driver step
424    /// loop entry. The auto-repro renderer groups passes by this
425    /// field to compose the bracketed `==== PHASE N: <label> ====`
426    /// output. [`Cow`](std::borrow::Cow)`<'static, str>` so the common case (the RAII
427    /// guard's static `&'static str` label) pays zero allocation.
428    pub phase: Option<std::borrow::Cow<'static, str>>,
429}
430
431impl PassDetail {
432    /// Construct a binary-comparator pass record (e.g. `eq`, `ge`,
433    /// `in_range`). Both `value` and `expected` are stringified via
434    /// [`std::fmt::Display`] at the call site so the struct is
435    /// `T`-agnostic on the wire. See [`COMPARATOR_VOCABULARY`] for
436    /// the full set of canonical tokens.
437    pub fn binary(
438        name: impl Into<String>,
439        comparator: impl Into<std::borrow::Cow<'static, str>>,
440        value: impl Into<String>,
441        expected: impl Into<String>,
442    ) -> Self {
443        Self {
444            name: name.into(),
445            comparator: comparator.into(),
446            value: value.into(),
447            expected: Some(expected.into()),
448            phase: current_phase_label(),
449        }
450    }
451
452    /// Construct a unary-comparator pass record (e.g. `is_finite`,
453    /// `set_is_empty`). `expected` is left None — the comparator
454    /// name alone carries the meaning. See [`COMPARATOR_VOCABULARY`]
455    /// for the full set of canonical tokens.
456    pub fn unary(
457        name: impl Into<String>,
458        comparator: impl Into<std::borrow::Cow<'static, str>>,
459        value: impl Into<String>,
460    ) -> Self {
461        Self {
462            name: name.into(),
463            comparator: comparator.into(),
464            value: value.into(),
465            expected: None,
466            phase: current_phase_label(),
467        }
468    }
469
470    /// Builder-style setter for [`Self::phase`]. Consumes self,
471    /// stamps the phase label, returns the updated value so
472    /// per-phase test fixtures and the [`PhaseGuard`] RAII helper can chain
473    /// `PassDetail::binary(...).with_phase("step_0")`.
474    /// `&'static str` literals stay `Cow::Borrowed` (zero alloc);
475    /// runtime-built `String` becomes `Cow::Owned`.
476    pub fn with_phase(mut self, phase: impl Into<std::borrow::Cow<'static, str>>) -> Self {
477        self.phase = Some(phase.into());
478        self
479    }
480}
481
482/// Wire-canonical vocabulary of `PassDetail.comparator` tokens.
483///
484/// Every comparator implementation in [`crate::assert::claim`] emits
485/// one of these tokens when it records a passing claim. The vocabulary
486/// is the **stable wire contract** — renderers, sidecar consumers,
487/// and the auto-repro pipeline match against these exact
488/// strings. A token rename in `claim.rs` without a parallel update
489/// here breaks every downstream consumer; the regression test in
490/// `tests/claim_comparator_tokens_canonical.rs` pins this.
491///
492/// One synthetic token is NOT in this vocabulary: the cap-overflow
493/// sentinel record (see [`PASSES_TRUNCATION_SENTINEL_NAME`]) carries
494/// `comparator = "truncated"` to indicate the slot is metadata, not
495/// a real claim. Renderers that filter passes by vocabulary should
496/// also handle the sentinel as a distinct category.
497///
498/// Tokens follow three style rules:
499///
500/// 1. **Operator-canonical**: comparison operators map to short
501///    operator names (`eq`, `ne`, `ge`, `le`, `lt`, `gt`) regardless
502///    of whether the builder method is `eq` or `at_least`. The
503///    vocabulary is independent of method naming.
504/// 2. **Container-prefixed**: comparators bound to a specific
505///    container type prefix their token with the container name
506///    (`set_*`, `sequence_*`) to disambiguate same-named operations
507///    across surfaces. Scalar tokens are unprefixed.
508/// 3. **Snake-case ASCII**: every token is lower-snake-case, no
509///    Unicode, no spaces — survives shell escapes, IDE regex search,
510///    and log-mining pipelines without transformation.
511///
512/// Asymmetries are intentional: `sequence_*` does not carry
513/// `subset_of` / `disjoint_from` because sequences have order and
514/// duplicates that set semantics don't model.
515///
516/// Categorization below groups by SEMANTIC AXIS (comparison /
517/// predicate / cardinality / membership / relation), not by call-
518/// site arity. Every `len_*` cardinality token (`set_len_eq` /
519/// `set_len_le` / `set_len_ge` and the sequence peers) records
520/// via the binary helper so renderer-side handling is uniform:
521/// each pass surfaces both the actual length and the expected
522/// bound. The previous unary-on-eq + binary-on-le/ge asymmetry
523/// was a micro-optimization (eq's `actual == expected` makes the
524/// actual redundant on the pass arm) that traded uniform output
525/// for one elided field. The `*_is_non_empty` and `*_is_empty`
526/// predicates remain unary by design — the comparator token IS
527/// the predicate, and there is no separate expected bound to
528/// surface. `*_is_non_empty` records the observed length
529/// (evidence the container was non-empty); `*_is_empty` records
530/// no value (the predicate token alone carries the meaning —
531/// emptiness is self-evident from the comparator).
532pub const COMPARATOR_VOCABULARY: &[&str] = &[
533    // Scalar comparisons
534    "eq",
535    "ne",
536    "ge",
537    "le",
538    "lt",
539    "gt",
540    "in_range",
541    "near_within",
542    // Scalar predicates
543    "is_finite",
544    // Set predicates (emptiness)
545    "set_is_empty",
546    "set_is_non_empty",
547    // Set cardinality
548    "set_len_eq",
549    "set_len_le",
550    "set_len_ge",
551    // Set membership / relations
552    "set_contains",
553    "subset_of",
554    "disjoint_from",
555    // Sequence predicates (emptiness)
556    "sequence_is_empty",
557    "sequence_is_non_empty",
558    // Sequence cardinality
559    "sequence_len_eq",
560    "sequence_len_le",
561    "sequence_len_ge",
562    // Sequence membership
563    "sequence_contains",
564];
565
566/// Cap on `AssertResult.passes` (and the matching truncation sentinel)
567/// so a pathological test that fires millions of claims doesn't
568/// balloon the wire-formatted result. Mirrors SnapshotBridge's
569/// `MAX_STORED_EVENTS` truncation pattern: when the cap is hit,
570/// the cap-th record is replaced with a synthetic
571/// `PassDetail { name: PASSES_TRUNCATION_SENTINEL_NAME, … }` carrying
572/// the dropped-count, and further pushes are no-ops.
573///
574/// 10_000 is comfortably above the steady-state claim count of every
575/// existing test (typical test fires <100 claims; pathological hot-
576/// loop tests in the tree fire under 5_000) while bounding the
577/// worst-case wire size to ~3 MB — well under the 16 MiB
578/// `MAX_BULK_FRAME_PAYLOAD` per vmm/bulk.rs:56.
579pub const MAX_RECORDED_PASSES: usize = 10_000;
580
581/// Sentinel `PassDetail.name` value used by the truncation record
582/// that replaces the `MAX_RECORDED_PASSES`-th slot when a test
583/// over-runs the cap. Consumers (the auto-repro renderer) match on
584/// this string to render `[N passes truncated]` instead of treating
585/// it as a real claim.
586///
587/// **Truncation-check idiom**: a caller checking
588/// `result.passes.len() == MAX_RECORDED_PASSES` MISSES the truncated
589/// state because the truncation sentinel pushes the vec to
590/// `MAX_RECORDED_PASSES + 1`. The correct check is
591/// `result.passes.last().map(|p| p.name == PASSES_TRUNCATION_SENTINEL_NAME)
592/// .unwrap_or(false)` — i.e. inspect the tail entry's name.
593pub const PASSES_TRUNCATION_SENTINEL_NAME: &str = "__ktstr_passes_truncated__";
594
595/// Comparator-string value used by the truncation sentinel record
596/// alone. Out-of-vocabulary by design — not in [`COMPARATOR_VOCABULARY`]
597/// — so the runtime debug_assert in `record_pass_inner` allows it
598/// explicitly without polluting the wire-canonical token set.
599pub const PASSES_TRUNCATION_SENTINEL_COMPARATOR: &str = "truncated";
600
601/// `Display` adapter returned by [`AssertDetail::display_with_kind`].
602/// Renders the detail as `[<kind>] <message>`. Held by reference so
603/// the helper allocates nothing on the formatting path; the lifetime
604/// is the borrow of the source `AssertDetail`.
605#[must_use = "AssertDetailWithKind only renders when formatted"]
606pub struct AssertDetailWithKind<'a> {
607    detail: &'a AssertDetail,
608}
609
610impl std::fmt::Display for AssertDetailWithKind<'_> {
611    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
612        write!(f, "[{:?}] {}", self.detail.kind, self.detail.message)
613    }
614}
615
616impl From<String> for AssertDetail {
617    /// Conversion for uncategorized messages; defaults `kind` to
618    /// [`DetailKind::Other`]. Prefer [`AssertDetail::new`] when the
619    /// detail has a meaningful category — the `DetailKind` is serialized
620    /// into the sidecar JSON and consumed by stats tooling to bucket
621    /// failures, so losing the category bucket makes post-run
622    /// categorization rely on free-text regex against `message`.
623    fn from(message: String) -> Self {
624        Self::new(DetailKind::Other, message)
625    }
626}
627
628/// Informational annotation that does NOT contribute to the failure
629/// verdict — the structural counterpart to [`AssertDetail`] for
630/// "context surfaced alongside a result" emissions. Lives in its own
631/// type (not as a `DetailKind` variant of `AssertDetail`) so the
632/// "details = failures" mental model holds at the type level:
633/// `AssertResult::details` is the failure stream, `AssertResult::info_notes`
634/// is the context stream. Producers can no longer accidentally tag a
635/// note as a failure (the prior `DetailKind::Note` variant on
636/// `AssertDetail` made misclassification a one-character bug — every
637/// sidecar consumer that read `details` needed to remember to filter
638/// `kind == Note` to count real failures, and forgetting silently
639/// misreported failure counts).
640///
641/// Carries the same `phase` field as [`AssertDetail`] so the auto-repro
642/// renderer can attribute notes to the scenario phase they were emitted
643/// under, mirroring the per-step grouping already used for failures
644/// and passes.
645///
646/// `PartialEq + Eq` mirror the derive set on [`AssertDetail`] and
647/// [`PassDetail`] so test authors can compose `AssertResult` fixtures
648/// across the three record types with uniform structural-equality
649/// affordances. Test authors should still prefer
650/// `result.info_notes.iter().any(|n| n.message.contains(...))` over
651/// `assert_eq!(result.info_notes, expected)` so pins survive note
652/// wording adjustments without churn.
653#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
654pub struct InfoNote {
655    pub message: String,
656    /// Scenario phase the note was emitted under. Mirrors
657    /// [`AssertDetail::phase`] and [`PassDetail::phase`] so the
658    /// renderer threads pass / fail / note records through one
659    /// per-phase grouping.
660    pub phase: Option<std::borrow::Cow<'static, str>>,
661}
662
663impl InfoNote {
664    pub fn new(message: impl Into<String>) -> Self {
665        Self {
666            message: message.into(),
667            phase: current_phase_label(),
668        }
669    }
670
671    /// Builder-style setter for [`Self::phase`]. Matches the
672    /// [`AssertDetail::with_phase`] shape so producers can chain
673    /// `InfoNote::new(...).with_phase(...)` uniformly with the
674    /// failure-detail builder.
675    #[must_use = "builder methods consume self; bind the result"]
676    pub fn with_phase(mut self, phase: impl Into<std::borrow::Cow<'static, str>>) -> Self {
677        self.phase = Some(phase.into());
678        self
679    }
680}
681
682impl std::fmt::Display for InfoNote {
683    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
684        f.write_str(&self.message)
685    }
686}
687
688impl From<&str> for AssertDetail {
689    /// Conversion for uncategorized messages; defaults `kind` to
690    /// [`DetailKind::Other`]. Prefer [`AssertDetail::new`] when the
691    /// detail has a meaningful category — the `DetailKind` is serialized
692    /// into the sidecar JSON and consumed by stats tooling to bucket
693    /// failures, so losing the category bucket makes post-run
694    /// categorization rely on free-text regex against `message`.
695    fn from(s: &str) -> Self {
696        Self::new(DetailKind::Other, s)
697    }
698}
699
700impl std::fmt::Display for AssertDetail {
701    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
702        f.write_str(&self.message)
703    }
704}
705
706/// Result of checking a scenario run.
707///
708/// Contains pass/fail status, human-readable detail messages, and
709/// aggregated statistics. Multiple results can be combined with
710/// [`merge()`](AssertResult::merge).
711///
712/// ```
713/// # use ktstr::assert::{AssertDetail, AssertResult, DetailKind};
714/// let mut a = AssertResult::pass();
715/// assert!(a.is_pass());
716///
717/// let mut b = AssertResult::pass();
718/// b.record_fail(AssertDetail::new(DetailKind::NoProgress, "worker made no progress"));
719///
720/// a.merge(b);
721/// assert!(a.is_fail());
722/// assert!(a.failure_details().any(|d| d.kind == DetailKind::NoProgress));
723/// ```
724/// Structured measurement value attached via
725/// [`AssertResult::note_value`] / [`Verdict::note_value`].
726///
727/// The variants cover every primitive shape stats tooling consumes:
728/// signed and unsigned 64-bit ints, 64-bit floats, booleans, and
729/// owned strings. A test that wants to surface "max_wchar=12345"
730/// alongside a passing IO_ACCOUNTING reachability check writes
731/// `verdict.note_value("max_wchar", 12345i64)` and downstream stats
732/// tooling reads `result.measurements["max_wchar"]` as
733/// `NoteValue::Int(12345)`.
734///
735/// Distinct from [`AssertResult::info_notes`]'s free-form
736/// [`InfoNote`] messages: an `InfoNote` carries a single human-
737/// readable string (formatted via its `Display` impl), the
738/// structured map carries typed `(key, NoteValue)` pairs for
739/// programmatic consumption (sidecar parsers, `perf-delta`,
740/// regression dashboards). Producers can call BOTH `note(msg)`
741/// and `note_value(key, val)` on the same result — they occupy
742/// independent buffers (`info_notes` vs `measurements`).
743///
744/// Conversion via the `From` impls below: any
745/// `i64`/`u64`/`f64`/`bool`/`String`/`&str` literal flows into
746/// `note_value` without explicit variant naming. Integer types
747/// narrower than 64-bit (`i32`, `u32`, etc.) need an explicit cast
748/// at the call site rather than a blanket impl, so the call site
749/// reads honestly about the value's resolution.
750///
751/// Derives `PartialEq` but NOT `Eq`: the `Float(f64)` variant holds
752/// IEEE-754 doubles where `NaN != NaN`, which violates the
753/// reflexivity requirement on `Eq`. Equality on `NoteValue` is
754/// partial-equivalence semantics for the same reason `f64` is.
755///
756/// Uses serde's externally-tagged default (no `#[serde(untagged)]`).
757/// Like [`Outcome`], NoteValue is wire-encoded as part of
758/// [`AssertResult::measurements`] via postcard's TLV transport from
759/// guest to host. Postcard is not a self-describing format and cannot
760/// decode `#[serde(untagged)]` enums (returns `WontImplement`) — pre-fix
761/// the decode silently failed when any test populated measurements
762/// before its result crossed the wire. The externally-tagged default
763/// (JSON form `{"Int": 42}` / `{"Text": "x"}`) is what postcard's
764/// externally-tagged enum decoder expects. The
765/// `assert_result_postcard_roundtrip` test pins this contract so a
766/// regression that re-adds `#[serde(untagged)]` trips at test time
767/// rather than as a silent data drop at runtime.
768#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
769pub enum NoteValue {
770    /// 64-bit signed integer — pid_t, exit codes, signed counters.
771    Int(i64),
772    /// 64-bit unsigned integer — work_units, byte counts, durations.
773    Uint(u64),
774    /// 64-bit float — ratios, rates, percentiles in microseconds.
775    Float(f64),
776    /// Boolean — completion flags, feature-detect results.
777    Bool(bool),
778    /// Owned string — categorical labels, environment tokens.
779    Text(String),
780}
781
782impl From<i64> for NoteValue {
783    fn from(v: i64) -> Self {
784        Self::Int(v)
785    }
786}
787impl From<u64> for NoteValue {
788    fn from(v: u64) -> Self {
789        Self::Uint(v)
790    }
791}
792impl From<f64> for NoteValue {
793    fn from(v: f64) -> Self {
794        Self::Float(v)
795    }
796}
797impl From<bool> for NoteValue {
798    fn from(v: bool) -> Self {
799        Self::Bool(v)
800    }
801}
802impl From<String> for NoteValue {
803    fn from(v: String) -> Self {
804        Self::Text(v)
805    }
806}
807impl From<&str> for NoteValue {
808    fn from(v: &str) -> Self {
809        Self::Text(v.to_string())
810    }
811}
812
813/// Terminal verdict for a single test scenario or merge fold —
814/// strict four-state enum that replaces the `(passed, skipped)`
815/// bool-pair encoding on [`AssertResult`].
816///
817/// Precedence under [`AssertResult::merge`]:
818/// **`Fail > Inconclusive > Pass > Skip`**.
819/// A merge that contains any `Fail` resolves to `Fail`; absent a
820/// `Fail`, any `Inconclusive` resolves to `Inconclusive`; absent
821/// both, a `Pass + Skip` mix resolves to `Pass` (Pass dominates
822/// Skip — a check that actually ran and passed overrides a
823/// sibling check whose precondition was unmet, so the merge does
824/// not falsely demote to Skip on the strength of an unrelated
825/// missing-precondition sibling). Skip-only merges stay Skip.
826/// Pass-only merges stay Pass. Inconclusive sits between Fail
827/// and Pass because "couldn't evaluate" is not a real Pass (an
828/// Inconclusive run must not satisfy `is_pass()`-keyed CI gates)
829/// but also not a hard Fail (no claim was made that the system
830/// did the wrong thing).
831///
832/// `Inconclusive` exists for ratio assertions whose denominator
833/// is an INSTRUMENT-derived measurement (iteration count, sample
834/// count, wall-clock interval) that legitimately reached zero —
835/// the gate has no signal to evaluate against. Distinguish from
836/// `Fail`: a POLICY-derived denominator (e.g. NUMA pages under
837/// `MemPolicy::Bind`, where the policy specifies pages will
838/// exist) staying at zero IS a defect signal and stays as `Fail`
839/// per the existing semantic — see `assert_page_locality` /
840/// `AssertPlan::assert_cgroup` for the policy-derived carve-out.
841///
842/// Note: Notes do NOT belong here. [`AssertResult::info_notes`]
843/// is the structurally-separate context stream; re-encoding Note
844/// as an `Outcome` variant would re-mix the failure / verdict
845/// surface with the context surface and erase the separation.
846/// Outcome is strictly terminal verdict; notes are non-verdict
847/// context.
848///
849/// `Skip`, `Inconclusive`, and `Fail` carry an [`AssertDetail`]
850/// payload so the match arm has the diagnostic in hand without
851/// re-walking `details`. `Pass` carries no payload — there is no
852/// failure to describe.
853///
854/// Outcomes are stored as [`AssertResult::outcomes`] and the
855/// [`AssertResult::outcome`] accessor folds the vec via this enum's
856/// [`Self::merge`] (identity = `Outcome::Pass`). Callers query via
857/// [`AssertResult::is_pass`] / [`AssertResult::is_fail`] /
858/// [`AssertResult::is_skip`] / [`AssertResult::is_inconclusive`]
859/// (bool checks), [`AssertResult::record_fail`] /
860/// [`AssertResult::record_skip`] / [`AssertResult::record_pass`] /
861/// [`AssertResult::record_inconclusive`] (atomic mutators), or
862/// [`AssertResult::failure_details`] / [`AssertResult::skip_details`] /
863/// [`AssertResult::inconclusive_details`] (per-variant payload
864/// iterators).
865///
866/// **Skip is not Pass**: `is_pass()` returns `false` on skip — a
867/// skipped scenario is "couldn't run", not "passed". Stats tooling
868/// and gate callers that want to count "not a failure" must test
869/// `r.is_pass() || r.is_skip()` rather than bare `r.is_pass()`.
870/// **Inconclusive is not Pass either**: `is_pass()` returns `false`
871/// when any Inconclusive is recorded, so a zero-denominator ratio
872/// gate cannot silently satisfy an `is_pass()`-keyed CI check.
873/// Uses serde's externally-tagged default (no `#[serde(tag,
874/// content)]`). Most ktstr enums adopt the adjacently-tagged
875/// `#[serde(tag = "kind", content = "data")]` style for JSON
876/// readability, but `Outcome` is uniquely wire-encoded via
877/// postcard as part of [`AssertResult`]'s TLV transport from
878/// guest to host (see
879/// `crate::test_support::output::parse_assert_result_from_drain`
880/// and `crate::test_support::test_helpers::assert_result_tlv_entry`).
881/// Postcard is not a self-describing format and cannot decode
882/// adjacently-tagged enums — pre-fix the decode silently failed and
883/// surfaced as `ERR_NO_TEST_FUNCTION_OUTPUT`. The externally-tagged
884/// default is what postcard's externally-tagged enum decoder
885/// expects. `tests_assert.rs::outcome_serde_externally_tagged_*`
886/// pins both the JSON shape and the postcard roundtrip so a
887/// refactor that re-adds adjacent tagging trips loudly at test
888/// time rather than at runtime.
889///
890/// # Wire-format stability (postcard variant index)
891///
892/// Postcard encodes externally-tagged enums by **variant index**,
893/// not variant name — the integer position in the `enum` body
894/// becomes part of the wire format. The current encoding is:
895/// `Pass=0`, `Skip=1`, `Inconclusive=2`, `Fail=3`.
896///
897/// **Append-only:** new variants MUST be added at the END of the
898/// variant list. Re-ordering, removing, or inserting a variant
899/// shifts the index of every variant after it and silently
900/// reinterprets in-flight bytes from guest payloads as a
901/// different variant on the host — the failure mode is a `Pass`
902/// reading as `Skip` (or vice versa) with no decode error.
903///
904/// Any change to the variant order or list MUST be accompanied
905/// by an update to `tests_assert.rs::outcome_serde_externally_tagged_*`
906/// (which pins the JSON shape and the postcard roundtrip) and
907/// `tests_assert.rs::outcome_postcard_variant_index_byte_sentinel`
908/// (which pins the leading variant-index byte) so a silent-shift
909/// regression trips at test time.
910#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
911pub enum Outcome {
912    // Wire-format-stable: variant indices encode into postcard
913    // bytes (Pass=0, Skip=1, Inconclusive=2, Fail=3). Append new
914    // variants ONLY at the end of this list — see the enum doc's
915    // "Wire-format stability" section for the silent-shift hazard
916    // a reorder introduces.
917    Pass,
918    Skip(AssertDetail),
919    Inconclusive(AssertDetail),
920    Fail(AssertDetail),
921}
922
923impl Outcome {
924    /// True iff `self == Outcome::Pass`.
925    ///
926    /// Part of the `is_pass` / `is_fail` / `is_inconclusive` /
927    /// `is_skip` vocabulary uniform across the verdict surfaces:
928    /// [`crate::assert::AssertResult::is_pass`] /
929    /// [`crate::test_support::SidecarResult::is_pass`] /
930    /// [`Self::is_pass`] / `MonitorVerdict::is_pass` (in the
931    /// `monitor` module, which is `pub(crate)`) / `Verdict::is_pass`
932    /// (re-exported at [`crate::assert::Verdict`]) /
933    /// `GauntletRow::is_pass` (in the `stats` module, which is
934    /// `pub(crate)`). [`OutcomeRef::is_pass`] is a borrowed-view
935    /// twin of this method on the borrowed [`OutcomeRef`] enum and
936    /// is intentionally NOT counted as a peer surface — it shares
937    /// the boolean semantic for naming parity but is a `&self`
938    /// projection over [`Outcome`], not an independent verdict
939    /// shape.
940    pub fn is_pass(&self) -> bool {
941        matches!(self, Outcome::Pass)
942    }
943
944    /// True iff `self == Outcome::Skip(_)`.
945    pub fn is_skip(&self) -> bool {
946        matches!(self, Outcome::Skip(_))
947    }
948
949    /// True iff `self == Outcome::Fail(_)`.
950    pub fn is_fail(&self) -> bool {
951        matches!(self, Outcome::Fail(_))
952    }
953
954    /// True iff `self == Outcome::Inconclusive(_)`.
955    pub fn is_inconclusive(&self) -> bool {
956        matches!(self, Outcome::Inconclusive(_))
957    }
958
959    /// Merge two outcomes per the precedence
960    /// `Fail > Inconclusive > Pass > Skip`.
961    ///
962    /// Discriminant-commutative: the merged Pass/Skip/Inconclusive/Fail
963    /// kind is the same regardless of operand order. Idempotent on
964    /// Pass (`Pass.merge(Pass) == Pass`).
965    ///
966    /// Payload semantic (NOT commutative):
967    /// - Same-variant ties (Fail+Fail, Inconclusive+Inconclusive,
968    ///   Skip+Skip): the LEFT operand's payload wins, so caller-
969    ///   controlled merge ordering produces deterministic detail
970    ///   content.
971    /// - Cross-variant Fail+{Inconclusive,Skip}: the merged outcome is
972    ///   Fail and the payload comes from whichever side carries the
973    ///   Fail (the dominated side's payload is dropped — the merged
974    ///   verdict is Fail, so the dominated narrative is irrelevant to
975    ///   the failure record).
976    /// - Cross-variant Inconclusive+{Pass,Skip}: merged outcome is
977    ///   Inconclusive and the payload comes from whichever side
978    ///   carries the Inconclusive.
979    pub fn merge(self, other: Outcome) -> Outcome {
980        use Outcome::*;
981        match (self, other) {
982            (Fail(d), _) | (_, Fail(d)) => Fail(d),
983            (Inconclusive(d), _) | (_, Inconclusive(d)) => Inconclusive(d),
984            (Pass, _) | (_, Pass) => Pass,
985            (Skip(d), Skip(_)) => Skip(d),
986        }
987    }
988
989    /// Borrow this outcome's payload as an [`OutcomeRef`]. Zero-
990    /// allocation projection — `Pass` carries no payload; `Skip`,
991    /// `Inconclusive`, and `Fail` borrow their [`AssertDetail`] in
992    /// place. Used by
993    /// the verdict-read fast path
994    /// ([`AssertResult::outcome_ref`]) and any caller that wants
995    /// to inspect the terminal verdict without cloning the
996    /// detail (e.g. error-message formatting where the detail
997    /// outlives the formatter, or sidecar emission that already
998    /// owns the source `Outcome`).
999    pub fn as_ref(&self) -> OutcomeRef<'_> {
1000        match self {
1001            Outcome::Pass => OutcomeRef::Pass,
1002            Outcome::Skip(d) => OutcomeRef::Skip(d),
1003            Outcome::Inconclusive(d) => OutcomeRef::Inconclusive(d),
1004            Outcome::Fail(d) => OutcomeRef::Fail(d),
1005        }
1006    }
1007}
1008
1009/// Borrowed view of an [`Outcome`]: same four discriminants but
1010/// the `Skip`, `Inconclusive`, and `Fail` payloads borrow their
1011/// [`AssertDetail`] in place. Returned by [`Outcome::as_ref`] and
1012/// the zero-clone verdict-read fast path
1013/// [`AssertResult::outcome_ref`].
1014///
1015/// Use when the caller wants the terminal verdict shape (or its
1016/// payload) WITHOUT taking ownership — typical sites are
1017/// formatter and sidecar paths that already hold the source
1018/// `AssertResult` and want to avoid the per-call
1019/// `AssertDetail::clone` the owned [`Outcome`] accessor performs.
1020#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1021pub enum OutcomeRef<'a> {
1022    Pass,
1023    Skip(&'a AssertDetail),
1024    Inconclusive(&'a AssertDetail),
1025    Fail(&'a AssertDetail),
1026}
1027
1028impl OutcomeRef<'_> {
1029    /// True iff `self == OutcomeRef::Pass`. Matches the boolean
1030    /// shape of [`Outcome::is_pass`] for naming parity.
1031    pub fn is_pass(&self) -> bool {
1032        matches!(self, OutcomeRef::Pass)
1033    }
1034    /// True iff `self == OutcomeRef::Skip(_)`. Matches the
1035    /// boolean shape of [`Outcome::is_skip`].
1036    pub fn is_skip(&self) -> bool {
1037        matches!(self, OutcomeRef::Skip(_))
1038    }
1039    /// True iff `self == OutcomeRef::Fail(_)`. Matches the
1040    /// boolean shape of [`Outcome::is_fail`].
1041    pub fn is_fail(&self) -> bool {
1042        matches!(self, OutcomeRef::Fail(_))
1043    }
1044    /// True iff `self == OutcomeRef::Inconclusive(_)`. Matches the
1045    /// boolean shape of [`Outcome::is_inconclusive`].
1046    pub fn is_inconclusive(&self) -> bool {
1047        matches!(self, OutcomeRef::Inconclusive(_))
1048    }
1049    /// Promote a borrowed [`OutcomeRef`] into an owned [`Outcome`]
1050    /// by cloning the borrowed [`AssertDetail`] (when present).
1051    /// `OutcomeRef::Pass` carries no payload so the conversion is
1052    /// allocation-free. Pairs with [`Outcome::as_ref`] for the
1053    /// borrow ↔ own round-trip; [`AssertResult::outcome`] delegates
1054    /// here so the fold logic stays single-sourced in
1055    /// [`AssertResult::outcome_ref`] and any future fold-rule
1056    /// change (e.g. a new terminal arm) lands in one place.
1057    pub fn to_owned(&self) -> Outcome {
1058        match self {
1059            OutcomeRef::Pass => Outcome::Pass,
1060            OutcomeRef::Skip(d) => Outcome::Skip((*d).clone()),
1061            OutcomeRef::Inconclusive(d) => Outcome::Inconclusive((*d).clone()),
1062            OutcomeRef::Fail(d) => Outcome::Fail((*d).clone()),
1063        }
1064    }
1065}