Skip to main content

lellm_graph/error/
mod.rs

1//! Graph 错误类型。
2//!
3//! 错误模型:
4//! - `Terminal` — 终止执行,stream 关闭
5//! - Fallback — 控制流(通过 `StreamNodeResult::Fallback`),非错误
6//! - 可观测性 — 通过 `GraphEvent::ObservedError` 事件发送
7//!
8//! `build()` = 结构正确性校验(纯函数,只产生 BuildError)
9//! `analyze()` = 风险诊断(产生 GraphDiagnostics)
10
11use std::fmt;
12
13mod build_error;
14
15pub use build_error::*;
16
17// ─── GraphError ──────────────────────────────────────────────
18
19/// Graph 运行时错误。
20///
21/// 只有 Terminal 变体 — Fallback 改为控制流(`StreamNodeResult::Fallback`)。
22#[derive(Debug)]
23pub enum GraphError {
24    /// 终止执行 — stream 关闭,不可恢复
25    Terminal(TerminalError),
26}
27
28/// 终止错误 — Graph 执行不可恢复地停止。
29#[derive(Debug)]
30pub enum TerminalError {
31    /// 图结构无效(构建时校验遗漏的运行时问题)
32    InvalidGraph(String),
33    /// 节点不存在
34    NodeNotFound(String),
35    /// Goto 目标缺少对应的边
36    MissingEdge { from: String, to: String },
37    /// 节点执行失败(不可恢复)
38    NodeExecutionFailed {
39        node: String,
40        source: Box<dyn std::error::Error + Send + Sync>,
41    },
42    /// 全局步数超限(运行时熔断)
43    StepsExceeded { limit: usize },
44    /// 循环超限
45    LoopLimitExceeded { limit: usize },
46    /// Barrier 超时
47    BarrierTimeout {
48        node: String,
49        timeout: std::time::Duration,
50    },
51    /// Barrier 被取消
52    BarrierCancelled { node: String },
53    /// 无匹配边 — 没有任何 outgoing edge 满足条件,且无 fallback
54    Unrouted {
55        /// 当前节点
56        node: String,
57        /// 尝试的条件及其结果
58        attempted_conditions: Vec<ConditionEval>,
59    },
60    /// State 操作错误
61    StateError(String),
62    /// 检查点同步保存失败 — 执行在该边界停止
63    CheckpointSaveFailed { error: String },
64    /// 持久化/恢复入口遇到不支持的图结构(Parallel/Subgraph/Barrier)
65    RestoreUnsupported { node: String, kind: String },
66    /// 传入的检查点不是该 trace 的最新检查点 — 拒绝续写原 trace(避免历史分叉)
67    RestoreNotLatest { checkpoint: String, latest: String },
68    /// 检查点格式版本不支持(legacy 格式)
69    RestoreUnsupportedFormat { actual: u32, expected: u32 },
70    /// graph_hash 不匹配(图结构已变更)
71    RestoreGraphMismatch { expected: u64, actual: u64 },
72    /// trace 已有检查点 — 首次执行入口要求 trace 新鲜
73    TraceNotFresh { trace: String, latest: String },
74    /// 检查点加载失败(存储读取错误 — 存储故障语义,非恢复校验失败)
75    CheckpointLoadFailed { error: String },
76    /// 恢复前置条件失败(其他未结构化原因)
77    RestoreFailed { reason: String },
78}
79
80/// 可观测性事件 — 不属于错误体系,通过 GraphEvent 发送。
81#[derive(Debug, Clone)]
82pub enum ObservedError {
83    /// 警告
84    Warning { node: String, message: String },
85    /// 降级执行
86    Degraded { node: String, message: String },
87    /// 部分失败
88    PartialFailure {
89        node: String,
90        succeeded: usize,
91        failed: usize,
92        message: String,
93    },
94}
95
96impl fmt::Display for ObservedError {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        match self {
99            Self::Warning { node, message } => write!(f, "node '{}': {}", node, message),
100            Self::Degraded { node, message } => write!(f, "node '{}' degraded: {}", node, message),
101            Self::PartialFailure {
102                node,
103                succeeded,
104                failed,
105                message,
106            } => {
107                write!(
108                    f,
109                    "node '{}' partial: {}/{} ok, {}",
110                    node,
111                    succeeded,
112                    succeeded + failed,
113                    message
114                )
115            }
116        }
117    }
118}
119
120/// 条件评估结果 — 用于 Unrouted 错误报告。
121#[derive(Debug, Clone)]
122pub struct ConditionEval {
123    /// 边描述
124    pub edge: String,
125    /// 条件描述(None = default edge)
126    pub condition: Option<String>,
127    /// 评估结果
128    pub matched: bool,
129}
130
131// ─── Display ─────────────────────────────────────────────────
132
133impl fmt::Display for GraphError {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        match self {
136            Self::Terminal(e) => write!(f, "[terminal] {}", e),
137        }
138    }
139}
140
141impl fmt::Display for TerminalError {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        match self {
144            Self::InvalidGraph(msg) => write!(f, "invalid graph: {msg}"),
145            Self::NodeNotFound(name) => write!(f, "node not found: {name}"),
146            Self::MissingEdge { from, to } => {
147                write!(
148                    f,
149                    "goto '{}' from '{}' failed: no edge {}→{} exists",
150                    to, from, from, to
151                )
152            }
153            Self::NodeExecutionFailed { node, source } => {
154                write!(f, "node '{node}' execution failed: {source}")
155            }
156            Self::StepsExceeded { limit } => {
157                write!(f, "step limit {limit} exceeded (potential infinite loop)")
158            }
159            Self::LoopLimitExceeded { limit } => write!(f, "loop limit exceeded: {limit}"),
160            Self::BarrierTimeout { node, timeout } => {
161                write!(f, "barrier '{node}' timed out after {timeout:?}")
162            }
163            Self::BarrierCancelled { node } => {
164                write!(
165                    f,
166                    "barrier '{node}' cancelled: consumer dropped the signal channel"
167                )
168            }
169            Self::Unrouted {
170                node,
171                attempted_conditions,
172            } => {
173                write!(f, "node '{}' has no matching outgoing edge", node)?;
174                if !attempted_conditions.is_empty() {
175                    write!(f, ". evaluated: [")?;
176                    for (i, ce) in attempted_conditions.iter().enumerate() {
177                        if i > 0 {
178                            write!(f, ", ")?;
179                        }
180                        write!(f, "{}={}", ce.edge, ce.matched)?;
181                    }
182                    write!(f, "]")?;
183                }
184                Ok(())
185            }
186            Self::StateError(msg) => write!(f, "state error: {msg}"),
187            Self::CheckpointSaveFailed { error } => {
188                write!(f, "checkpoint save failed: {error}")
189            }
190            Self::RestoreUnsupported { node, kind } => write!(
191                f,
192                "persistence/restore does not support {kind} node '{node}' (phase 1: serial + loops only)"
193            ),
194            Self::RestoreNotLatest { checkpoint, latest } => write!(
195                f,
196                "checkpoint {checkpoint} is not the latest of this trace (latest: {latest}); restore requires the latest checkpoint or a new trace"
197            ),
198            Self::RestoreUnsupportedFormat { actual, expected } => write!(
199                f,
200                "unsupported checkpoint format_version: {actual} (expected {expected})"
201            ),
202            Self::RestoreGraphMismatch { expected, actual } => write!(
203                f,
204                "graph hash mismatch: expected {expected:016x}, got {actual:016x}"
205            ),
206            Self::TraceNotFresh { trace, latest } => write!(
207                f,
208                "trace {trace} already has checkpoint {latest} (use restore entry)"
209            ),
210            Self::CheckpointLoadFailed { error } => {
211                write!(f, "checkpoint load failed: {error}")
212            }
213            Self::RestoreFailed { reason } => write!(f, "restore precondition failed: {reason}"),
214        }
215    }
216}
217
218impl std::error::Error for GraphError {
219    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
220        match self {
221            Self::Terminal(TerminalError::NodeExecutionFailed { source, .. }) => {
222                Some(source.as_ref())
223            }
224            Self::Terminal(_) => None,
225        }
226    }
227}
228
229impl std::error::Error for TerminalError {
230    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
231        match self {
232            Self::NodeExecutionFailed { source, .. } => Some(source.as_ref()),
233            _ => None,
234        }
235    }
236}