Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions openspec/changes/surface-model-quota-errors/design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
## 设计
永久额度问题立即终止。上游窗口耗尽指向服务端恢复,钱包余额问题指向充值。暂时限流保留 429 与 Retry-After;ACEModel 短等待最多重试两次,长等待交给用户。已发往上游的未知结果仍保留既有结算保护。

已用实际 ACECode 通过公开网关验证 Responses 和 Chat Completions:钱包零余额、独立 Key 额度耗尽各请求一次后显示 402;持续 429 的对话请求共三次后结束。正常 Key 两种协议均成功。
7 changes: 7 additions & 0 deletions openspec/changes/surface-model-quota-errors/proposal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
## Why
用户遇到额度耗尽时可能持续重连,需要在当前回合收到可采取行动的错误。
## What Changes
- 区分钱包、独立 Key、上游窗口与临时限流。
- 为 ACEModel 限流提供有界重试及可读错误。
## Impact
影响 ACEModel 错误响应及 ACECode 的 OpenAI 兼容流式对话。
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
## ADDED Requirements

### Requirement: 明示额度与限流错误
系统 SHALL 区分用户余额耗尽、独立 Key 额度耗尽、上游用量窗口和临时请求限流,提供状态、错误码及恢复方式。

#### Scenario: 用户额度为零
- **WHEN** 已用尽额度的用户发起模型请求
- **THEN** 返回可读的终止错误,本回合不重新连接或扣费。

#### Scenario: 持续临时限流
- **WHEN** ACEModel 持续返回临时限流
- **THEN** ACECode 有界重试,显示限流原因并结束本回合;后续用户可主动重试。
3 changes: 3 additions & 0 deletions openspec/changes/surface-model-quota-errors/tasks.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## 交付
- [x] 1. 实现并测试本仓库的额度与限流合同。
- [x] 2. 验证实际客户端、部署状态与错误可见性。
12 changes: 9 additions & 3 deletions src/adapters/provider/openai_provider.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1972,18 +1972,25 @@ ChatResponse OpenAiCompatProvider::parse_sse_stream(
continue;
}

if (error_info.retryable) {
error_info.retry_max_attempts = -1;
if (auto delay = parse_retry_after_ms(header_value_ci(r.header, "Retry-After"))) {
error_info.server_retry_after_ms = *delay;
}
apply_acemodel_limit_policy(error_info, is_acemodel_request_endpoint("/chat/completions") ||
!header_value_ci(r.header, "X-ACEModel-Limit").empty(), attempt - 1);
}
if (error_info.retryable) {
const int delay_ms = retry_after_delay_ms(
r.header, attempt, error_info.status_code, error_info.raw_body);
error_info.retry_attempt = saturating_retry_attempt(attempt);
error_info.retry_max_attempts = -1;
error_info.retry_delay_ms = delay_ms;
LOG_WARN("Retrying streaming request after " +
provider_error_kind_to_string(error_info.kind) +
" failure; retry=" +
std::to_string(error_info.retry_attempt) +
" delay_ms=" + std::to_string(delay_ms) +
" max_attempts=unbounded");
" max_attempts=" + std::to_string(error_info.retry_max_attempts));
emit_retry_event(callback, error_info);
if (wait_for_retry(
std::chrono::milliseconds(delay_ms), abort_flag)) {
Expand All @@ -2005,7 +2012,6 @@ ChatResponse OpenAiCompatProvider::parse_sse_stream(

error_info.retry_attempt =
saturating_retry_attempt(attempt > 0 ? attempt - 1 : 0);
error_info.retry_max_attempts = 0;
emit_provider_error(callback, error_info);
return accumulated;
}
Expand Down
13 changes: 10 additions & 3 deletions src/adapters/provider/openai_responses.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -77,17 +77,24 @@ ProviderErrorInfo response_error(const Json& event, ProviderErrorKind kind,
if (result.request_id.empty()) result.request_id = text_field(payload, "request_id");
if (kind == ProviderErrorKind::Unknown) {
result.status_code = nonnegative_int(payload, "status_code");
const auto code = text_field(payload, "code");
auto code = text_field(payload, "code");
if (code.empty()) code = text_field(payload, "type");
const bool quota = provider_error_body_has_hard_quota(result.raw_body);
const bool throttle = code == "rate_limit_exceeded" || code == "rate_limit_reached" ||
code == "rate_limit_error";
if ((quota || throttle) && !code.empty()) {
result.display_message += " [" + code + "]";
}
if (result.status_code == 0) {
if (code == "rate_limit_exceeded" || code == "rate_limit_reached") {
if (throttle) {
result.status_code = 429;
} else if (code == "server_error" || code == "internal_server_error") {
result.status_code = 500;
} else if (code == "overloaded_error") {
result.status_code = 503;
}
}
result.retryable = !provider_error_body_has_hard_quota(result.raw_body) &&
result.retryable = !quota &&
provider_http_error_is_retryable(result.status_code, result.raw_body);
}
return result;
Expand Down
4 changes: 3 additions & 1 deletion src/adapters/provider/openai_responses_provider.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,9 @@ void OpenAiResponsesProvider::stream_impl(const std::vector<ChatMessage>& messag
if (!emitted_provisional_output && completion_events.empty() &&
remove_rejected_prompt_cache_key(body, url,
failure.status_code, failure.raw_body)) continue;
failure.retry_max_attempts = -1;
apply_acemodel_limit_policy(failure, is_acemodel_request_endpoint("/responses") ||
!header_value(upstream.header, "x-acemodel-limit").empty(), retry_number);
if (!failure.retryable) {
failure.retry_attempt = saturating_retry_attempt(retry_number);
emit_error(callback, failure);
Expand All @@ -476,7 +479,6 @@ void OpenAiResponsesProvider::stream_impl(const std::vector<ChatMessage>& messag
const auto delay = provider_retry_delay_ms(retry_number, server_delay,
provider_retry_max_delay_ms(failure.status_code, failure.raw_body));
failure.retry_attempt = saturating_retry_attempt(retry_number);
failure.retry_max_attempts = -1;
failure.retry_delay_ms = static_cast<int>(delay);
emit_error(callback, failure, StreamEventType::Retry);
if (wait_for_retry(std::chrono::milliseconds(delay), abort_flag)) {
Expand Down
28 changes: 26 additions & 2 deletions src/adapters/provider/retry_policy.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include "retry_policy.hpp"

#include "pa/pa_quirks.hpp"
#include "llm/llm_provider.hpp"

#include <curl/curl.h>
#include <nlohmann/json.hpp>
Expand Down Expand Up @@ -51,7 +52,8 @@ bool is_hard_quota_code(const std::string& value) {
code == "billing_hard_limit_reached" ||
code == "billing_not_active" ||
code == "credit_balance_too_low" ||
code == "hard_limit_reached";
code == "hard_limit_reached" || code == "upstream_quota_exhausted" ||
code == "usage_limit_reached" || code == "quota_exhausted";
}

// 429 报文的 message 明确说「额度 / 余额用完」时也算硬配额。起因(yubo2 反馈):
Expand Down Expand Up @@ -112,7 +114,7 @@ bool provider_error_body_has_hard_quota(const std::string& body) {
bool provider_http_error_is_retryable(int status_code,
const std::string& body) {
const bool hard_quota = provider_error_body_has_hard_quota(body);
if (status_code == 429 && hard_quota) {
if (hard_quota) {
return false;
}

Expand Down Expand Up @@ -242,6 +244,28 @@ std::int64_t provider_retry_delay_ms(
return (std::min)(delay, cap);
}

void apply_acemodel_limit_policy(ProviderErrorInfo& error, bool acemodel,
std::uint64_t retries_sent) {
if (!acemodel || !error.retryable ||
!provider_error_is_rate_limited(error.status_code, error.raw_body)) return;

constexpr int max_retries = 2;
error.retry_max_attempts = max_retries;
if (retries_sent < max_retries &&
error.server_retry_after_ms <= kProviderRateLimitRetryMaxDelayMs) return;

error.retryable = false;
std::string message = u8"请求受限(HTTP 429)。";
if (error.server_retry_after_ms > 0) {
const auto ms = error.server_retry_after_ms;
message += u8"请在 " + std::to_string(ms / 1000 + (ms % 1000 != 0)) +
u8" 秒后重试。";
} else {
message += u8"请稍后重试。";
}
error.display_message = message + "\n" + error.display_message;
}

int saturating_retry_attempt(std::uint64_t retry_number) {
const auto max_int =
static_cast<std::uint64_t>((std::numeric_limits<int>::max)());
Expand Down
6 changes: 6 additions & 0 deletions src/adapters/provider/retry_policy.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ constexpr std::int64_t kProviderRateLimitRetryMaxDelayMs = 60 * 1000;
// Exact billing/quota codes make an otherwise retryable 429 terminal.
bool provider_error_body_has_hard_quota(const std::string& body);

struct ProviderErrorInfo;
// Apply the ACEModel throttle budget before emitting Retry or a terminal Error.
// Other transient failures retain their existing recovery policy.
void apply_acemodel_limit_policy(ProviderErrorInfo& error, bool acemodel,
std::uint64_t retries_sent);

// Shared allowlist for streaming and non-streaming provider requests.
// 状态码不可信的网关(src/adapters/pa)按报文文案兜底:写明上下文超限的一律
// 不重试(要走压缩 / 兜底链,重发同一个超大请求没有意义),写明限流的一律
Expand Down
28 changes: 28 additions & 0 deletions tests/provider/openai_responses_provider_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,34 @@ TEST(OpenAiResponsesProviderTest, TruncatedStreamResetsProvisionalOutputAndCalls
EXPECT_EQ(count_events(events, StreamEventType::Error), 0);
}

TEST(OpenAiResponsesProviderTest, AceModelThrottleStopsWithCodeAndHonorsLongWait) {
for (const auto& hint : {std::string("0"), std::string("120")}) {
std::atomic<int> requests{0};
LocalHttpServer server([&](httplib::Server& http) {
http.Post("/v1/responses", [&](const httplib::Request&, httplib::Response& r) {
// A fourth request must end the test even if the budget regresses.
r.status = ++requests > 3 ? 400 : 429;
r.set_header("X-ACEModel-Limit", "rate_limit_reached");
r.set_header("Retry-After", hint);
r.set_content(R"({"error":{"code":"rate_limit_reached"}})", "application/json");
});
});
OpenAiResponsesProvider provider(server.url(), "", "test-model", 3000);
std::atomic<bool> abort{false};
std::vector<StreamEvent> events;
provider.chat_stream({user_message()}, {}, [&](const StreamEvent& event) {
events.push_back(event);
if (hint == "120" && event.type == StreamEventType::Retry) abort.store(true);
}, &abort);
const auto* error = last_event(events, StreamEventType::Error);
ASSERT_NE(error, nullptr);
EXPECT_EQ(requests.load(), hint == "0" ? 3 : 1);
EXPECT_FALSE(error->provider_error.retryable);
EXPECT_NE(error->error.find("rate_limit_reached"), std::string::npos);
EXPECT_EQ(error->provider_error.status_code, 429);
}
}

TEST(OpenAiResponsesProviderTest, HardQuotaAndMalformedJsonAreTerminalWithDiagnostics) {
const std::vector<std::pair<int, std::string>> failures{
{429, R"({"error":{"code":"insufficient_quota","message":"buy credits"}})"},
Expand Down
5 changes: 4 additions & 1 deletion tests/provider/openai_responses_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,10 @@ TEST(OpenAiResponsesTest, StructuredErrorsPreserveQuotaClassificationAndDiagnost
EXPECT_EQ(result.finish_reason, "error");
EXPECT_EQ(result.provider_error.provider, "openai");
EXPECT_EQ(result.provider_error.raw_body, wire.dump());
EXPECT_EQ(result.provider_error.display_message, "upstream failed");
const bool limit = std::string(code) == "rate_limit_exceeded" ||
std::string(code) == "insufficient_quota";
EXPECT_EQ(result.provider_error.display_message,
limit ? "upstream failed [" + std::string(code) + "]" : "upstream failed");
EXPECT_EQ(result.provider_error.retryable,
std::string(code) == "server_error" || std::string(code) == "rate_limit_exceeded");
}
Expand Down
Loading