Elffuss BraidHub

kikocis/utopia public

An empty balance is not a rate limit (#182)

* Being turned away by a quota is worth telling someone about

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* An empty balance is not a rate limit

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Changeset98165df18f1030b7c3328f1157eb815eba0c9f770d1bd6a098a0b1d00399c2a7
AuthorWaylandYang <145302500+WaylandYang@users.noreply.github.com> · 2026-09-02 17:53 +08:00
CommitterGitHub <noreply@github.com> · 2026-09-02 17:53 +08:00
Parents0dc0623dcff5

Browse the files at this changeset

5 files changed

modified crates/utopia-llm/src/lib.rs +81 −2
@@ -103,6 +103,26 @@
103103 err.chain().find_map(|e| e.downcast_ref::<RateLimited>())
104104 }
105105
106+/// 账号付不起这次请求:欠费,或者套餐配额用尽。
107+///
108+/// **跟 [`RateLimited`] 分开,因为它不会自己好。** 限流等一分钟就过去,
109+/// 欠费等到天亮也还是欠费——重试只是在把同一个错误说三遍,而真正该发生的事
110+/// (有人去充值)不会因为重试而发生。
111+///
112+/// 实测:一次跑测里 14 篇文档因为它整篇失败,而当时它跟普通失败走同一条路,
113+/// 唯一能知道原因的办法是去数据库里翻 `graph_error`。
114+#[derive(Debug, thiserror::Error)]
115+#[error("LLM account cannot pay for this request ({status}): {detail}")]
116+pub struct OutOfCredit {
117+ pub status: u16,
118+ pub detail: String,
119+}
120+
121+/// anyhow 错误链里的 [`OutOfCredit`],穿透 context 层。
122+pub fn out_of_credit(err: &anyhow::Error) -> Option<&OutOfCredit> {
123+ err.chain().find_map(|e| e.downcast_ref::<OutOfCredit>())
124+}
125+
106126 /// `Retry-After` 的整数秒形态。
107127 ///
108128 /// 规范还允许 HTTP-date,这里**不解析**:为一个很少有人发的头引一个日期库不划算,
@@ -118,8 +138,10 @@
118138 .map(Duration::from_secs)
119139 }
120140
121-/// 非 2xx 统一在这里成型。**只有 429 算限流**:503 可能是端点真挂了、
122-/// 也可能是中间代理,把它算进来会让「等一会儿再来」用在等不回来的地方。
141+/// 非 2xx 统一在这里成型,分成三类:欠费、限流、其他。
142+///
143+/// **503 不算限流**:它可能是端点真挂了、也可能是中间代理,把它算进来会让
144+/// 「等一会儿再来」用在等不回来的地方。判据窄一点,宁可退回「其他」。
123145 fn failure(
124146 kind: &str,
125147 status: reqwest::StatusCode,
@@ -127,6 +149,18 @@
127149 body: &serde_json::Value,
128150 ) -> anyhow::Error {
129151 let detail = err_detail(body);
152+ // **欠费要先判,而且不能只看状态码。**
153+ //
154+ // 402 是标准答案(SiliconFlow 用它),但 OpenAI 的余额耗尽走的是 **429**,
155+ // 靠 body 里的 `insufficient_quota` 区分。只按状态码分类的话,一个没钱的
156+ // OpenAI 账号会被当成限流,然后无限退避重试一个永远不会好的东西——
157+ // 而退避越久,症状越像"端点慢",越查不到根上。
158+ if status == reqwest::StatusCode::PAYMENT_REQUIRED || says_out_of_credit(body) {
159+ return anyhow::Error::new(OutOfCredit {
160+ status: status.as_u16(),
161+ detail,
162+ });
163+ }
130164 if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
131165 return anyhow::Error::new(RateLimited {
132166 status: status.as_u16(),
@@ -493,6 +527,21 @@
493527 .to_string()
494528 }
495529
530+/// 响应体说不说这是余额问题。
531+///
532+/// **给 429 用的**:OpenAI 用同一个状态码表示「太快了」和「没钱了」,
533+/// `error.code` 或 `error.type` 里的 `insufficient_quota` 才是分界。
534+///
535+/// 只认这一个标识、不去匹配 message 的自由文本:措辞会改、会本地化,
536+/// 而 `code` 是接口契约的一部分。认不出来就退回按状态码判,那是安全的一侧
537+/// (当成限流退避几次,比当成欠费直接放弃温和)。
538+fn says_out_of_credit(body: &serde_json::Value) -> bool {
539+ ["code", "type"]
540+ .iter()
541+ .filter_map(|k| body["error"][k].as_str())
542+ .any(|v| v == "insufficient_quota")
543+}
544+
496545 #[cfg(test)]
497546 mod tests {
498547 use super::*;
@@ -635,6 +684,36 @@
635684 );
636685 }
637686
687+ /// **429 不一定是限流。** OpenAI 用同一个状态码表示「太快了」和「没钱了」,
688+ /// 分界在 `error.code`。只按状态码分类的话,一个没钱的账号会被无限退避
689+ /// 重试——而重试越久,症状越像「端点慢」,越查不到根上。
690+ #[test]
691+ fn a_429_that_says_insufficient_quota_is_a_billing_problem() {
692+ let body = serde_json::json!({
693+ "error": { "message": "You exceeded your current quota", "code": "insufficient_quota" }
694+ });
695+ let e = failure("LLM", reqwest::StatusCode::TOO_MANY_REQUESTS, None, &body);
696+ assert!(out_of_credit(&e).is_some(), "该判成欠费");
697+ assert!(rate_limited(&e).is_none(), "不该判成限流");
698+ }
699+
700+ /// 402 是标准答案,SiliconFlow 用的就是它。
701+ #[test]
702+ fn a_402_is_a_billing_problem() {
703+ let body = serde_json::json!({ "message": "Sorry, your account balance is insufficient" });
704+ let e = failure("LLM", reqwest::StatusCode::PAYMENT_REQUIRED, None, &body);
705+ assert!(out_of_credit(&e).is_some());
706+ }
707+
708+ /// 反面:不带那个标识的 429 还是限流,别把会自己好的事判成要人动手。
709+ #[test]
710+ fn a_plain_429_is_still_a_rate_limit() {
711+ let body = serde_json::json!({ "error": { "message": "TPM limit reached" } });
712+ let e = failure("LLM", reqwest::StatusCode::TOO_MANY_REQUESTS, None, &body);
713+ assert!(rate_limited(&e).is_some());
714+ assert!(out_of_credit(&e).is_none());
715+ }
716+
638717 /// 反面:别的 4xx 不是限流。密钥错了重试一万次还是错。
639718 #[tokio::test]
640719 async fn an_auth_failure_is_not_a_rate_limit() {
modified crates/utopia-server/src/alerting.rs +36 −5
@@ -56,12 +56,19 @@
5656 /// 一次任务失败该报哪一类告警,报不报。
5757 ///
5858 /// **抽成纯函数是为了能测**:`observe_job_failure` 要 `AppState` 和一个真数据库,
59-/// 而这里要守的是分类本身——限流不能被当成端点不可达,反之亦然。两者该做的事
60-/// 完全不同:一个去查网络或地址,一个去降并发或升配额。
59+/// 而这里要守的是分类本身。三类该做的事完全不同——欠费要人去充值,限流要降并发
60+/// 或升配额,端点不可达要查网络和地址。**混成一条会把人指向错的地方,比不报还费时间。**
6161 ///
62-/// **限流排在前面。** 两者今天互斥,但顺序反过来的话,将来谁给 `Unreachable`
63-/// 加一层包装就会把限流吞进去,而症状是这条告警再也不出现——没有任何测试会红。
62+/// 顺序是「更该先说的放前面」,而不是判据有重叠:类型本身互斥,重叠在状态码上
63+/// (OpenAI 的余额耗尽也回 429),那一层已经在 `utopia_llm::failure` 里分开了。
6464 fn alert_for(err: &anyhow::Error) -> Option<(&'static str, &'static str)> {
65+ // 欠费排在限流之前。两者的状态码会重叠——OpenAI 的余额耗尽也回 429——
66+ // 而分类在 `utopia_llm::failure` 里已经做完,这里的顺序只是把「更该先说
67+ // 的那件事」放前面:没钱是人必须动手的,限流不是
68+ if utopia_llm::out_of_credit(err).is_some() {
69+ // `error`:它不会自己好,在有人充值之前抽取一直是停的
70+ return Some((alerts::kind::LLM_OUT_OF_CREDIT, "error"));
71+ }
6572 if utopia_llm::rate_limited(err).is_some() {
6673 // `warning` 不是 `error`:配额会自己恢复,端点挂了不会
6774 return Some((alerts::kind::LLM_RATE_LIMITED, "warning"));
@@ -135,7 +142,7 @@
135142 #[cfg(test)]
136143 mod tests {
137144 use super::alert_for;
138- use utopia_llm::RateLimited;
145+ use utopia_llm::{OutOfCredit, RateLimited};
139146 use utopia_store::alerts::kind;
140147
141148 /// 限流与端点不可达是两类事,报的告警必须分开。
@@ -167,6 +174,30 @@
167174 assert_eq!(alert_for(&err), Some((kind::LLM_RATE_LIMITED, "warning")));
168175 }
169176
177+ /// 欠费与限流必须分开:一个要人去充值,一个等一会儿就好。
178+ ///
179+ /// 报错了方向的代价是实打实的——实测 14 篇文档因为欠费整篇失败,
180+ /// 而当时唯一能知道原因的办法是去数据库里翻 `graph_error`。
181+ #[test]
182+ fn out_of_credit_is_not_a_rate_limit() {
183+ let err = anyhow::Error::new(OutOfCredit {
184+ status: 402,
185+ detail: "Sorry, your account balance is insufficient".into(),
186+ });
187+ assert_eq!(alert_for(&err), Some((kind::LLM_OUT_OF_CREDIT, "error")));
188+ }
189+
190+ /// 判定同样要穿透 context 层。
191+ #[test]
192+ fn out_of_credit_survives_context_layers() {
193+ let err = anyhow::Error::new(OutOfCredit {
194+ status: 402,
195+ detail: "insufficient balance".into(),
196+ })
197+ .context("bootstrap_ontology 失败");
198+ assert_eq!(alert_for(&err), Some((kind::LLM_OUT_OF_CREDIT, "error")));
199+ }
200+
170201 /// 反面:普通失败不该报告警,否则每一次解析错都弹一条,人会学会忽略它。
171202 #[test]
172203 fn an_ordinary_failure_raises_nothing() {
modified crates/utopia-store/src/alerts.rs +6 −0
@@ -39,6 +39,12 @@
3939 /// 真的被配额挡在外面时,没有这条告警就没有任何人知道——
4040 /// 实测一次跑测里 4 篇失败,一半是不可达(有告警),一半是限流(静默)。
4141 pub const LLM_RATE_LIMITED: &str = "llm.rate_limited";
42+ /// 系统级:账号付不起请求——欠费或套餐配额用尽。`min_role = admin`
43+ ///
44+ /// **`error` 而不是 `warning`,正因为它跟限流的区别是「会不会自己好」**:
45+ /// 配额到点重置,欠费不会。在有人去充值之前,这个部署的抽取与向量化
46+ /// 一直是停的。
47+ pub const LLM_OUT_OF_CREDIT: &str = "llm.out_of_credit";
4248 /// 库级:数据源挂上了,它的库表结构却没摄进来。`min_role = admin`
4349 ///
4450 /// **这一条描述的不是那次失败,是它留下的状态**:源挂着,而问数看不见它有
modified web/src/i18n/en.ts +4 −0
@@ -168,6 +168,10 @@
168168 title: "The model endpoint is rate limiting us",
169169 hint: "Documents were retried and still turned away, so some are missing facts. Lower model concurrency in system settings, or raise the quota on the account.",
170170 },
171+ "llm.out_of_credit": {
172+ title: "The model account cannot pay for requests",
173+ hint: "Extraction and embedding are stopped and will not resume on their own. Top up the account, or point system settings at an endpoint that can serve.",
174+ },
171175 } as Record<string, { title: string; hint: string } | undefined>,
172176 // 没见过的 kind 也要能显示:新告警源上线时前端可能还没更新
173177 unknownKind: (kind: string) => kind,
modified web/src/i18n/zh.ts +4 −0
@@ -149,6 +149,10 @@
149149 title: "模型端点在限流",
150150 hint: "退避重试之后仍然被挡回来,有文档因此缺了事实。去系统设置里降低模型并发,或者把账号配额升一档。",
151151 },
152+ "llm.out_of_credit": {
153+ title: "模型账号付不起请求",
154+ hint: "抽取与向量化已停摆,而且不会自己恢复。去给账号充值,或者在系统设置里换一个能用的端点。",
155+ },
152156 } as Record<string, { title: string; hint: string } | undefined>,
153157 unknownKind: (kind: string) => kind,
154158 },