Skip to main content

reef_core/runtime/agent/
error.rs

1//! Closed errors for Agent construction, admission, and teardown.
2
3use std::error::Error;
4use std::fmt;
5use std::sync::Arc;
6
7use crate::runtime::hook::{self, AttributedError};
8use crate::runtime::model::RequestError;
9use crate::runtime::session::LeaseError;
10use crate::transcript::store;
11use crate::value::lifecycle::CoordError;
12
13/// A panic isolated at one Agent teardown callback boundary.
14#[derive(Clone, Copy, Debug, Eq, PartialEq)]
15pub struct ClosePanickedError;
16
17impl fmt::Display for ClosePanickedError {
18    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
19        formatter.write_str("Agent OnClose callback panicked")
20    }
21}
22
23impl Error for ClosePanickedError {}
24
25/// Configuration validation failure.
26#[derive(Clone, Debug)]
27#[non_exhaustive]
28pub enum ConfigError {
29    /// Hook registry construction failed.
30    Hooks(hook::RegistryError),
31    /// Frozen request defaults were invalid.
32    InvalidDefaults(RequestError),
33    /// The process-wide nonzero revision identity space was exhausted.
34    RevisionIdExhausted,
35}
36
37impl fmt::Display for ConfigError {
38    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
39        match self {
40            Self::Hooks(error) => error.fmt(formatter),
41            Self::InvalidDefaults(error) => error.fmt(formatter),
42            Self::RevisionIdExhausted => formatter.write_str("Agent revision identity exhausted"),
43        }
44    }
45}
46
47impl Error for ConfigError {
48    fn source(&self) -> Option<&(dyn Error + 'static)> {
49        match self {
50            Self::Hooks(error) => Some(error),
51            Self::InvalidDefaults(error) => Some(error),
52            Self::RevisionIdExhausted => None,
53        }
54    }
55}
56
57/// Why [`Agent::start`](super::Agent::start) admitted no Run.
58///
59/// Every variant is pre-admission. A `StartError` means no Run exists, the
60/// Session lease and Agent attachment have been rolled back, and the transcript
61/// is as it was; once admission completes, failure is reported by the returned
62/// Run's [`Terminal`](crate::runtime::run::Terminal) instead. `Agent::start`
63/// documents which condition produces which variant.
64#[derive(Clone, Debug)]
65#[non_exhaustive]
66pub enum StartError {
67    /// Agent close sealed new attachment before any Session access.
68    AgentClosed,
69    /// The target Session already has an active lease.
70    SessionBusy,
71    /// Cancellation won before admission completed.
72    Cancelled,
73    /// The process-wide Run identity space was exhausted.
74    RunIdExhausted,
75    /// Session or Run identity validation failed.
76    InvalidIdentity(CoordError),
77    /// Lease admission or a lease-bound prepare mutation failed.
78    Admission(LeaseError),
79    /// A prepare hook failed.
80    Prepare(AttributedError),
81    /// Transcript mutation failed.
82    Transcript(store::Error),
83}
84
85impl fmt::Display for StartError {
86    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
87        match self {
88            Self::AgentClosed => formatter.write_str("Agent is closed"),
89            Self::SessionBusy => formatter.write_str("Session already has an active Run"),
90            Self::Cancelled => formatter.write_str("Run admission canceled"),
91            Self::RunIdExhausted => formatter.write_str("Run identity exhausted"),
92            Self::InvalidIdentity(error) => error.fmt(formatter),
93            Self::Admission(error) => error.fmt(formatter),
94            Self::Prepare(error) => {
95                write!(formatter, "hook {} prepare failed", error.name())
96            }
97            Self::Transcript(error) => error.fmt(formatter),
98        }
99    }
100}
101
102impl Error for StartError {
103    fn source(&self) -> Option<&(dyn Error + 'static)> {
104        match self {
105            Self::InvalidIdentity(error) => Some(error),
106            Self::Admission(error) => Some(error),
107            // The attributed failure, not the `HookError` inside it: skipping
108            // that link would drop the registration name, which `Display`
109            // reports but nothing below the wrapper carries.
110            Self::Prepare(error) => Some(error),
111            Self::Transcript(error) => Some(error),
112            Self::AgentClosed | Self::SessionBusy | Self::Cancelled | Self::RunIdExhausted => None,
113        }
114    }
115}
116
117/// Ordered immutable Agent teardown failures.
118///
119/// [`Error::source`] returns the first [`AttributedError`]. Remaining failures
120/// stay reachable only through [`entries`](Self::entries).
121#[derive(Clone, Debug)]
122pub struct TeardownError(pub(super) Arc<[AttributedError]>);
123
124impl TeardownError {
125    /// Returns failures in hook registration order.
126    #[must_use]
127    pub fn entries(&self) -> &[AttributedError] {
128        &self.0
129    }
130}
131
132impl fmt::Display for TeardownError {
133    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
134        write!(
135            formatter,
136            "{} Agent OnClose callback(s) failed",
137            self.0.len()
138        )
139    }
140}
141
142impl Error for TeardownError {
143    /// The first teardown failure, in registration order.
144    ///
145    /// A generic `source()` walk therefore sees that first [`AttributedError`]
146    /// and stops. Remaining failures are not on this chain;
147    /// [`entries`](Self::entries) is the ordered list. This is not "the most
148    /// severe" entry — the type does not own a severity order.
149    ///
150    /// [`Agent::close`](super::Agent::close) never constructs an empty aggregate:
151    /// it wraps [`CloseError::Hooks`] only when `failures` is nonempty. `source()`
152    /// is therefore `Some` whenever close produces this type.
153    fn source(&self) -> Option<&(dyn Error + 'static)> {
154        self.0.first().map(|error| error as &(dyn Error + 'static))
155    }
156}
157
158/// Agent close result, separating retryable active-run state from cached hooks.
159#[derive(Clone, Debug)]
160#[non_exhaustive]
161pub enum CloseError {
162    /// One or more Run attachments still own the Agent.
163    #[non_exhaustive]
164    Busy {
165        /// Exact number of attachments at the close linearization point.
166        active_runs: usize,
167    },
168    /// Every teardown ran, and these callbacks failed or panicked.
169    Hooks(TeardownError),
170}
171
172impl fmt::Display for CloseError {
173    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
174        match self {
175            Self::Busy { active_runs } => {
176                write!(formatter, "Agent has {active_runs} active Run(s)")
177            }
178            Self::Hooks(errors) => errors.fmt(formatter),
179        }
180    }
181}
182
183impl Error for CloseError {
184    fn source(&self) -> Option<&(dyn Error + 'static)> {
185        match self {
186            Self::Busy { .. } => None,
187            Self::Hooks(errors) => Some(errors),
188        }
189    }
190}