Skip to main content

dive_model/
control.rs

1//! Typed control transport for the additive controlled binding entry points.
2
3use dive_eval::{EvalError, HostControlConflict};
4
5use crate::{BindError, Failure, Message};
6
7/// A controlled binding failed, preserving startup output and run ownership.
8///
9/// This does not classify a resource or produce a checker verdict. The caller
10/// must match the original interruption against its own active run control.
11#[derive(Clone, Debug, PartialEq, Eq)]
12pub enum ControlledBindError {
13    /// The ordinary binding failure, with unchanged diagnostics and output.
14    Binding(Box<Failure>),
15    /// Evaluator work returned its driver's typed interruption.
16    Interrupted {
17        /// The original error, including its opaque identity and source origin.
18        error: EvalError,
19        /// Output before interruption, in original startup order.
20        output: Vec<Message>,
21    },
22    /// Fallible evaluation or optional source-proof planning failed intrinsically.
23    /// Controlled binding retains the original error. The plain boxed binding
24    /// API has no exception channel and uses its existing fail-closed bug wrapper.
25    EvaluationFailure {
26        /// Original resource-limit or internal evaluator error.
27        error: EvalError,
28        /// Startup output produced before the failure, in original order.
29        output: Vec<Message>,
30    },
31    /// The evaluator could not admit this control registration.
32    ControlConflict {
33        /// The registration error; it is not resource exhaustion.
34        error: HostControlConflict,
35        /// Output before registration failed.
36        output: Vec<Message>,
37    },
38}
39
40impl ControlledBindError {
41    /// Startup output emitted before the failure, in order.
42    #[must_use]
43    pub fn output(&self) -> &[Message] {
44        match self {
45            Self::Binding(failure) => &failure.output,
46            Self::Interrupted { output, .. }
47            | Self::EvaluationFailure { output, .. }
48            | Self::ControlConflict { output, .. } => output,
49        }
50    }
51
52    #[allow(
53        clippy::unnecessary_box_returns,
54        reason = "preserve the uncontrolled public boxed-error contract without reallocating existing failures"
55    )]
56    pub(crate) fn into_uncontrolled(self) -> Box<Failure> {
57        match self {
58            Self::Binding(failure) => failure,
59            // The plain boxed error has no exception channel. Preserve its
60            // fail-closed bug projection rather than minting a semantic refusal.
61            Self::Interrupted { output, .. }
62            | Self::EvaluationFailure { output, .. }
63            | Self::ControlConflict { output, .. } => Box::new(Failure {
64                error: BindError::bug("uncontrolled binding returned a controlled failure"),
65                output,
66            }),
67        }
68    }
69}
70
71impl std::fmt::Display for ControlledBindError {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        match self {
74            Self::Binding(failure) => failure.fmt(f),
75            Self::Interrupted { error, .. } | Self::EvaluationFailure { error, .. } => error.fmt(f),
76            Self::ControlConflict { error, .. } => error.fmt(f),
77        }
78    }
79}
80impl std::error::Error for ControlledBindError {}
81
82impl From<Box<Failure>> for ControlledBindError {
83    fn from(failure: Box<Failure>) -> Self {
84        Self::Binding(failure)
85    }
86}
87
88#[derive(Debug)]
89pub(crate) enum StepError {
90    Binding(BindError),
91    Interrupted(EvalError),
92    EvaluationFailure(EvalError),
93    ControlConflict(HostControlConflict),
94}
95
96impl StepError {
97    pub(crate) fn with_output(self, output: Vec<Message>) -> ControlledBindError {
98        match self {
99            Self::Binding(error) => {
100                ControlledBindError::Binding(Box::new(Failure { error, output }))
101            }
102            Self::Interrupted(error) => ControlledBindError::Interrupted { error, output },
103            Self::EvaluationFailure(error) => {
104                ControlledBindError::EvaluationFailure { error, output }
105            }
106            Self::ControlConflict(error) => ControlledBindError::ControlConflict { error, output },
107        }
108    }
109
110    pub(crate) fn ordinary(self) -> Result<BindError, Self> {
111        match self {
112            Self::Binding(error) => Ok(error),
113            other => Err(other),
114        }
115    }
116
117    pub(crate) fn is_exception(&self) -> bool {
118        matches!(self, Self::Interrupted(_) | Self::EvaluationFailure(_))
119    }
120}
121
122impl From<BindError> for StepError {
123    fn from(error: BindError) -> Self {
124        Self::Binding(error)
125    }
126}
127impl From<HostControlConflict> for StepError {
128    fn from(error: HostControlConflict) -> Self {
129        Self::ControlConflict(error)
130    }
131}
132
133pub(crate) fn eval_error(
134    controlled: bool,
135    fallible_errors: bool,
136    error: EvalError,
137    to_binding: impl FnOnce(EvalError) -> BindError,
138) -> StepError {
139    if (controlled || fallible_errors) && error.class() == dive_eval::ErrorClass::Interrupted {
140        StepError::Interrupted(error)
141    } else if fallible_errors
142        && matches!(
143            error.class(),
144            dive_eval::ErrorClass::ResourceLimit | dive_eval::ErrorClass::Bug
145        )
146    {
147        StepError::EvaluationFailure(error)
148    } else {
149        StepError::Binding(to_binding(error))
150    }
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156    #[test]
157    fn fallible_intrinsic_errors_retain_original_class_origin_and_output() {
158        for original in [
159            EvalError::resource_limit("actual allocation failure"),
160            EvalError::bug("actual internal failure"),
161        ] {
162            let original = original.at(dive_ir::ExprId(17));
163            let binding = eval_error(false, false, original.clone(), |error| {
164                BindError::unsupported(error.to_string())
165            });
166            assert!(matches!(binding, StepError::Binding(_)));
167            let output = vec![Message::Print("before".into())];
168            let result = eval_error(false, true, original.clone(), |error| {
169                BindError::unsupported(error.to_string())
170            })
171            .with_output(output.clone());
172            assert!(
173                matches!(result,ControlledBindError::EvaluationFailure{error,output:actual} if error==original&&actual==output)
174            );
175        }
176    }
177}