Elffuss BraidHub

kikocis/utopia public

An empty balance is final, so the queue should stop asking (#201)

A handler can mark a failure terminal; the queue then fails it on the first attempt instead of spending three retries over seven minutes. Only an empty balance qualifies, judged by the same typed error the alert reads. Alerting fires on a terminal failure too, so failing faster does not mean telling nobody.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Changeseta69149677e22372e66177f785e60678b47a9149a2772f3a43d5f3f4926fc7c7d
AuthorWaylandYang <145302500+WaylandYang@users.noreply.github.com> · 2026-09-03 03:38 +08:00
CommitterGitHub <noreply@github.com> · 2026-09-03 03:38 +08:00
Parentsb89a499ca65b

Browse the files at this changeset

5 files changed

modified crates/utopia-core/src/error.rs +30 −0
@@ -50,3 +50,33 @@
5050 }
5151
5252 pub type AppResult<T> = Result<T, AppError>;
53+
54+/// 标在一个**不会因为重试而变好**的失败上(见 issue #195)。
55+///
56+/// 队列的默认假设是「再等一会儿也许就好了」,多数失败确实如此:端点抖一下、
57+/// 数据库忙一瞬、限流一分钟就过去。余额耗尽不是——三次重试隔着 30 秒、2 分钟、
58+/// 4 分半,七分钟里没有人会去充值,重试只是把同一句错误重说三遍,而运维需要
59+/// 看见的那条「失败」被推迟了七分钟才出现。
60+///
61+/// **判据留在处理器那一侧,不在队列里。** 什么算没救跟领域有关——
62+/// `utopia-store` 看不见 `utopia-llm` 的错误类型,也不该看见。处理器把这个标记
63+/// 挂上去(`err.context(Terminal)`),队列只问「挂了没有」。
64+///
65+/// 挂上它不影响别的:告警照报(`observe_job_failure` 一并认这个标记,
66+/// 否则失败得更快反而没人被告知),`last_error` 照写。
67+#[derive(Debug, Clone, Copy)]
68+pub struct Terminal;
69+
70+impl std::fmt::Display for Terminal {
71+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72+ f.write_str("will not recover by retrying")
73+ }
74+}
75+
76+impl std::error::Error for Terminal {}
77+
78+/// 这次失败被标成不必重试了吗。**沿整条 context 链找**——处理器挂上标记之后,
79+/// 上层还会继续 `context(...)`,只看最外层就等于没看
80+pub fn is_terminal(err: &anyhow::Error) -> bool {
81+ err.chain().any(|e| e.is::<Terminal>())
82+}
modified crates/utopia-core/src/lib.rs +1 −1
@@ -4,4 +4,4 @@
44 pub mod error;
55 pub mod models;
66
7-pub use error::{AppError, AppResult};
7+pub use error::{is_terminal, AppError, AppResult, Terminal};
modified crates/utopia-server/src/alerting.rs +47 −4
@@ -15,9 +15,10 @@
1515
1616 /// 任务失败时看一眼是不是模型端点不可用。
1717 ///
18-/// **只在任务最终放弃时报**(`attempts >= max_attempts`)。中间那几次重试报了
19-/// 就是同一件事发三遍——重试本来就是为了不惊动人,报出去等于把它的意义抵消掉。
20-/// 一个任务至多一条告警,不需要任何去重状态。
18+/// **只在任务最终放弃时报**——次数用完,或者这次失败被标成了不必重试
19+/// ([`hopeless`],#195)。中间那几次重试报了就是同一件事发三遍:重试本来就是
20+/// 为了不惊动人,报出去等于把它的意义抵消掉。一个任务至多一条告警,
21+/// 不需要任何去重状态。
2122 ///
2223 /// 判据是错误的**类型**,不匹配错误文本——调用链上任何一层加一句 context
2324 /// 都会改文本。分类本身抽在 [`alert_for`]。
@@ -26,7 +27,9 @@
2627 job: &utopia_store::jobs::Job,
2728 err: &anyhow::Error,
2829 ) {
29- if job.attempts < job.max_attempts {
30+ // 标成不必重试的那些**这一次就是最后一次**,所以现在就报(#195)。
31+ // 漏掉这一句的后果是失败得更快、却反而没人被告知——比不改还糟
32+ if job.attempts < job.max_attempts && !utopia_core::is_terminal(err) {
3033 return;
3134 }
3235 let Some((kind, severity)) = alert_for(err) else {
@@ -53,6 +56,17 @@
5356 state.emit_alert();
5457 }
5558
59+/// 这次失败还值不值得重试。
60+///
61+/// **只有欠费是没救的。** 限流会自己恢复,端点不可达可能是重启中的服务,
62+/// 别的错误更没有理由一次定生死——只有余额不会在七分钟里自己长回来(#195)。
63+///
64+/// 判据与 [`alert_for`] 同源(`utopia_llm::out_of_credit`,类型不是文本),
65+/// 于是「报成 error 那一类」与「不再重试那一类」永远是同一类,不会分叉。
66+pub fn hopeless(err: &anyhow::Error) -> bool {
67+ utopia_llm::out_of_credit(err).is_some()
68+}
69+
5670 /// 一次任务失败该报哪一类告警,报不报。
5771 ///
5872 /// **抽成纯函数是为了能测**:`observe_job_failure` 要 `AppState` 和一个真数据库,
@@ -212,4 +226,33 @@
212226 let err = anyhow::anyhow!("LLM request failed (401 Unauthorized): bad key");
213227 assert_eq!(alert_for(&err), None);
214228 }
229+
230+ /// **余额不会在七分钟里自己长回来**,所以那三次退避重试只是把同一句错误
231+ /// 重说三遍,还把该看见的失败推迟了七分钟(#195)。
232+ #[test]
233+ fn an_empty_balance_is_not_worth_retrying() {
234+ let err = anyhow::Error::new(OutOfCredit {
235+ status: 402,
236+ detail: "insufficient balance".into(),
237+ })
238+ .context("抽取失败");
239+ assert!(super::hopeless(&err));
240+ }
241+
242+ /// 而限流正是这套退避的服务对象——两类分开(#176)的意义就在这里。
243+ #[test]
244+ fn a_rate_limit_still_gets_its_retries() {
245+ let err = anyhow::Error::new(RateLimited {
246+ status: 429,
247+ retry_after: Some(std::time::Duration::from_secs(30)),
248+ detail: "TPM limit reached".into(),
249+ });
250+ assert!(!super::hopeless(&err));
251+ }
252+
253+ /// 反面:普通失败照常重试。一次网络抖动不该一次定生死。
254+ #[test]
255+ fn an_ordinary_failure_still_gets_its_retries() {
256+ assert!(!super::hopeless(&anyhow::anyhow!("结果解析失败")));
257+ }
215258 }
modified crates/utopia-server/src/main.rs +9 −1
@@ -131,7 +131,15 @@
131131 async move {
132132 // 任务失败时看一眼是不是模型端点连不上——那是系统级故障,
133133 // 而现在它只会留在 jobs.last_error 里,没有任何界面看得到
134- let result = dispatch(&st, &job).await;
134+ //
135+ // 没救的失败在这里挂上标记,队列据此不再退避重试(#195):
136+ // 判据在这一侧,因为 `utopia-store` 看不见 LLM 的错误类型
137+ let result = dispatch(&st, &job)
138+ .await
139+ .map_err(|e| match alerting::hopeless(&e) {
140+ true => e.context(utopia_core::Terminal),
141+ false => e,
142+ });
135143 if let Err(e) = &result {
136144 alerting::observe_job_failure(&st, &job, e).await;
137145 }
modified crates/utopia-store/src/jobs.rs +62 −19
@@ -1,5 +1,6 @@
11 //! 任务队列:Postgres `FOR UPDATE SKIP LOCKED` 消费。
2-//! worker 与 API 同进程(tokio task),失败按 30s * attempts² 退避重试。
2+//! worker 与 API 同进程(tokio task),失败按 30s * attempts² 退避重试——
3+//! 除非处理器把它标成了 `utopia_core::Terminal`,那种一次就到此为止(见 [`retry_delay`])。
34 //! 并发消费:调度循环按"运行中 < 目标数"续派,任务在独立 task 执行;
45 //! 目标数经 AtomicUsize 热读——系统设置里改并发即时生效,无需重启。
56
@@ -61,29 +62,51 @@
6162 Ok(())
6263 }
6364
64-async fn mark_failed(pool: &PgPool, job: &Job, err: &str) -> AppResult<()> {
65- if job.attempts >= job.max_attempts {
65+/// 下一次重试等多久;`None` = 到此为止。
66+///
67+/// 两个理由到此为止:**次数用完了**,或者**处理器说了这次不会因为重试而变好**
68+/// (`utopia_core::Terminal`,见 issue #195)。后者以前不存在,于是余额耗尽的
69+/// 任务照样把三次退避走完——七分钟里余额不会自己长回来,那三次只是把同一句
70+/// 错误重说三遍,还把运维该看见的「失败」推迟了七分钟。
71+///
72+/// 限流相反,它正是这套退避的服务对象:配额会自己恢复。#176 把两类分开就是
73+/// 为了让它们各走各的路,而重试策略当时没跟上。
74+///
75+/// 抽成纯函数是为了能测——决定在这里,写库只是把决定落下去。
76+fn retry_delay(attempts: i32, max_attempts: i32, terminal: bool) -> Option<i64> {
77+ if terminal || attempts >= max_attempts {
78+ return None;
79+ }
80+ Some(30i64 * i64::from(attempts) * i64::from(attempts))
81+}
82+
83+async fn mark_failed(pool: &PgPool, job: &Job, err: &anyhow::Error) -> AppResult<()> {
84+ let text = format!("{err:#}");
85+ let Some(backoff_secs) = retry_delay(
86+ job.attempts,
87+ job.max_attempts,
88+ utopia_core::is_terminal(err),
89+ ) else {
6690 sqlx::query(
6791 "UPDATE jobs SET status = 'failed', last_error = $2, updated_at = now() WHERE id = $1",
6892 )
6993 .bind(job.id)
70- .bind(err)
71- .execute(pool)
72- .await?;
73- } else {
74- let backoff_secs = 30i64 * i64::from(job.attempts) * i64::from(job.attempts);
75- sqlx::query(
76- "UPDATE jobs SET status = 'queued', last_error = $2,
77- run_at = now() + make_interval(secs => $3::float8),
78- updated_at = now()
79- WHERE id = $1",
80- )
81- .bind(job.id)
82- .bind(err)
83- .bind(backoff_secs as f64)
94+ .bind(&text)
8495 .execute(pool)
8596 .await?;
86- }
97+ return Ok(());
98+ };
99+ sqlx::query(
100+ "UPDATE jobs SET status = 'queued', last_error = $2,
101+ run_at = now() + make_interval(secs => $3::float8),
102+ updated_at = now()
103+ WHERE id = $1",
104+ )
105+ .bind(job.id)
106+ .bind(&text)
107+ .bind(backoff_secs as f64)
108+ .execute(pool)
109+ .await?;
87110 Ok(())
88111 }
89112
@@ -137,7 +160,7 @@
137160 Ok(()) => mark_done(&pool, job.id).await,
138161 Err(e) => {
139162 tracing::warn!(job_id = job.id, kind = %job.kind, error = %e, "任务执行失败");
140- mark_failed(&pool, &job, &e.to_string()).await
163+ mark_failed(&pool, &job, &e).await
141164 }
142165 };
143166 if let Err(e) = outcome {
@@ -154,3 +177,23 @@
154177 }
155178 }
156179 }
180+
181+#[cfg(test)]
182+mod tests {
183+ use super::retry_delay;
184+
185+ /// 退避照旧:30s、120s、270s,第三次之后放弃。
186+ #[test]
187+ fn an_ordinary_failure_backs_off_and_then_gives_up() {
188+ assert_eq!(retry_delay(1, 3, false), Some(30));
189+ assert_eq!(retry_delay(2, 3, false), Some(120));
190+ assert_eq!(retry_delay(3, 3, false), None);
191+ }
192+
193+ /// 标成没救的**第一次就到此为止**——那三次退避加起来是七分钟,
194+ /// 而余额不会在七分钟里自己长回来(#195)。
195+ #[test]
196+ fn a_terminal_failure_does_not_spend_the_budget() {
197+ assert_eq!(retry_delay(1, 3, true), None);
198+ }
199+}